@profullstack/threatcrush 0.13.63 → 0.13.65

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
@@ -23425,9 +23425,9 @@ var source_default = chalk;
23425
23425
 
23426
23426
  // src/index.ts
23427
23427
  var import_readline = __toESM(require("readline"));
23428
- var import_node_child_process25 = require("child_process");
23429
- var import_node_fs60 = require("fs");
23430
- var import_node_path46 = require("path");
23428
+ var import_node_child_process26 = require("child_process");
23429
+ var import_node_fs61 = require("fs");
23430
+ var import_node_path47 = require("path");
23431
23431
  var import_node_os18 = require("os");
23432
23432
 
23433
23433
  // src/commands/monitor.ts
@@ -30243,6 +30243,39 @@ function parseNginxLog(line2) {
30243
30243
  fields
30244
30244
  };
30245
30245
  }
30246
+ function parseCaddyAccessLog(line2) {
30247
+ let entry;
30248
+ try {
30249
+ entry = JSON.parse(line2);
30250
+ } catch {
30251
+ return null;
30252
+ }
30253
+ if (entry.logger !== "http.log.access") return null;
30254
+ const request = entry.request;
30255
+ if (!request || typeof request !== "object" || Array.isArray(request)) return null;
30256
+ const req = request;
30257
+ const host = typeof req.host === "string" ? req.host.toLowerCase() : "";
30258
+ if (host !== "agent.database.pit.world") return null;
30259
+ const required = [req.method, req.uri, entry.status, entry.size];
30260
+ if (required.some((value) => typeof value !== "string" && typeof value !== "number")) return null;
30261
+ const timestamp = typeof entry.ts === "number" ? new Date(entry.ts * 1e3) : /* @__PURE__ */ new Date();
30262
+ return {
30263
+ timestamp: Number.isNaN(timestamp.getTime()) ? /* @__PURE__ */ new Date() : timestamp,
30264
+ raw: line2,
30265
+ source: "nginx",
30266
+ fields: {
30267
+ ip: typeof req.client_ip === "string" ? req.client_ip : typeof req.remote_ip === "string" ? req.remote_ip : "",
30268
+ method: String(req.method),
30269
+ path: String(req.uri).split("?")[0],
30270
+ protocol: typeof req.proto === "string" ? req.proto : "",
30271
+ status: String(entry.status),
30272
+ size: String(entry.size),
30273
+ referer: "",
30274
+ user_agent: "",
30275
+ host
30276
+ }
30277
+ };
30278
+ }
30246
30279
  function parseAuthLog(line2) {
30247
30280
  const match = line2.match(AUTH_REGEX);
30248
30281
  if (!match) return null;
@@ -30289,10 +30322,20 @@ function sshdPeerIp(message) {
30289
30322
  function classifySshAuth(entry) {
30290
30323
  const { ip, user, message } = entry.fields;
30291
30324
  if (/failed password/i.test(message)) {
30292
- return { severity: "high", message: `Failed SSH login for ${user || "unknown"} from ${ip || "unknown"}`, source_ip: ip };
30325
+ return {
30326
+ severity: "high",
30327
+ message: `Failed SSH login for ${user || "unknown"} from ${ip || "unknown"}`,
30328
+ source_ip: ip,
30329
+ ...user ? { details: { user } } : {}
30330
+ };
30293
30331
  }
30294
30332
  if (/invalid user/i.test(message)) {
30295
- return { severity: "high", message: `Invalid SSH user: ${user || "unknown"} from ${ip || "unknown"}`, source_ip: ip };
30333
+ return {
30334
+ severity: "high",
30335
+ message: `Invalid SSH user: ${user || "unknown"} from ${ip || "unknown"}`,
30336
+ source_ip: ip,
30337
+ ...user ? { details: { user } } : {}
30338
+ };
30296
30339
  }
30297
30340
  if (/accepted/i.test(message)) {
30298
30341
  const login2 = parseAcceptedLogin(message);
@@ -30301,7 +30344,7 @@ function classifySshAuth(entry) {
30301
30344
  severity: "info",
30302
30345
  message: `SSH login accepted for ${login2?.user || user || "unknown"}`,
30303
30346
  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 } : {} } } : {}
30347
+ ...login2 ? { details: { user: login2.user, 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
30348
  };
30306
30349
  }
30307
30350
  return null;
@@ -30435,6 +30478,7 @@ function parseConfigText(raw) {
30435
30478
  update: parsed.update,
30436
30479
  threat_feeds: parsed.threat_feeds,
30437
30480
  privileged: parsed.privileged,
30481
+ command_history: parsed.command_history,
30438
30482
  lightning: parsed.lightning,
30439
30483
  storage: parsed.storage,
30440
30484
  // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
@@ -30494,6 +30538,7 @@ function generateDefaultConfig(detectedServices) {
30494
30538
  // when the section is absent.
30495
30539
  cloud: { enabled: true, min_severity: "medium" },
30496
30540
  update: { auto: true, interval: "6h", min_age: "2h" },
30541
+ command_history: { enabled: false },
30497
30542
  // Reporting to shared reputation feeds (PRD 0015). On by default but inert
30498
30543
  // until a key is set: nothing is reported without ABUSEIPDB_API_KEY or the
30499
30544
  // key below, and only corroborated, handshake-verified sources ever are.
@@ -37584,6 +37629,14 @@ function isSuppressed(suppressions, index, ruleId) {
37584
37629
  if (!rules) return false;
37585
37630
  return rules.has("*") || rules.has(ruleId);
37586
37631
  }
37632
+ function pemPlaceholder(lines, index) {
37633
+ const first = lines[index] ?? "";
37634
+ const header2 = /-----BEGIN ((?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?)-----/.exec(first);
37635
+ if (!header2) return false;
37636
+ const tail = [first.slice(header2.index + header2[0].length), ...lines.slice(index + 1, index + 21)].join("\n").replace(/\\n/g, "\n");
37637
+ const end = tail.indexOf(`-----END ${header2[1]}-----`);
37638
+ return end >= 0 && ["your-pem-body-here", "your-private-key-here", "your-private-key-body-here"].includes(tail.slice(0, end).trim().toLowerCase());
37639
+ }
37587
37640
  function isTestPath(relativePath) {
37588
37641
  const p = relativePath.replace(/\\/g, "/");
37589
37642
  return /(?:^|\/)(?:tests?|__tests__|__mocks__|spec|specs|fixtures?|mocks?|e2e|testdata|testutils?|harness)\//i.test(p) || /(?:^|\/)(?:test|conftest)_[^/]+$/i.test(p) || /[._-](?:test|spec)\.[a-z]+$/i.test(p) || /_test\.[a-z]+$/i.test(p);
@@ -37779,7 +37832,7 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
37779
37832
  test: inTests,
37780
37833
  "test-block": inlineTests.has(index),
37781
37834
  suppressed: foreignSecurityMark(line2),
37782
- placeholder: isPlaceholderAttribute(line2, value),
37835
+ placeholder: isPlaceholderAttribute(line2, value) || rule.id === "secret-private-key" && pemPlaceholder(lines, index),
37783
37836
  "self-describing": rule.keywordShaped === true && describesItsOwnKey(line2, value)
37784
37837
  });
37785
37838
  findings2.push({
@@ -41468,16 +41521,16 @@ async function sshConnect(options) {
41468
41521
  }
41469
41522
 
41470
41523
  // src/commands/daemon.ts
41471
- var import_node_child_process18 = require("child_process");
41472
- var import_node_fs48 = require("fs");
41473
- var import_node_path37 = require("path");
41524
+ var import_node_child_process19 = require("child_process");
41474
41525
  var import_node_fs49 = require("fs");
41526
+ var import_node_path38 = require("path");
41527
+ var import_node_fs50 = require("fs");
41475
41528
 
41476
41529
  // src/daemon/index.ts
41477
- var import_node_fs47 = require("fs");
41478
- var import_node_child_process17 = require("child_process");
41530
+ var import_node_fs48 = require("fs");
41531
+ var import_node_child_process18 = require("child_process");
41479
41532
  var import_node_os14 = require("os");
41480
- var import_node_path36 = require("path");
41533
+ var import_node_path37 = require("path");
41481
41534
  var import_node_util4 = require("util");
41482
41535
  init_paths();
41483
41536
 
@@ -41796,8 +41849,11 @@ var DEFAULT_SOURCES = [
41796
41849
  { path: "/var/log/auth.log", module: "ssh-guard", category: "auth" },
41797
41850
  { path: "/var/log/secure", module: "ssh-guard", category: "auth" },
41798
41851
  { path: "/var/log/nginx/access.log", module: "log-watcher", category: "web" },
41852
+ { path: "/var/log/caddy/agent.database.pit.world.access.log", module: "log-watcher", category: "web" },
41799
41853
  { path: "/var/log/syslog", module: "log-watcher", category: "system" }
41800
41854
  ];
41855
+ var AGENTDB_API_PATH = /^\/v1\/(?:list_databases|inspect_schema|query_readonly|explain_query|cluster_health|backup_status|audit\/events|backup\/(?:create|verify)|tokens(?:\/revoke)?)$/;
41856
+ var AGENTDB_HOST = "agent.database.pit.world";
41801
41857
  var LogWatcher = class {
41802
41858
  constructor(bus2, sources = DEFAULT_SOURCES) {
41803
41859
  this.bus = bus2;
@@ -41858,7 +41914,8 @@ var LogWatcher = class {
41858
41914
  });
41859
41915
  }
41860
41916
  process(line2, src) {
41861
- const parsed = autoDetectParser(line2);
41917
+ const caddy = parseCaddyAccessLog(line2);
41918
+ const parsed = caddy ?? autoDetectParser(line2);
41862
41919
  if (!parsed) return;
41863
41920
  let severity = "info";
41864
41921
  let message = line2;
@@ -41876,7 +41933,7 @@ var LogWatcher = class {
41876
41933
  ({ severity, message, source_ip: sourceIp } = verdict);
41877
41934
  if (verdict.details) Object.assign(details, verdict.details);
41878
41935
  } else if (parsed.source === "nginx") {
41879
- const entry = parseNginxLog(line2);
41936
+ const entry = caddy ?? parseNginxLog(line2);
41880
41937
  if (!entry) return;
41881
41938
  sourceIp = entry.fields.ip;
41882
41939
  const status = parseInt(entry.fields.status, 10);
@@ -41890,6 +41947,16 @@ var LogWatcher = class {
41890
41947
  if (Number.isFinite(status)) details.status = status;
41891
41948
  if (entry.fields.method) details.method = entry.fields.method;
41892
41949
  if (entry.fields.path) details.url = entry.fields.path.slice(0, 2048);
41950
+ const agentDbHost = entry.fields.host?.toLowerCase();
41951
+ const isAgentDbApi = AGENTDB_API_PATH.test(reqPath) && (!agentDbHost || agentDbHost === AGENTDB_HOST);
41952
+ if (isAgentDbApi) {
41953
+ details.url = reqPath;
41954
+ details.service = "agentdb";
41955
+ const responseBytes = Number(entry.fields.size);
41956
+ if (Number.isSafeInteger(responseBytes) && responseBytes >= 0) {
41957
+ details.response_bytes = responseBytes;
41958
+ }
41959
+ }
41893
41960
  if (crs.score > 0) {
41894
41961
  Object.assign(details, {
41895
41962
  attack_type: crs.attackType,
@@ -41900,7 +41967,10 @@ var LogWatcher = class {
41900
41967
  }
41901
41968
  if (attack) {
41902
41969
  severity = attack;
41903
- message = `Attack [${type}]: ${entry.fields.method} ${entry.fields.path}`;
41970
+ message = `Attack [${type}]: ${entry.fields.method} ${isAgentDbApi ? reqPath : entry.fields.path}`;
41971
+ } else if (isAgentDbApi) {
41972
+ severity = status >= 500 ? "medium" : status >= 400 ? "low" : "info";
41973
+ message = `AgentDB API ${status}: ${entry.fields.method} ${reqPath}`;
41904
41974
  } else if (status >= 500) {
41905
41975
  severity = "medium";
41906
41976
  message = `Server error ${status}: ${entry.fields.method} ${entry.fields.path}`;
@@ -41933,9 +42003,50 @@ var LogWatcher = class {
41933
42003
  }
41934
42004
  };
41935
42005
 
42006
+ // src/daemon/watchers/journal-provenance.ts
42007
+ var JournalProvenance = class {
42008
+ peers = /* @__PURE__ */ new Map();
42009
+ fields(entry) {
42010
+ const details = {};
42011
+ for (const [source, dest] of Object.entries({ _PID: "pid", _BOOT_ID: "boot_id", __CURSOR: "journal_cursor", _AUDIT_SESSION: "audit_session", _AUDIT_LOGINUID: "login_uid" })) {
42012
+ if (typeof entry[source] === "string") details[dest] = entry[source].slice(0, 200);
42013
+ }
42014
+ const trusted = entry._UID === "0" && ["sshd", "sshd-session", "sshd-auth"].includes(String(entry._COMM));
42015
+ if (!trusted || typeof entry.MESSAGE !== "string") return { details };
42016
+ const at = Number(entry.__REALTIME_TIMESTAMP) / 1e3;
42017
+ const key = typeof entry._BOOT_ID === "string" && typeof entry._PID === "string" ? `${entry._BOOT_ID}:${entry._PID}` : null;
42018
+ for (const [k, peer2] of this.peers) if (!Number.isFinite(at) || at - peer2.at > 12e4 || at < peer2.at) this.peers.delete(k);
42019
+ const direct = sshdPeerIp(entry.MESSAGE);
42020
+ if (direct && key && Number.isFinite(at)) {
42021
+ this.peers.delete(key);
42022
+ this.peers.set(key, { ip: direct, at });
42023
+ if (this.peers.size > 512) this.peers.delete(this.peers.keys().next().value);
42024
+ }
42025
+ const peer = key ? this.peers.get(key) : void 0;
42026
+ const source_ip = direct ?? (peer && Number.isFinite(at) && at >= peer.at && at - peer.at <= 12e4 ? peer.ip : void 0);
42027
+ if (source_ip) details.source_ip_basis = direct ? "current sshd record" : "same boot and sshd PID within 120 seconds";
42028
+ return { ...source_ip ? { source_ip } : {}, details };
42029
+ }
42030
+ };
42031
+
41936
42032
  // src/daemon/watchers/journal-watcher.ts
41937
42033
  var import_node_child_process6 = require("child_process");
41938
42034
  var SSHD_COMMS = ["sshd", "sshd-session"];
42035
+ var accountNames = /* @__PURE__ */ new Map();
42036
+ function accountNameForUid(value) {
42037
+ if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
42038
+ if (accountNames.has(value)) return accountNames.get(value) ?? null;
42039
+ const result = (0, import_node_child_process6.spawnSync)("getent", ["passwd", value], {
42040
+ encoding: "utf-8",
42041
+ timeout: 1e3,
42042
+ maxBuffer: 4096,
42043
+ stdio: ["ignore", "pipe", "ignore"]
42044
+ });
42045
+ const name = result.status === 0 ? result.stdout.split(":", 1)[0] : "";
42046
+ const resolved = /^[a-zA-Z0-9_.@-]{1,256}$/.test(name) ? name : null;
42047
+ accountNames.set(value, resolved);
42048
+ return resolved;
42049
+ }
41939
42050
  function isSshdRecord(entry) {
41940
42051
  return entry._UID === "0" && SSHD_COMMS.includes(entry._COMM);
41941
42052
  }
@@ -41944,6 +42055,7 @@ function sshEventFromJournal(entry) {
41944
42055
  const timestamp = realtimeToDate(entry.__REALTIME_TIMESTAMP) || /* @__PURE__ */ new Date();
41945
42056
  const verdict = classifySshAuth(parseAuthMessage(entry._COMM, entry.MESSAGE, timestamp));
41946
42057
  if (!verdict) return null;
42058
+ const systemAccount = accountNameForUid(entry._UID);
41947
42059
  return {
41948
42060
  timestamp,
41949
42061
  module: "ssh-guard",
@@ -41951,7 +42063,12 @@ function sshEventFromJournal(entry) {
41951
42063
  severity: verdict.severity,
41952
42064
  message: verdict.message,
41953
42065
  source_ip: verdict.source_ip,
41954
- ...verdict.details ? { details: verdict.details } : {}
42066
+ details: {
42067
+ ...verdict.details ?? {},
42068
+ ...typeof entry._UID === "string" && /^\d+$/.test(entry._UID) ? { system_uid: entry._UID } : {},
42069
+ ...systemAccount ? { system_account: systemAccount } : {},
42070
+ ...typeof entry._COMM === "string" ? { process: entry._COMM } : {}
42071
+ }
41955
42072
  };
41956
42073
  }
41957
42074
  function sshdLineFromJournal(entry) {
@@ -41971,6 +42088,7 @@ var JournalWatcher = class _JournalWatcher {
41971
42088
  buffer = "";
41972
42089
  sshdBuffer = "";
41973
42090
  moduleName = "user-journal";
42091
+ provenance = new JournalProvenance();
41974
42092
  active = false;
41975
42093
  // When the daemon runs as root (system mode), tail the SYSTEM journal so
41976
42094
  // we pick up sshd / sudo / kernel / UFW events. Falling back to --user
@@ -42029,8 +42147,9 @@ var JournalWatcher = class _JournalWatcher {
42029
42147
  this.sshdBuffer = this.drain(this.sshdBuffer + chunk2, (entry) => {
42030
42148
  const line2 = sshdLineFromJournal(entry);
42031
42149
  if (line2) this.bus.sshdLine?.(line2);
42150
+ const context = this.provenance.fields(entry);
42032
42151
  const event = sshEventFromJournal(entry);
42033
- if (event) this.emit(event);
42152
+ if (event) this.emit({ ...event, source_ip: event.source_ip ?? context.source_ip, details: { ...event.details, ...context.details } });
42034
42153
  });
42035
42154
  });
42036
42155
  child.on("error", () => {
@@ -42077,6 +42196,7 @@ var JournalWatcher = class _JournalWatcher {
42077
42196
  return buffer;
42078
42197
  }
42079
42198
  handleEntry(entry) {
42199
+ const context = this.provenance.fields(entry);
42080
42200
  if (this.sshdProc && isSshdRecord(entry)) return;
42081
42201
  const message = entry.MESSAGE;
42082
42202
  if (!message) return;
@@ -42089,7 +42209,17 @@ var JournalWatcher = class _JournalWatcher {
42089
42209
  module: this.moduleName,
42090
42210
  category: "system",
42091
42211
  severity: bumpedSeverity,
42092
- message: `[${ident}] ${message}`.slice(0, 500)
42212
+ ...context.source_ip ? { source_ip: context.source_ip } : {},
42213
+ message: `[${ident}] ${message}`.slice(0, 500),
42214
+ details: {
42215
+ ...context.details,
42216
+ ...typeof entry._UID === "string" && /^\d+$/.test(entry._UID) ? { system_uid: entry._UID } : {},
42217
+ ...accountNameForUid(entry._UID) ? { system_account: accountNameForUid(entry._UID) } : {},
42218
+ ...typeof entry._COMM === "string" ? { process: entry._COMM } : {},
42219
+ ...typeof entry.SYSLOG_IDENTIFIER === "string" ? { identifier: entry.SYSLOG_IDENTIFIER } : {},
42220
+ ...typeof entry._PID === "string" ? { pid: entry._PID } : {},
42221
+ ...typeof entry._SYSTEMD_UNIT === "string" ? { unit: entry._SYSTEMD_UNIT } : {}
42222
+ }
42093
42223
  });
42094
42224
  }
42095
42225
  emit(event) {
@@ -43723,7 +43853,7 @@ function str2(value) {
43723
43853
  return typeof value === "string" && value ? value : void 0;
43724
43854
  }
43725
43855
  function detectionEvent(serverId, event) {
43726
- const { rule_id, username, user, description, ...rest } = event.details ?? {};
43856
+ const { rule_id, username, user, ssh_user, account, description, ...rest } = event.details ?? {};
43727
43857
  const title = event.module === "rule-engine" ? event.message.replace(/^\[DETECTION\]\s*/, "") : event.message;
43728
43858
  return {
43729
43859
  type: "detection",
@@ -43733,7 +43863,7 @@ function detectionEvent(serverId, event) {
43733
43863
  rule_id: str2(rule_id) ?? event.module,
43734
43864
  description: str2(description),
43735
43865
  source_ip: event.source_ip && (0, import_node_net8.isIP)(event.source_ip) ? event.source_ip : void 0,
43736
- username: str2(username) ?? str2(user),
43866
+ username: str2(username) ?? str2(user) ?? str2(ssh_user) ?? str2(account),
43737
43867
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
43738
43868
  detected_at: event.timestamp.toISOString()
43739
43869
  };
@@ -46019,10 +46149,325 @@ var PrivilegeWatch = class {
46019
46149
  }
46020
46150
  };
46021
46151
 
46022
- // src/daemon/workers/ssh-intrusion.ts
46152
+ // src/daemon/workers/command-history.ts
46023
46153
  var import_node_fs40 = require("fs");
46024
- var import_node_path31 = require("path");
46025
46154
  var import_node_child_process13 = require("child_process");
46155
+ var import_node_path31 = require("path");
46156
+ var import_node_zlib2 = require("zlib");
46157
+ var import_node_crypto10 = require("crypto");
46158
+ var POLL_MS3 = 6e4;
46159
+ var MAX_HISTORY_BYTES = 4 * 1024 * 1024;
46160
+ var MAX_COMPRESSED_HISTORY_BYTES = MAX_HISTORY_BYTES + 65536;
46161
+ var MAX_SNAPSHOTS = 96;
46162
+ var SNAPSHOT_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
46163
+ var HISTORY_TARGETS = {
46164
+ bash: [".bash_history"],
46165
+ zsh: [".zsh_history"],
46166
+ fish: [".local/share/fish/fish_history"],
46167
+ ksh: [".sh_history"]
46168
+ };
46169
+ function commandHistorySettings(section) {
46170
+ return { enabled: section?.enabled === true };
46171
+ }
46172
+ function historyAccounts() {
46173
+ let passwd;
46174
+ try {
46175
+ passwd = (0, import_node_child_process13.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
46176
+ } catch {
46177
+ try {
46178
+ passwd = (0, import_node_fs40.readFileSync)("/etc/passwd", "utf8");
46179
+ } catch {
46180
+ return [];
46181
+ }
46182
+ }
46183
+ const root = typeof process.getuid === "function" && process.getuid() === 0;
46184
+ return passwd.split("\n").flatMap((line2) => {
46185
+ const fields = line2.split(":");
46186
+ const uid = Number(fields[2]);
46187
+ const gid = Number(fields[3]);
46188
+ const name = fields[0] ?? "";
46189
+ const home = fields[5] ?? "";
46190
+ const shell = fields[6] ?? "";
46191
+ if (!Number.isInteger(uid) || !Number.isInteger(gid) || !(0, import_node_path31.isAbsolute)(home) || home === "/" || home.split("/").includes("..")) return [];
46192
+ if (root ? uid !== 0 && uid < 1e3 : uid !== process.getuid?.()) return [];
46193
+ if (!HISTORY_TARGETS[(0, import_node_path31.basename)(shell)]) return [];
46194
+ return [{ uid, gid, name, home, shell }];
46195
+ });
46196
+ }
46197
+ function historyWritableHomes() {
46198
+ return [...new Set(historyAccounts().map((account) => account.home))].filter((home) => /^\/[A-Za-z0-9._/-]+$/.test(home));
46199
+ }
46200
+ function descriptorPath(directoryFd, name) {
46201
+ return `/proc/self/fd/${directoryFd}/${name}`;
46202
+ }
46203
+ function openDirectoryChain(path2) {
46204
+ if (!(0, import_node_path31.isAbsolute)(path2) || path2.split(import_node_path31.sep).includes("..")) throw new Error("directory path is not a safe absolute path");
46205
+ const flags = import_node_fs40.constants.O_RDONLY | import_node_fs40.constants.O_DIRECTORY | (import_node_fs40.constants.O_NOFOLLOW ?? 0);
46206
+ let fd = (0, import_node_fs40.openSync)("/", flags);
46207
+ try {
46208
+ for (const part of path2.split(import_node_path31.sep).filter((item) => item && item !== ".")) {
46209
+ const next = (0, import_node_fs40.openSync)(descriptorPath(fd, part), flags);
46210
+ (0, import_node_fs40.closeSync)(fd);
46211
+ fd = next;
46212
+ }
46213
+ return fd;
46214
+ } catch (error2) {
46215
+ (0, import_node_fs40.closeSync)(fd);
46216
+ throw error2;
46217
+ }
46218
+ }
46219
+ function readExact(fd, size) {
46220
+ const data = Buffer.alloc(size);
46221
+ let offset = 0;
46222
+ while (offset < data.length) {
46223
+ const read = (0, import_node_fs40.readSync)(fd, data, offset, data.length - offset, offset);
46224
+ if (read === 0) break;
46225
+ offset += read;
46226
+ }
46227
+ return offset === data.length ? data : null;
46228
+ }
46229
+ function privateDirectory(path2) {
46230
+ (0, import_node_fs40.mkdirSync)(path2, { recursive: true, mode: 448 });
46231
+ const stat = (0, import_node_fs40.lstatSync)(path2);
46232
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("history storage path is not a directory");
46233
+ (0, import_node_fs40.chmodSync)(path2, 448);
46234
+ }
46235
+ function safeReadHistory(directoryFd, name, uid) {
46236
+ const noFollow = import_node_fs40.constants.O_NOFOLLOW ?? 0;
46237
+ const fd = (0, import_node_fs40.openSync)(descriptorPath(directoryFd, name), import_node_fs40.constants.O_RDONLY | noFollow);
46238
+ try {
46239
+ const opened = (0, import_node_fs40.fstatSync)(fd);
46240
+ if (!opened.isFile() || opened.nlink !== 1 || opened.uid !== uid) return null;
46241
+ if (opened.size > MAX_HISTORY_BYTES) throw new Error(`history file exceeds ${MAX_HISTORY_BYTES} bytes`);
46242
+ const data = readExact(fd, opened.size);
46243
+ if (data === null) return null;
46244
+ const after = (0, import_node_fs40.fstatSync)(fd);
46245
+ if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs) return null;
46246
+ return data;
46247
+ } finally {
46248
+ (0, import_node_fs40.closeSync)(fd);
46249
+ }
46250
+ }
46251
+ function atomicWrite(path2, data, mode = 384, owner, parentFd) {
46252
+ const dirFd = parentFd ?? openDirectoryChain((0, import_node_path31.dirname)(path2));
46253
+ const ownsDirFd = parentFd === void 0;
46254
+ const name = (0, import_node_path31.basename)(path2);
46255
+ const temp = descriptorPath(dirFd, `${name}.${(0, import_node_crypto10.randomUUID)()}.tmp`);
46256
+ const destination = descriptorPath(dirFd, name);
46257
+ const noFollow = import_node_fs40.constants.O_NOFOLLOW ?? 0;
46258
+ let fd;
46259
+ try {
46260
+ fd = (0, import_node_fs40.openSync)(temp, import_node_fs40.constants.O_WRONLY | import_node_fs40.constants.O_CREAT | import_node_fs40.constants.O_EXCL | noFollow, mode);
46261
+ let offset = 0;
46262
+ while (offset < data.length) offset += (0, import_node_fs40.writeSync)(fd, data, offset, data.length - offset);
46263
+ (0, import_node_fs40.fchmodSync)(fd, mode);
46264
+ if (owner && typeof process.getuid === "function" && process.getuid() === 0) {
46265
+ (0, import_node_fs40.fchownSync)(fd, owner.uid, owner.gid);
46266
+ }
46267
+ (0, import_node_fs40.fsyncSync)(fd);
46268
+ (0, import_node_fs40.closeSync)(fd);
46269
+ fd = void 0;
46270
+ (0, import_node_fs40.renameSync)(temp, destination);
46271
+ } catch (error2) {
46272
+ if (fd !== void 0) {
46273
+ try {
46274
+ (0, import_node_fs40.closeSync)(fd);
46275
+ } catch {
46276
+ }
46277
+ }
46278
+ try {
46279
+ (0, import_node_fs40.unlinkSync)(temp);
46280
+ } catch {
46281
+ }
46282
+ throw error2;
46283
+ } finally {
46284
+ if (ownsDirFd) (0, import_node_fs40.closeSync)(dirFd);
46285
+ }
46286
+ }
46287
+ function readCurrentBackup(path2) {
46288
+ let fd;
46289
+ try {
46290
+ const parentFd = openDirectoryChain((0, import_node_path31.dirname)(path2));
46291
+ try {
46292
+ fd = (0, import_node_fs40.openSync)(descriptorPath(parentFd, (0, import_node_path31.basename)(path2)), import_node_fs40.constants.O_RDONLY | (import_node_fs40.constants.O_NOFOLLOW ?? 0));
46293
+ } finally {
46294
+ (0, import_node_fs40.closeSync)(parentFd);
46295
+ }
46296
+ const stat = (0, import_node_fs40.fstatSync)(fd);
46297
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_COMPRESSED_HISTORY_BYTES) return null;
46298
+ const compressed = readExact(fd, stat.size);
46299
+ const after = (0, import_node_fs40.fstatSync)(fd);
46300
+ if (!compressed || after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) return null;
46301
+ return (0, import_node_zlib2.gunzipSync)(compressed, { maxOutputLength: MAX_HISTORY_BYTES });
46302
+ } catch {
46303
+ return null;
46304
+ } finally {
46305
+ if (fd !== void 0) (0, import_node_fs40.closeSync)(fd);
46306
+ }
46307
+ }
46308
+ function compactTime(date) {
46309
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.(\d{3})Z$/, "$1Z");
46310
+ }
46311
+ var CommandHistoryWatcher = class {
46312
+ constructor(opts) {
46313
+ this.opts = opts;
46314
+ this.pollMs = Math.max(1e4, opts.pollMs ?? POLL_MS3);
46315
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
46316
+ this.listAccounts = opts.listAccounts ?? historyAccounts;
46317
+ this.root = (0, import_node_path31.join)(opts.stateDir, "command-history");
46318
+ }
46319
+ opts;
46320
+ timer = null;
46321
+ scanning = false;
46322
+ pollMs;
46323
+ now;
46324
+ listAccounts;
46325
+ root;
46326
+ start() {
46327
+ if (!this.opts.settings.enabled) {
46328
+ this.opts.log("[command-history] disabled; set [command_history] enabled = true to collect local shell history");
46329
+ return;
46330
+ }
46331
+ if (process.platform !== "linux") {
46332
+ this.opts.log("[command-history] unavailable: only Linux account history paths are supported");
46333
+ return;
46334
+ }
46335
+ try {
46336
+ privateDirectory(this.root);
46337
+ } catch (error2) {
46338
+ this.opts.log(`[command-history] cannot create private storage: ${error2.message}`);
46339
+ return;
46340
+ }
46341
+ this.opts.log(`[command-history] enabled; private snapshots under ${this.root}, checking every ${Math.round(this.pollMs / 1e3)}s`);
46342
+ void this.scanOnce();
46343
+ this.timer = setInterval(() => {
46344
+ void this.scanOnce();
46345
+ }, this.pollMs);
46346
+ this.timer.unref();
46347
+ }
46348
+ stop() {
46349
+ if (this.timer) clearInterval(this.timer);
46350
+ this.timer = null;
46351
+ }
46352
+ async scanOnce() {
46353
+ if (this.scanning || !this.opts.settings.enabled || process.platform !== "linux") return;
46354
+ this.scanning = true;
46355
+ try {
46356
+ privateDirectory(this.root);
46357
+ for (const account of this.listAccounts()) {
46358
+ if (!Number.isInteger(account.uid) || account.uid < 0 || !(0, import_node_path31.isAbsolute)(account.home)) continue;
46359
+ const targets = this.targetsFor(account);
46360
+ for (const relative4 of targets) this.scanFile(account, relative4);
46361
+ }
46362
+ } catch (error2) {
46363
+ this.opts.log(`[command-history] scan failed: ${error2.message}`);
46364
+ } finally {
46365
+ this.scanning = false;
46366
+ }
46367
+ }
46368
+ targetsFor(account) {
46369
+ const targets = new Set(HISTORY_TARGETS[(0, import_node_path31.basename)(account.shell)] ?? []);
46370
+ for (const relative4 of Object.values(HISTORY_TARGETS).flat()) {
46371
+ if (targets.has(relative4)) continue;
46372
+ const path2 = (0, import_node_path31.join)(account.home, relative4);
46373
+ try {
46374
+ (0, import_node_fs40.lstatSync)(path2);
46375
+ targets.add(relative4);
46376
+ continue;
46377
+ } catch (error2) {
46378
+ if (error2.code !== "ENOENT") continue;
46379
+ }
46380
+ const current = (0, import_node_path31.join)(this.root, String(account.uid), `${(0, import_node_path31.basename)(relative4)}.current.gz`);
46381
+ if (readCurrentBackup(current) !== null) targets.add(relative4);
46382
+ }
46383
+ return [...targets];
46384
+ }
46385
+ scanFile(account, relative4) {
46386
+ const path2 = (0, import_node_path31.join)(account.home, relative4);
46387
+ const store = (0, import_node_path31.join)(this.root, String(account.uid), (0, import_node_path31.basename)(relative4));
46388
+ const current = `${store}.current.gz`;
46389
+ let userParentFd;
46390
+ try {
46391
+ userParentFd = openDirectoryChain((0, import_node_path31.dirname)(path2));
46392
+ } catch {
46393
+ this.opts.log(`[command-history] skipped uid=${account.uid} ${(0, import_node_path31.basename)(relative4)} because its parent path is missing or not a real directory`);
46394
+ return;
46395
+ }
46396
+ try {
46397
+ privateDirectory((0, import_node_path31.dirname)(store));
46398
+ const userPath = descriptorPath(userParentFd, (0, import_node_path31.basename)(path2));
46399
+ let status;
46400
+ try {
46401
+ status = (0, import_node_fs40.lstatSync)(userPath);
46402
+ } catch (error2) {
46403
+ if (error2.code !== "ENOENT") throw error2;
46404
+ }
46405
+ const backup = readCurrentBackup(current);
46406
+ const suspicious = status && (!status.isFile() || status.isSymbolicLink() || status.nlink !== 1 || status.uid !== account.uid);
46407
+ const missingWithBackup = !status && backup !== null;
46408
+ if (suspicious || missingWithBackup) {
46409
+ const reason = !status ? "deleted" : status.isSymbolicLink() ? "symlinked" : !status.isFile() ? "not a regular file" : status.nlink !== 1 ? "hard-linked" : "owned by another account";
46410
+ const restored = backup ?? Buffer.alloc(0);
46411
+ this.restore(path2, restored, account, userParentFd);
46412
+ this.emitTamper(account, relative4, reason, backup !== null);
46413
+ } else if (!status) {
46414
+ this.restore(path2, Buffer.alloc(0), account, userParentFd);
46415
+ }
46416
+ const data = safeReadHistory(userParentFd, (0, import_node_path31.basename)(path2), account.uid);
46417
+ if (data === null) return;
46418
+ const previous = backup;
46419
+ if (previous?.equals(data)) {
46420
+ this.pruneSnapshots(current);
46421
+ return;
46422
+ }
46423
+ const compressed = (0, import_node_zlib2.gzipSync)(data, { level: 6 });
46424
+ const stamp = compactTime(this.now());
46425
+ atomicWrite(`${store}.${stamp}-${(0, import_node_crypto10.randomUUID)().slice(0, 8)}.gz`, compressed);
46426
+ atomicWrite(current, compressed);
46427
+ this.pruneSnapshots(store);
46428
+ } catch (error2) {
46429
+ this.opts.log(`[command-history] could not snapshot uid=${account.uid} ${(0, import_node_path31.basename)(relative4)}: ${error2.message}`);
46430
+ } finally {
46431
+ (0, import_node_fs40.closeSync)(userParentFd);
46432
+ }
46433
+ }
46434
+ restore(path2, content, account, parentFd) {
46435
+ atomicWrite(path2, content, 384, account, parentFd);
46436
+ }
46437
+ emitTamper(account, relative4, reason, hadBackup) {
46438
+ const name = /^[A-Za-z0-9_.-]{1,64}$/.test(account.name) ? account.name : `uid ${account.uid}`;
46439
+ const event = {
46440
+ timestamp: this.now(),
46441
+ module: "command-history",
46442
+ category: "system",
46443
+ severity: "medium",
46444
+ message: `Shell history for ${name} (${(0, import_node_path31.basename)(relative4)}) was ${reason}; restored${hadBackup ? " from the latest backup" : " as an empty file"}`,
46445
+ details: { uid: account.uid, account: name, history_file: (0, import_node_path31.basename)(relative4), action: "restored", reason, had_backup: hadBackup }
46446
+ };
46447
+ this.opts.bus.publish(event);
46448
+ this.opts.log(`[command-history] ${event.message}`);
46449
+ }
46450
+ pruneSnapshots(current) {
46451
+ const dir = (0, import_node_path31.dirname)(current);
46452
+ const prefix = `${(0, import_node_path31.basename)(current).replace(/\.current\.gz$/, "")}.`;
46453
+ const snapshots = (0, import_node_fs40.readdirSync)(dir).filter((name) => name !== (0, import_node_path31.basename)(current) && name.startsWith(prefix) && name.endsWith(".gz")).map((name) => ({ path: (0, import_node_path31.join)(dir, name), name, time: (0, import_node_fs40.lstatSync)((0, import_node_path31.join)(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time);
46454
+ const cutoff = this.now().getTime() - SNAPSHOT_RETENTION_MS;
46455
+ const removeCount = Math.max(0, snapshots.length - MAX_SNAPSHOTS);
46456
+ snapshots.forEach((snapshot, index) => {
46457
+ if (snapshot.time < cutoff || index < removeCount) {
46458
+ try {
46459
+ (0, import_node_fs40.unlinkSync)(snapshot.path);
46460
+ } catch {
46461
+ }
46462
+ }
46463
+ });
46464
+ }
46465
+ };
46466
+
46467
+ // src/daemon/workers/ssh-intrusion.ts
46468
+ var import_node_fs41 = require("fs");
46469
+ var import_node_path32 = require("path");
46470
+ var import_node_child_process14 = require("child_process");
46026
46471
 
46027
46472
  // src/core/asn.ts
46028
46473
  var import_node_dns = require("dns");
@@ -46215,35 +46660,35 @@ function parseKeyLoginsByFingerprint(text) {
46215
46660
  }
46216
46661
  function readJson2(path2) {
46217
46662
  try {
46218
- return JSON.parse((0, import_node_fs40.readFileSync)(path2, "utf-8"));
46663
+ return JSON.parse((0, import_node_fs41.readFileSync)(path2, "utf-8"));
46219
46664
  } catch {
46220
46665
  return null;
46221
46666
  }
46222
46667
  }
46223
46668
  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);
46669
+ (0, import_node_fs41.mkdirSync)((0, import_node_path32.dirname)(path2), { recursive: true });
46670
+ (0, import_node_fs41.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
46671
+ (0, import_node_fs41.renameSync)(`${path2}.tmp`, path2);
46227
46672
  }
46228
46673
  var fsIO2 = {
46229
46674
  readFile: (p) => {
46230
46675
  try {
46231
- return (0, import_node_fs40.readFileSync)(p, "utf-8");
46676
+ return (0, import_node_fs41.readFileSync)(p, "utf-8");
46232
46677
  } catch {
46233
46678
  return null;
46234
46679
  }
46235
46680
  },
46236
46681
  readDir: (p) => {
46237
46682
  try {
46238
- return (0, import_node_fs40.readdirSync)(p);
46683
+ return (0, import_node_fs41.readdirSync)(p);
46239
46684
  } catch {
46240
46685
  return null;
46241
46686
  }
46242
46687
  },
46243
- exists: (p) => (0, import_node_fs40.existsSync)(p)
46688
+ exists: (p) => (0, import_node_fs41.existsSync)(p)
46244
46689
  };
46245
46690
  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"] });
46691
+ const res = (0, import_node_child_process14.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
46247
46692
  return res.status === 0 ? res.stdout : null;
46248
46693
  }
46249
46694
  var SshIntrusionWatch = class {
@@ -46441,7 +46886,7 @@ var SshIntrusionWatch = class {
46441
46886
  };
46442
46887
 
46443
46888
  // src/daemon/workers/lightning-watch.ts
46444
- var import_node_fs41 = require("fs");
46889
+ var import_node_fs42 = require("fs");
46445
46890
  var DEFAULT_CLN_LOGS = [
46446
46891
  "/home/lightning/.lightning/cln.log",
46447
46892
  "/root/.lightning/cln.log",
@@ -46497,9 +46942,9 @@ var LightningWatch = class {
46497
46942
  if (this.opts.enabled === false) return [];
46498
46943
  const found = [];
46499
46944
  for (const path2 of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
46500
- if (!(0, import_node_fs41.existsSync)(path2)) continue;
46945
+ if (!(0, import_node_fs42.existsSync)(path2)) continue;
46501
46946
  try {
46502
- (0, import_node_fs41.accessSync)(path2, import_node_fs41.constants.R_OK);
46947
+ (0, import_node_fs42.accessSync)(path2, import_node_fs42.constants.R_OK);
46503
46948
  } catch {
46504
46949
  continue;
46505
46950
  }
@@ -46534,8 +46979,8 @@ var LightningWatch = class {
46534
46979
  };
46535
46980
 
46536
46981
  // src/core/tor-exits.ts
46537
- var import_node_fs42 = require("fs");
46538
- var import_node_path32 = require("path");
46982
+ var import_node_fs43 = require("fs");
46983
+ var import_node_path33 = require("path");
46539
46984
  var import_node_net15 = require("net");
46540
46985
  var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
46541
46986
  function parseTorExitList(text) {
@@ -46603,10 +47048,10 @@ var TorExitList = class _TorExitList {
46603
47048
  }
46604
47049
  loadCache() {
46605
47050
  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"));
47051
+ if (!(0, import_node_fs43.existsSync)(this.opts.cachePath)) return false;
47052
+ const parsed = parseTorExitList((0, import_node_fs43.readFileSync)(this.opts.cachePath, "utf-8"));
46608
47053
  if (parsed.size === 0) return false;
46609
- this.load(parsed, (0, import_node_fs42.statSync)(this.opts.cachePath).mtimeMs);
47054
+ this.load(parsed, (0, import_node_fs43.statSync)(this.opts.cachePath).mtimeMs);
46610
47055
  this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
46611
47056
  return true;
46612
47057
  } catch (err) {
@@ -46638,9 +47083,9 @@ var TorExitList = class _TorExitList {
46638
47083
  const before2 = this.exits.size;
46639
47084
  this.load(parsed);
46640
47085
  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);
47086
+ (0, import_node_fs43.mkdirSync)((0, import_node_path33.dirname)(this.opts.cachePath), { recursive: true });
47087
+ (0, import_node_fs43.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
47088
+ (0, import_node_fs43.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
46644
47089
  } catch (err) {
46645
47090
  this.log(`[tor] could not save the exit list cache: ${err.message}`);
46646
47091
  }
@@ -46665,7 +47110,35 @@ function expire(window, now) {
46665
47110
  }
46666
47111
  var EVIDENCE_MESSAGE_CHARS = 500;
46667
47112
  var EVIDENCE_FIELD_CHARS = 200;
46668
- var EVIDENCE_FIELDS = ["unit", "identifier", "process", "comm", "pid", "user", "path", "method", "status", "host", "priority"];
47113
+ var EVIDENCE_FIELDS = [
47114
+ "unit",
47115
+ "identifier",
47116
+ "process",
47117
+ "comm",
47118
+ "pid",
47119
+ "user",
47120
+ "ssh_user",
47121
+ "username",
47122
+ "account",
47123
+ "runas",
47124
+ "command",
47125
+ "system_account",
47126
+ "system_uid",
47127
+ "fingerprint",
47128
+ "key_type",
47129
+ "auth_method",
47130
+ "port",
47131
+ "path",
47132
+ "method",
47133
+ "status",
47134
+ "host",
47135
+ "priority",
47136
+ "boot_id",
47137
+ "journal_cursor",
47138
+ "audit_session",
47139
+ "login_uid",
47140
+ "source_ip_basis"
47141
+ ];
46669
47142
  function evidenceOf(event) {
46670
47143
  const details = event.details ?? {};
46671
47144
  const out = {
@@ -46742,7 +47215,7 @@ var RuleEngine = class {
46742
47215
  title: rule.title,
46743
47216
  description: `${rule.description} (${hitsLabel} events in ${rule.window_seconds}s${spread})`,
46744
47217
  source_ip: aggregate ? void 0 : event.source_ip,
46745
- username: event.details?.user || void 0,
47218
+ username: (event.details?.user ?? event.details?.ssh_user ?? event.details?.username ?? event.details?.account) || void 0,
46746
47219
  raw_metadata: {
46747
47220
  rule_version: rule.version,
46748
47221
  tags: rule.tags,
@@ -46830,8 +47303,8 @@ var RuleEngine = class {
46830
47303
  };
46831
47304
 
46832
47305
  // src/daemon/rules/loader.ts
46833
- var import_node_fs43 = require("fs");
46834
- var import_node_path33 = require("path");
47306
+ var import_node_fs44 = require("fs");
47307
+ var import_node_path34 = require("path");
46835
47308
 
46836
47309
  // src/daemon/rules/default-rules.ts
46837
47310
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -47293,6 +47766,127 @@ var DEFAULT_RULES = [
47293
47766
  description: "Confirm whether a capture tool or new bridge is expected on this host"
47294
47767
  },
47295
47768
  enabled: true
47769
+ },
47770
+ {
47771
+ id: "agentdb-auth-failure-burst",
47772
+ title: "AgentDB Authentication Failure Burst",
47773
+ description: "Repeated rejected credentials against the AgentDB API",
47774
+ version: "1.0.0",
47775
+ category: "auth",
47776
+ severity: "high",
47777
+ source_types: ["log-watcher"],
47778
+ match: {
47779
+ field: "service",
47780
+ operator: "equals",
47781
+ value: "agentdb",
47782
+ and: [{ field: "status", operator: "regex", value: "^(401|403)$" }]
47783
+ },
47784
+ threshold: 5,
47785
+ window_seconds: 60,
47786
+ cooldown_seconds: 300,
47787
+ tags: ["agentdb", "auth", "credential-abuse"],
47788
+ remediation: { action: "alert", description: "Review the source and rotate any credential that may have leaked" },
47789
+ enabled: true
47790
+ },
47791
+ {
47792
+ id: "agentdb-query-burst",
47793
+ title: "AgentDB Query Burst",
47794
+ description: "An unusually large number of database reads reached the service",
47795
+ version: "1.0.0",
47796
+ category: "web",
47797
+ severity: "high",
47798
+ source_types: ["log-watcher"],
47799
+ match: {
47800
+ field: "service",
47801
+ operator: "equals",
47802
+ value: "agentdb",
47803
+ and: [
47804
+ { field: "path", operator: "equals", value: "/v1/query_readonly" },
47805
+ { field: "status", operator: "regex", value: "^2[0-9][0-9]$" }
47806
+ ]
47807
+ },
47808
+ threshold: 60,
47809
+ window_seconds: 60,
47810
+ cooldown_seconds: 300,
47811
+ group_by: "endpoint",
47812
+ tags: ["agentdb", "data-access", "possible-exfiltration"],
47813
+ remediation: { action: "alert", description: "Check the token owner and audit query volume before revoking credentials" },
47814
+ enabled: true
47815
+ },
47816
+ {
47817
+ id: "agentdb-token-creation-burst",
47818
+ title: "AgentDB Credential Creation Burst",
47819
+ description: "An operator credential created several service tokens in a short period",
47820
+ version: "1.0.0",
47821
+ category: "auth",
47822
+ severity: "high",
47823
+ source_types: ["log-watcher"],
47824
+ match: {
47825
+ field: "service",
47826
+ operator: "equals",
47827
+ value: "agentdb",
47828
+ and: [
47829
+ { field: "path", operator: "equals", value: "/v1/tokens" },
47830
+ { field: "status", operator: "regex", value: "^2[0-9][0-9]$" }
47831
+ ]
47832
+ },
47833
+ threshold: 3,
47834
+ window_seconds: 60,
47835
+ cooldown_seconds: 600,
47836
+ group_by: "endpoint",
47837
+ tags: ["agentdb", "credentials", "persistence"],
47838
+ remediation: { action: "alert", description: "Check operator access and identify any newly issued token" },
47839
+ enabled: true
47840
+ },
47841
+ {
47842
+ id: "agentdb-large-query-exports",
47843
+ title: "Repeated Large AgentDB Query Responses",
47844
+ description: "Several large read-only query responses were served in a short period",
47845
+ version: "1.0.0",
47846
+ category: "web",
47847
+ severity: "high",
47848
+ source_types: ["log-watcher"],
47849
+ match: {
47850
+ field: "service",
47851
+ operator: "equals",
47852
+ value: "agentdb",
47853
+ and: [
47854
+ { field: "path", operator: "equals", value: "/v1/query_readonly" },
47855
+ { field: "status", operator: "regex", value: "^2[0-9][0-9]$" },
47856
+ { field: "response_bytes", operator: "regex", value: "^[1-9][0-9]{6,}$" }
47857
+ ]
47858
+ },
47859
+ threshold: 3,
47860
+ window_seconds: 600,
47861
+ cooldown_seconds: 600,
47862
+ group_by: "endpoint",
47863
+ tags: ["agentdb", "data-access", "large-export"],
47864
+ remediation: { action: "alert", description: "Review the source and revoke the token if this export was not expected" },
47865
+ enabled: true
47866
+ },
47867
+ {
47868
+ id: "agentdb-query-throttled",
47869
+ title: "AgentDB Read Limit Triggered",
47870
+ description: "AgentDB rejected a query because the client reached a service limit",
47871
+ version: "1.0.0",
47872
+ category: "web",
47873
+ severity: "medium",
47874
+ source_types: ["log-watcher"],
47875
+ match: {
47876
+ field: "service",
47877
+ operator: "equals",
47878
+ value: "agentdb",
47879
+ and: [
47880
+ { field: "path", operator: "equals", value: "/v1/query_readonly" },
47881
+ { field: "status", operator: "equals", value: "429" }
47882
+ ]
47883
+ },
47884
+ threshold: 1,
47885
+ window_seconds: 60,
47886
+ cooldown_seconds: 300,
47887
+ tags: ["agentdb", "rate-limit", "data-access"],
47888
+ remediation: { action: "alert", description: "Review AgentDB audit metadata for the token and request pattern" },
47889
+ enabled: true
47296
47890
  }
47297
47891
  ];
47298
47892
 
@@ -47301,11 +47895,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
47301
47895
  function loadAllRules(customDir) {
47302
47896
  const rules = [...DEFAULT_RULES];
47303
47897
  const dir = customDir || RULES_DIR;
47304
- if ((0, import_node_fs43.existsSync)(dir)) {
47305
- const files = (0, import_node_fs43.readdirSync)(dir).filter((f) => f.endsWith(".json"));
47898
+ if ((0, import_node_fs44.existsSync)(dir)) {
47899
+ const files = (0, import_node_fs44.readdirSync)(dir).filter((f) => f.endsWith(".json"));
47306
47900
  for (const file of files) {
47307
47901
  try {
47308
- const raw = (0, import_node_fs43.readFileSync)((0, import_node_path33.join)(dir, file), "utf-8");
47902
+ const raw = (0, import_node_fs44.readFileSync)((0, import_node_path34.join)(dir, file), "utf-8");
47309
47903
  const parsed = JSON.parse(raw);
47310
47904
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
47311
47905
  for (const rule of customRules) {
@@ -47336,9 +47930,9 @@ function loadAllRules(customDir) {
47336
47930
  }
47337
47931
 
47338
47932
  // src/daemon/firewall/adapters.ts
47339
- var import_node_child_process14 = require("child_process");
47340
- var import_node_fs44 = require("fs");
47341
- var import_node_path34 = require("path");
47933
+ var import_node_child_process15 = require("child_process");
47934
+ var import_node_fs45 = require("fs");
47935
+ var import_node_path35 = require("path");
47342
47936
  var import_node_net16 = require("net");
47343
47937
  function assertValidFirewallIp(ip) {
47344
47938
  if ((0, import_node_net16.isIP)(ip) !== 4) {
@@ -47351,9 +47945,9 @@ function assertBannableIp(ip) {
47351
47945
  }
47352
47946
  }
47353
47947
  function writeIfAbsent(path2, contents) {
47354
- (0, import_node_fs44.mkdirSync)((0, import_node_path34.dirname)(path2), { recursive: true });
47948
+ (0, import_node_fs45.mkdirSync)((0, import_node_path35.dirname)(path2), { recursive: true });
47355
47949
  try {
47356
- (0, import_node_fs44.writeFileSync)(path2, contents, { flag: "wx" });
47950
+ (0, import_node_fs45.writeFileSync)(path2, contents, { flag: "wx" });
47357
47951
  } catch (err) {
47358
47952
  if (err.code !== "EEXIST") throw err;
47359
47953
  }
@@ -47372,11 +47966,11 @@ var Fail2banAdapter = class {
47372
47966
  enforces = true;
47373
47967
  jailReady = false;
47374
47968
  isAvailable() {
47375
- const result = (0, import_node_child_process14.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
47969
+ const result = (0, import_node_child_process15.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
47376
47970
  return result.status === 0;
47377
47971
  }
47378
47972
  client(args) {
47379
- return (0, import_node_child_process14.execFileSync)("fail2ban-client", args, {
47973
+ return (0, import_node_child_process15.execFileSync)("fail2ban-client", args, {
47380
47974
  encoding: "utf-8",
47381
47975
  stdio: ["ignore", "pipe", "pipe"]
47382
47976
  });
@@ -47472,35 +48066,35 @@ var NftablesAdapter = class {
47472
48066
  table = "threatcrush";
47473
48067
  set = "blocklist";
47474
48068
  isAvailable() {
47475
- const result = (0, import_node_child_process14.spawnSync)("nft", ["--version"], { stdio: "pipe" });
48069
+ const result = (0, import_node_child_process15.spawnSync)("nft", ["--version"], { stdio: "pipe" });
47476
48070
  return result.status === 0;
47477
48071
  }
47478
48072
  ensureSetup() {
47479
48073
  try {
47480
- (0, import_node_child_process14.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
48074
+ (0, import_node_child_process15.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
47481
48075
  } catch {
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`);
48076
+ (0, import_node_child_process15.execSync)(`nft add table inet ${this.table}`);
48077
+ (0, import_node_child_process15.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
48078
+ (0, import_node_child_process15.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
48079
+ (0, import_node_child_process15.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
47486
48080
  }
47487
48081
  }
47488
48082
  async block(ip) {
47489
48083
  assertValidFirewallIp(ip);
47490
48084
  this.ensureSetup();
47491
- (0, import_node_child_process14.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
48085
+ (0, import_node_child_process15.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
47492
48086
  }
47493
48087
  async unblock(ip) {
47494
48088
  assertValidFirewallIp(ip);
47495
48089
  try {
47496
- (0, import_node_child_process14.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
48090
+ (0, import_node_child_process15.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
47497
48091
  } catch {
47498
48092
  }
47499
48093
  }
47500
48094
  async isBlocked(ip) {
47501
48095
  assertValidFirewallIp(ip);
47502
48096
  try {
47503
- const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
48097
+ const output = (0, import_node_child_process15.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
47504
48098
  return output.includes(ip);
47505
48099
  } catch {
47506
48100
  return false;
@@ -47508,7 +48102,7 @@ var NftablesAdapter = class {
47508
48102
  }
47509
48103
  async listBlocked() {
47510
48104
  try {
47511
- const output = (0, import_node_child_process14.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
48105
+ const output = (0, import_node_child_process15.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
47512
48106
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
47513
48107
  if (!match) return [];
47514
48108
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -47521,34 +48115,34 @@ var IptablesAdapter = class {
47521
48115
  name = "iptables";
47522
48116
  chain = "THREATCRUSH";
47523
48117
  isAvailable() {
47524
- const result = (0, import_node_child_process14.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
48118
+ const result = (0, import_node_child_process15.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
47525
48119
  return result.status === 0;
47526
48120
  }
47527
48121
  ensureChain() {
47528
48122
  try {
47529
- (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
48123
+ (0, import_node_child_process15.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
47530
48124
  } catch {
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}`);
48125
+ (0, import_node_child_process15.execSync)(`iptables -N ${this.chain}`);
48126
+ (0, import_node_child_process15.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
47533
48127
  }
47534
48128
  }
47535
48129
  async block(ip) {
47536
48130
  assertValidFirewallIp(ip);
47537
48131
  this.ensureChain();
47538
48132
  if (await this.isBlocked(ip)) return;
47539
- (0, import_node_child_process14.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
48133
+ (0, import_node_child_process15.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
47540
48134
  }
47541
48135
  async unblock(ip) {
47542
48136
  assertValidFirewallIp(ip);
47543
48137
  try {
47544
- (0, import_node_child_process14.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
48138
+ (0, import_node_child_process15.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
47545
48139
  } catch {
47546
48140
  }
47547
48141
  }
47548
48142
  async isBlocked(ip) {
47549
48143
  assertValidFirewallIp(ip);
47550
48144
  try {
47551
- const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
48145
+ const output = (0, import_node_child_process15.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
47552
48146
  return output.includes(ip);
47553
48147
  } catch {
47554
48148
  return false;
@@ -47556,7 +48150,7 @@ var IptablesAdapter = class {
47556
48150
  }
47557
48151
  async listBlocked() {
47558
48152
  try {
47559
- const output = (0, import_node_child_process14.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
48153
+ const output = (0, import_node_child_process15.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
47560
48154
  const ips = [];
47561
48155
  for (const line2 of output.split("\n")) {
47562
48156
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -47612,8 +48206,8 @@ function detectFirewallAdapter(backend = "auto") {
47612
48206
  }
47613
48207
 
47614
48208
  // src/daemon/firewall/remediation.ts
47615
- var import_node_fs45 = require("fs");
47616
- var import_node_child_process15 = require("child_process");
48209
+ var import_node_fs46 = require("fs");
48210
+ var import_node_child_process16 = require("child_process");
47617
48211
  var import_node_net17 = require("net");
47618
48212
  init_paths();
47619
48213
  init_backoff();
@@ -47684,19 +48278,19 @@ var defaultDiscovery = {
47684
48278
  const snapshot = takeSnapshot({
47685
48279
  readFile: (p) => {
47686
48280
  try {
47687
- return (0, import_node_fs45.readFileSync)(p, "utf-8");
48281
+ return (0, import_node_fs46.readFileSync)(p, "utf-8");
47688
48282
  } catch {
47689
48283
  return null;
47690
48284
  }
47691
48285
  },
47692
48286
  readDir: (p) => {
47693
48287
  try {
47694
- return (0, import_node_fs45.readdirSync)(p);
48288
+ return (0, import_node_fs46.readdirSync)(p);
47695
48289
  } catch {
47696
48290
  return null;
47697
48291
  }
47698
48292
  },
47699
- exists: (p) => (0, import_node_fs45.existsSync)(p)
48293
+ exists: (p) => (0, import_node_fs46.existsSync)(p)
47700
48294
  });
47701
48295
  const out = /* @__PURE__ */ new Set();
47702
48296
  for (const keys of Object.values(snapshot.keys)) {
@@ -47705,7 +48299,7 @@ var defaultDiscovery = {
47705
48299
  return out;
47706
48300
  },
47707
48301
  keyLoginJournal: (sinceSeconds) => new Promise((resolve8) => {
47708
- (0, import_node_child_process15.execFile)(
48302
+ (0, import_node_child_process16.execFile)(
47709
48303
  "journalctl",
47710
48304
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
47711
48305
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -48209,7 +48803,7 @@ var RemediationManager = class {
48209
48803
  }
48210
48804
  logLine(line2) {
48211
48805
  try {
48212
- (0, import_node_fs45.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
48806
+ (0, import_node_fs46.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
48213
48807
  `);
48214
48808
  } catch {
48215
48809
  }
@@ -48253,19 +48847,19 @@ function remediationSettings(section) {
48253
48847
  init_backoff();
48254
48848
 
48255
48849
  // src/daemon/watchdog-service.ts
48256
- var import_node_fs46 = require("fs");
48257
- var import_node_path35 = require("path");
48850
+ var import_node_fs47 = require("fs");
48851
+ var import_node_path36 = require("path");
48258
48852
  function defaultShareGid() {
48259
48853
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
48260
48854
  if (!isRoot4) return void 0;
48261
48855
  try {
48262
- return (0, import_node_fs46.statSync)("/var/log/auth.log").gid;
48856
+ return (0, import_node_fs47.statSync)("/var/log/auth.log").gid;
48263
48857
  } catch {
48264
48858
  return void 0;
48265
48859
  }
48266
48860
  }
48267
48861
  function startWatchdog(opts) {
48268
- const dir = opts.config?.dir ?? (0, import_node_path35.join)(opts.stateDir, WATCHDOG_DIRNAME);
48862
+ const dir = opts.config?.dir ?? (0, import_node_path36.join)(opts.stateDir, WATCHDOG_DIRNAME);
48269
48863
  const base = { dir, logged: 0, answered: 0, errored: 0 };
48270
48864
  if (opts.config?.enabled === false) {
48271
48865
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -48359,7 +48953,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
48359
48953
  }
48360
48954
 
48361
48955
  // src/core/node-runtime.ts
48362
- var import_node_child_process16 = require("child_process");
48956
+ var import_node_child_process17 = require("child_process");
48363
48957
  var MIN_DAEMON_NODE_MAJOR = 22;
48364
48958
  function nodeMajor(version) {
48365
48959
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -48373,23 +48967,23 @@ function daemonNodeProblem(version) {
48373
48967
  }
48374
48968
  function versionOfNode(path2) {
48375
48969
  if (path2 === process.execPath) return process.versions.node;
48376
- const res = (0, import_node_child_process16.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
48970
+ const res = (0, import_node_child_process17.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
48377
48971
  return res.status === 0 ? res.stdout.trim() : null;
48378
48972
  }
48379
48973
 
48380
48974
  // src/daemon/index.ts
48381
48975
  function readVersion2() {
48382
48976
  try {
48383
- const pkg = JSON.parse((0, import_node_fs47.readFileSync)((0, import_node_path36.join)(__dirname, "..", "package.json"), "utf-8"));
48977
+ const pkg = JSON.parse((0, import_node_fs48.readFileSync)((0, import_node_path37.join)(__dirname, "..", "package.json"), "utf-8"));
48384
48978
  return pkg.version || "0.0.0";
48385
48979
  } catch {
48386
48980
  return "0.0.0";
48387
48981
  }
48388
48982
  }
48389
48983
  async function runHardeningChecks() {
48390
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process17.execFile)(
48984
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process18.execFile)(
48391
48985
  process.execPath,
48392
- [(0, import_node_path36.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
48986
+ [(0, import_node_path37.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
48393
48987
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
48394
48988
  );
48395
48989
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -48401,9 +48995,9 @@ async function runHardeningChecks() {
48401
48995
  return patches ? [...findings2, patches] : findings2;
48402
48996
  }
48403
48997
  async function runPatchCheck() {
48404
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process17.execFile)(
48998
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process18.execFile)(
48405
48999
  process.execPath,
48406
- [(0, import_node_path36.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
49000
+ [(0, import_node_path37.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
48407
49001
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
48408
49002
  );
48409
49003
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -48411,7 +49005,7 @@ async function runPatchCheck() {
48411
49005
  }
48412
49006
  function logLine(line2) {
48413
49007
  try {
48414
- (0, import_node_fs47.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
49008
+ (0, import_node_fs48.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
48415
49009
  `);
48416
49010
  } catch {
48417
49011
  }
@@ -48436,9 +49030,9 @@ async function runDaemon() {
48436
49030
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
48437
49031
  const restartDaemon = () => {
48438
49032
  if (PATHS.mode === "system") {
48439
- (0, import_node_child_process17.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
49033
+ (0, import_node_child_process18.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
48440
49034
  } else {
48441
- (0, import_node_child_process17.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
49035
+ (0, import_node_child_process18.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
48442
49036
  setTimeout(() => process.exit(0), 500).unref();
48443
49037
  }
48444
49038
  };
@@ -48453,7 +49047,7 @@ async function runDaemon() {
48453
49047
  } catch (err) {
48454
49048
  logLine(`[daemon] state db unavailable: ${err.message}`);
48455
49049
  }
48456
- const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path36.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
49050
+ const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path37.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
48457
49051
  const config = loaded.config;
48458
49052
  if (loaded.error) {
48459
49053
  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)"}`);
@@ -48521,7 +49115,7 @@ async function runDaemon() {
48521
49115
  const threatFeeds = new ThreatFeeds({
48522
49116
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
48523
49117
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
48524
- cachePath: (0, import_node_path36.join)(PATHS.stateDir, "threat-feeds.json"),
49118
+ cachePath: (0, import_node_path37.join)(PATHS.stateDir, "threat-feeds.json"),
48525
49119
  bus,
48526
49120
  log: logLine
48527
49121
  });
@@ -48529,14 +49123,21 @@ async function runDaemon() {
48529
49123
  const privilegeWatch = new PrivilegeWatch({
48530
49124
  settings: privilegeSettings(config.privileged),
48531
49125
  bus,
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"),
49126
+ snapshotPath: (0, import_node_path37.join)(PATHS.stateDir, "privileges.json"),
49127
+ loginsPath: (0, import_node_path37.join)(PATHS.stateDir, "login-countries.json"),
49128
+ cursorPath: (0, import_node_path37.join)(PATHS.stateDir, "sudo-cursor.json"),
48535
49129
  log: logLine
48536
49130
  });
48537
49131
  privilegeWatch.start();
49132
+ const commandHistory = new CommandHistoryWatcher({
49133
+ settings: commandHistorySettings(config.command_history),
49134
+ bus,
49135
+ stateDir: PATHS.stateDir,
49136
+ log: logLine
49137
+ });
49138
+ commandHistory.start();
48538
49139
  const torExits = new TorExitList({
48539
- cachePath: (0, import_node_path36.join)(PATHS.stateDir, "tor-exits.txt"),
49140
+ cachePath: (0, import_node_path37.join)(PATHS.stateDir, "tor-exits.txt"),
48540
49141
  url: config.remediation?.tor_exit_list_url,
48541
49142
  log: logLine
48542
49143
  });
@@ -48544,7 +49145,7 @@ async function runDaemon() {
48544
49145
  bus,
48545
49146
  manager: remediation,
48546
49147
  tor: torExits,
48547
- historyPath: (0, import_node_path36.join)(PATHS.stateDir, "key-logins.json"),
49148
+ historyPath: (0, import_node_path37.join)(PATHS.stateDir, "key-logins.json"),
48548
49149
  keyLoginWatch: config.privileged?.key_login_watch !== false,
48549
49150
  log: logLine
48550
49151
  });
@@ -48591,7 +49192,7 @@ async function runDaemon() {
48591
49192
  version,
48592
49193
  hostname: (0, import_node_os14.hostname)(),
48593
49194
  minSeverity,
48594
- spoolPath: (0, import_node_path36.join)(PATHS.stateDir, "cloud-spool.jsonl"),
49195
+ spoolPath: (0, import_node_path37.join)(PATHS.stateDir, "cloud-spool.jsonl"),
48595
49196
  log: logLine,
48596
49197
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
48597
49198
  runHardening: runHardeningChecks
@@ -48624,8 +49225,8 @@ async function runDaemon() {
48624
49225
  const autoUpdate = autoUpdateRef = new AutoUpdate({
48625
49226
  version,
48626
49227
  settings: updateSettings(config.update),
48627
- pkgRoot: (0, import_node_path36.join)(__dirname, ".."),
48628
- statePath: (0, import_node_path36.join)(PATHS.stateDir, "auto-update.json"),
49228
+ pkgRoot: (0, import_node_path37.join)(__dirname, ".."),
49229
+ statePath: (0, import_node_path37.join)(PATHS.stateDir, "auto-update.json"),
48629
49230
  bus,
48630
49231
  log: logLine,
48631
49232
  restartDaemon
@@ -48680,6 +49281,10 @@ async function runDaemon() {
48680
49281
  privilegeWatch.stop();
48681
49282
  } catch {
48682
49283
  }
49284
+ try {
49285
+ commandHistory.stop();
49286
+ } catch {
49287
+ }
48683
49288
  try {
48684
49289
  sshIntrusion.stop();
48685
49290
  } catch {
@@ -48723,7 +49328,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
48723
49328
  function isRoot2() {
48724
49329
  return typeof process.getuid === "function" && process.getuid() === 0;
48725
49330
  }
48726
- var DAEMON_ENTRY = (0, import_node_path37.join)(__dirname, "daemon.js");
49331
+ var DAEMON_ENTRY = (0, import_node_path38.join)(__dirname, "daemon.js");
48727
49332
  async function daemonForeground() {
48728
49333
  await runDaemon();
48729
49334
  }
@@ -48744,7 +49349,7 @@ async function daemonStart() {
48744
49349
  return;
48745
49350
  }
48746
49351
  ensureRuntimeDirs();
48747
- if (!(0, import_node_fs48.existsSync)(DAEMON_ENTRY)) {
49352
+ if (!(0, import_node_fs49.existsSync)(DAEMON_ENTRY)) {
48748
49353
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
48749
49354
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
48750
49355
  return;
@@ -48752,8 +49357,8 @@ async function daemonStart() {
48752
49357
  let out;
48753
49358
  let err;
48754
49359
  try {
48755
- out = (0, import_node_fs49.openSync)(PATHS.logFile, "a");
48756
- err = (0, import_node_fs49.openSync)(PATHS.logFile, "a");
49360
+ out = (0, import_node_fs50.openSync)(PATHS.logFile, "a");
49361
+ err = (0, import_node_fs50.openSync)(PATHS.logFile, "a");
48757
49362
  } catch (e) {
48758
49363
  const code = e.code;
48759
49364
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -48766,7 +49371,7 @@ async function daemonStart() {
48766
49371
  }
48767
49372
  return;
48768
49373
  }
48769
- const child = (0, import_node_child_process18.spawn)(process.execPath, [DAEMON_ENTRY], {
49374
+ const child = (0, import_node_child_process19.spawn)(process.execPath, [DAEMON_ENTRY], {
48770
49375
  detached: true,
48771
49376
  stdio: ["ignore", out, err],
48772
49377
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -48841,41 +49446,41 @@ async function waitForExit(pid, timeoutMs) {
48841
49446
  }
48842
49447
  async function releaseStaleSocket() {
48843
49448
  const deadline = Date.now() + 2e3;
48844
- while ((0, import_node_fs48.existsSync)(PATHS.socket) && Date.now() < deadline) {
49449
+ while ((0, import_node_fs49.existsSync)(PATHS.socket) && Date.now() < deadline) {
48845
49450
  await new Promise((r) => setTimeout(r, 50));
48846
49451
  }
48847
- if ((0, import_node_fs48.existsSync)(PATHS.socket)) {
49452
+ if ((0, import_node_fs49.existsSync)(PATHS.socket)) {
48848
49453
  try {
48849
- (0, import_node_fs48.unlinkSync)(PATHS.socket);
49454
+ (0, import_node_fs49.unlinkSync)(PATHS.socket);
48850
49455
  } catch {
48851
49456
  }
48852
49457
  }
48853
49458
  }
48854
49459
 
48855
49460
  // src/commands/service.ts
48856
- var import_node_child_process19 = require("child_process");
48857
- var import_node_fs50 = require("fs");
48858
- var import_node_path38 = require("path");
49461
+ var import_node_child_process20 = require("child_process");
49462
+ var import_node_fs51 = require("fs");
49463
+ var import_node_path39 = require("path");
48859
49464
  var import_node_os15 = require("os");
48860
49465
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
48861
49466
  var DAEMON_UNIT_NAME = "threatcrushd.service";
48862
49467
  function resolveTemplate() {
48863
- const templatePath = (0, import_node_path38.join)(__dirname, "systemd", "threatcrushd.service");
48864
- if (!(0, import_node_fs50.existsSync)(templatePath)) {
49468
+ const templatePath = (0, import_node_path39.join)(__dirname, "systemd", "threatcrushd.service");
49469
+ if (!(0, import_node_fs51.existsSync)(templatePath)) {
48865
49470
  throw new Error(`systemd unit template not found at ${templatePath}`);
48866
49471
  }
48867
- return (0, import_node_fs50.readFileSync)(templatePath, "utf-8");
49472
+ return (0, import_node_fs51.readFileSync)(templatePath, "utf-8");
48868
49473
  }
48869
49474
  function stableBinPath(binPath) {
48870
49475
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
48871
49476
  if (stable === binPath) return binPath;
48872
- return (0, import_node_fs50.existsSync)(stable) ? stable : binPath;
49477
+ return (0, import_node_fs51.existsSync)(stable) ? stable : binPath;
48873
49478
  }
48874
49479
  function resolveBinPath() {
48875
49480
  const arg = process.argv[1];
48876
- if (arg && (0, import_node_fs50.existsSync)(arg)) return stableBinPath(arg);
49481
+ if (arg && (0, import_node_fs51.existsSync)(arg)) return stableBinPath(arg);
48877
49482
  try {
48878
- return (0, import_node_child_process19.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
49483
+ return (0, import_node_child_process20.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
48879
49484
  } catch {
48880
49485
  return "threatcrush";
48881
49486
  }
@@ -48883,11 +49488,11 @@ function resolveBinPath() {
48883
49488
  function stableNodePath(execPath) {
48884
49489
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
48885
49490
  if (stable === execPath) return execPath;
48886
- return (0, import_node_fs50.existsSync)(stable) ? stable : execPath;
49491
+ return (0, import_node_fs51.existsSync)(stable) ? stable : execPath;
48887
49492
  }
48888
49493
  function looksLikeNodeScript(path2) {
48889
49494
  try {
48890
- const head = (0, import_node_fs50.readFileSync)(path2, "utf-8").slice(0, 120);
49495
+ const head = (0, import_node_fs51.readFileSync)(path2, "utf-8").slice(0, 120);
48891
49496
  return /^#!.*\bnode\b/.test(head);
48892
49497
  } catch {
48893
49498
  return false;
@@ -48897,7 +49502,7 @@ function execStartCommand(binPath, nodePath, isNodeScript) {
48897
49502
  return isNodeScript ? `${nodePath} ${binPath} daemon` : `${binPath} daemon`;
48898
49503
  }
48899
49504
  function renderUnit(template, opts) {
48900
- return template.replaceAll("{{BIN_PATH}} daemon", opts.exec).replaceAll("{{BIN_PATH}}", opts.binPath).replaceAll("{{CONFIG_DIR}}", opts.configDir);
49505
+ return template.replaceAll("{{BIN_PATH}} daemon", opts.exec).replaceAll("{{BIN_PATH}}", opts.binPath).replaceAll("{{CONFIG_DIR}}", opts.configDir).replaceAll("{{HISTORY_PATHS}}", (opts.historyPaths ?? []).map((path2) => `-${path2}`).join(" ")).replace(/ReadWritePaths=([^\n]*)/, (_line, paths) => `ReadWritePaths=${paths.split(/\s+/).filter(Boolean).join(" ")}`);
48901
49506
  }
48902
49507
  function nodeVersionDir(path2) {
48903
49508
  const m = path2.match(
@@ -48914,20 +49519,20 @@ function isRoot3() {
48914
49519
  return typeof process.getuid === "function" && process.getuid() === 0;
48915
49520
  }
48916
49521
  function reexecWithSudo(args) {
48917
- if ((0, import_node_child_process19.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
49522
+ if ((0, import_node_child_process20.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
48918
49523
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
48919
49524
  const bin = resolveBinPath();
48920
49525
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
48921
- const result = (0, import_node_child_process19.spawnSync)("sudo", argv, { stdio: "inherit" });
49526
+ const result = (0, import_node_child_process20.spawnSync)("sudo", argv, { stdio: "inherit" });
48922
49527
  return result.status === 0;
48923
49528
  }
48924
49529
  function callerHome() {
48925
49530
  const user = process.env.SUDO_USER;
48926
49531
  if (!user) return null;
48927
49532
  try {
48928
- const line2 = (0, import_node_child_process19.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
49533
+ const line2 = (0, import_node_child_process20.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
48929
49534
  const home = line2.split(":")[5];
48930
- return home && (0, import_node_fs50.existsSync)(home) ? home : null;
49535
+ return home && (0, import_node_fs51.existsSync)(home) ? home : null;
48931
49536
  } catch {
48932
49537
  return null;
48933
49538
  }
@@ -48935,13 +49540,13 @@ function callerHome() {
48935
49540
  function stopUserModeDaemon() {
48936
49541
  const home = callerHome();
48937
49542
  if (!home) 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;
49543
+ const runDir = (0, import_node_path39.join)(home, ".threatcrush", "run");
49544
+ const pidFile = (0, import_node_path39.join)(runDir, "threatcrushd.pid");
49545
+ const socket = (0, import_node_path39.join)(runDir, "threatcrushd.sock");
49546
+ if (!(0, import_node_fs51.existsSync)(pidFile) && !(0, import_node_fs51.existsSync)(socket)) return;
48942
49547
  let pid = null;
48943
49548
  try {
48944
- pid = Number.parseInt((0, import_node_fs50.readFileSync)(pidFile, "utf-8").trim(), 10);
49549
+ pid = Number.parseInt((0, import_node_fs51.readFileSync)(pidFile, "utf-8").trim(), 10);
48945
49550
  } catch {
48946
49551
  pid = null;
48947
49552
  }
@@ -48954,13 +49559,13 @@ function stopUserModeDaemon() {
48954
49559
  }
48955
49560
  for (const path2 of [socket, pidFile]) {
48956
49561
  try {
48957
- if ((0, import_node_fs50.existsSync)(path2)) (0, import_node_fs50.rmSync)(path2);
49562
+ if ((0, import_node_fs51.existsSync)(path2)) (0, import_node_fs51.rmSync)(path2);
48958
49563
  } catch {
48959
49564
  }
48960
49565
  }
48961
49566
  }
48962
49567
  function unitIsActive() {
48963
- const result = (0, import_node_child_process19.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
49568
+ const result = (0, import_node_child_process20.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
48964
49569
  return result.status === 0;
48965
49570
  }
48966
49571
  async function installServiceCommand() {
@@ -48971,8 +49576,8 @@ async function installServiceCommand() {
48971
49576
  return;
48972
49577
  }
48973
49578
  const noSystemd = systemdUnavailableReason({
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")
49579
+ hasSystemctl: (0, import_node_child_process20.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
49580
+ booted: (0, import_node_fs51.existsSync)("/run/systemd/system")
48976
49581
  });
48977
49582
  if (noSystemd) {
48978
49583
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -48994,7 +49599,7 @@ async function installServiceCommand() {
48994
49599
  const isNodeScript = looksLikeNodeScript(binPath);
48995
49600
  let nodePath = stableNodePath(process.execPath);
48996
49601
  if (isNodeScript && nodeVersionDir(binPath)) {
48997
- binPath = (0, import_node_fs50.realpathSync)(binPath);
49602
+ binPath = (0, import_node_fs51.realpathSync)(binPath);
48998
49603
  nodePath = process.execPath;
48999
49604
  }
49000
49605
  if (isNodeScript) {
@@ -49007,9 +49612,11 @@ async function installServiceCommand() {
49007
49612
  }
49008
49613
  }
49009
49614
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
49010
- const configDir = (0, import_node_path38.join)((0, import_node_os15.homedir)(), ".threatcrush");
49011
- const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
49012
- (0, import_node_fs50.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
49615
+ const configDir = (0, import_node_path39.join)((0, import_node_os15.homedir)(), ".threatcrush");
49616
+ const commandHistoryEnabled = commandHistorySettings(loadConfig().command_history).enabled;
49617
+ const historyPaths = commandHistoryEnabled ? historyWritableHomes() : [];
49618
+ const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir, historyPaths });
49619
+ (0, import_node_fs51.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
49013
49620
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
49014
49621
  console.log(source_default.dim(` ExecStart=${exec}`));
49015
49622
  const nodeDir = nodeVersionDir(nodePath);
@@ -49024,8 +49631,8 @@ async function installServiceCommand() {
49024
49631
  installLogrotate();
49025
49632
  stopUserModeDaemon();
49026
49633
  try {
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" });
49634
+ (0, import_node_child_process20.execSync)("systemctl daemon-reload", { stdio: "inherit" });
49635
+ (0, import_node_child_process20.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
49029
49636
  } catch (err) {
49030
49637
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
49031
49638
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -49062,9 +49669,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
49062
49669
  ].join("\n");
49063
49670
  }
49064
49671
  function installLogrotate() {
49065
- if (!(0, import_node_fs50.existsSync)((0, import_node_path38.dirname)(LOGROTATE_PATH))) return;
49672
+ if (!(0, import_node_fs51.existsSync)((0, import_node_path39.dirname)(LOGROTATE_PATH))) return;
49066
49673
  try {
49067
- (0, import_node_fs50.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
49674
+ (0, import_node_fs51.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
49068
49675
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
49069
49676
  } catch (err) {
49070
49677
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -49086,20 +49693,20 @@ function ensureSystemDirs(configDir) {
49086
49693
  ];
49087
49694
  let admGid2 = null;
49088
49695
  try {
49089
- admGid2 = (0, import_node_fs50.statSync)("/var/log/auth.log").gid;
49696
+ admGid2 = (0, import_node_fs51.statSync)("/var/log/auth.log").gid;
49090
49697
  } catch {
49091
49698
  }
49092
49699
  for (const { path: path2, groupWritable, sticky } of dirs) {
49093
49700
  try {
49094
- (0, import_node_fs50.mkdirSync)(path2, { recursive: true });
49701
+ (0, import_node_fs51.mkdirSync)(path2, { recursive: true });
49095
49702
  } catch {
49096
49703
  }
49097
49704
  try {
49098
49705
  if (groupWritable && admGid2 !== null) {
49099
- (0, import_node_fs50.chmodSync)(path2, sticky ? 1533 : 509);
49100
- (0, import_node_child_process19.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
49706
+ (0, import_node_fs51.chmodSync)(path2, sticky ? 1533 : 509);
49707
+ (0, import_node_child_process20.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
49101
49708
  } else {
49102
- (0, import_node_fs50.chmodSync)(path2, 493);
49709
+ (0, import_node_fs51.chmodSync)(path2, 493);
49103
49710
  }
49104
49711
  } catch {
49105
49712
  }
@@ -49119,29 +49726,29 @@ async function uninstallServiceCommand() {
49119
49726
  return;
49120
49727
  }
49121
49728
  try {
49122
- (0, import_node_child_process19.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
49729
+ (0, import_node_child_process20.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
49123
49730
  } catch {
49124
49731
  }
49125
49732
  try {
49126
- (0, import_node_child_process19.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
49733
+ (0, import_node_child_process20.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
49127
49734
  } catch {
49128
49735
  }
49129
49736
  try {
49130
- if ((0, import_node_fs50.existsSync)(UNIT_PATH)) {
49131
- (0, import_node_child_process19.execSync)(`rm -f ${UNIT_PATH}`);
49737
+ if ((0, import_node_fs51.existsSync)(UNIT_PATH)) {
49738
+ (0, import_node_child_process20.execSync)(`rm -f ${UNIT_PATH}`);
49132
49739
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
49133
49740
  }
49134
49741
  } catch {
49135
49742
  }
49136
49743
  try {
49137
- (0, import_node_child_process19.execSync)("systemctl daemon-reload", { stdio: "inherit" });
49744
+ (0, import_node_child_process20.execSync)("systemctl daemon-reload", { stdio: "inherit" });
49138
49745
  } catch {
49139
49746
  }
49140
49747
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
49141
49748
  }
49142
49749
 
49143
49750
  // src/commands/save.ts
49144
- var import_node_fs51 = require("fs");
49751
+ var import_node_fs52 = require("fs");
49145
49752
  var import_toml5 = __toESM(require_toml());
49146
49753
  init_cli_config();
49147
49754
  init_paths();
@@ -49180,9 +49787,9 @@ async function saveCommand(opts = {}) {
49180
49787
  }
49181
49788
  const path2 = opts.config ?? PATHS.configFile;
49182
49789
  let config = {};
49183
- if ((0, import_node_fs51.existsSync)(path2)) {
49790
+ if ((0, import_node_fs52.existsSync)(path2)) {
49184
49791
  try {
49185
- config = import_toml5.default.parse((0, import_node_fs51.readFileSync)(path2, "utf-8"));
49792
+ config = import_toml5.default.parse((0, import_node_fs52.readFileSync)(path2, "utf-8"));
49186
49793
  } catch (err) {
49187
49794
  console.log(source_default.red(` \u2717 ${path2} is not valid TOML: ${err.message}
49188
49795
  `));
@@ -49295,8 +49902,8 @@ function welcomeCommand() {
49295
49902
  }
49296
49903
 
49297
49904
  // src/commands/properties.ts
49298
- var import_node_fs52 = require("fs");
49299
- var import_node_path39 = require("path");
49905
+ var import_node_fs53 = require("fs");
49906
+ var import_node_path40 = require("path");
49300
49907
  var import_node_readline4 = __toESM(require("readline"));
49301
49908
  init_cli_config();
49302
49909
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
@@ -49626,8 +50233,8 @@ async function propertiesRunsCommand(opts) {
49626
50233
  }
49627
50234
  }
49628
50235
  function parseImportFile(path2) {
49629
- const ext = (0, import_node_path39.extname)(path2).toLowerCase();
49630
- const raw = (0, import_node_fs52.readFileSync)(path2, "utf-8");
50236
+ const ext = (0, import_node_path40.extname)(path2).toLowerCase();
50237
+ const raw = (0, import_node_fs53.readFileSync)(path2, "utf-8");
49631
50238
  if (ext === ".json") {
49632
50239
  const parsed = JSON.parse(raw);
49633
50240
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -49822,19 +50429,19 @@ async function rulesCommand(opts) {
49822
50429
  }
49823
50430
 
49824
50431
  // src/commands/harden.ts
49825
- var import_node_fs53 = require("fs");
49826
- var import_node_child_process20 = require("child_process");
50432
+ var import_node_fs54 = require("fs");
50433
+ var import_node_child_process21 = require("child_process");
49827
50434
  init_cli_config();
49828
50435
  function tryExec(cmd) {
49829
50436
  try {
49830
- return (0, import_node_child_process20.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
50437
+ return (0, import_node_child_process21.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
49831
50438
  } catch {
49832
50439
  return null;
49833
50440
  }
49834
50441
  }
49835
50442
  function tryRead(path2) {
49836
50443
  try {
49837
- return (0, import_node_fs53.readFileSync)(path2, "utf-8");
50444
+ return (0, import_node_fs54.readFileSync)(path2, "utf-8");
49838
50445
  } catch {
49839
50446
  return null;
49840
50447
  }
@@ -49938,8 +50545,8 @@ function checkSshWeakConfig() {
49938
50545
  };
49939
50546
  }
49940
50547
  function checkAutoUpdates() {
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");
50548
+ const unattended = (0, import_node_fs54.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs54.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
50549
+ const dnfAuto = (0, import_node_fs54.existsSync)("/etc/dnf/automatic.conf");
49943
50550
  if (unattended || dnfAuto) {
49944
50551
  return {
49945
50552
  key: "auto-updates",
@@ -50065,7 +50672,7 @@ function checkFail2ban() {
50065
50672
  explanation: "fail2ban is installed and running."
50066
50673
  };
50067
50674
  }
50068
- if ((0, import_node_fs53.existsSync)("/etc/fail2ban/fail2ban.conf")) {
50675
+ if ((0, import_node_fs54.existsSync)("/etc/fail2ban/fail2ban.conf")) {
50069
50676
  return {
50070
50677
  key: checkKey,
50071
50678
  status: "warn",
@@ -50251,9 +50858,9 @@ async function hardenCommand(opts) {
50251
50858
  }
50252
50859
 
50253
50860
  // src/core/patches/index.ts
50254
- var import_node_fs54 = require("fs");
50255
- var import_node_path40 = require("path");
50256
- var import_node_child_process21 = require("child_process");
50861
+ var import_node_fs55 = require("fs");
50862
+ var import_node_path41 = require("path");
50863
+ var import_node_child_process22 = require("child_process");
50257
50864
  var import_node_util5 = require("util");
50258
50865
 
50259
50866
  // src/core/patches/dpkg-version.ts
@@ -50313,7 +50920,7 @@ var STALE_AFTER_MS = 2 * 864e5;
50313
50920
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
50314
50921
  var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
50315
50922
  var defaultExec = async (file, args) => {
50316
- const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process21.execFile)(file, args, {
50923
+ const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process22.execFile)(file, args, {
50317
50924
  timeout: 12e4,
50318
50925
  maxBuffer: 32 * 1024 * 1024,
50319
50926
  env: { ...process.env, LC_ALL: "C" }
@@ -50412,9 +51019,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
50412
51019
  function newestReleaseMtime(dir) {
50413
51020
  try {
50414
51021
  let newest = 0;
50415
- for (const name of (0, import_node_fs54.readdirSync)(dir)) {
51022
+ for (const name of (0, import_node_fs55.readdirSync)(dir)) {
50416
51023
  if (!/Release$/.test(name)) continue;
50417
- newest = Math.max(newest, (0, import_node_fs54.statSync)((0, import_node_path40.join)(dir, name)).mtimeMs);
51024
+ newest = Math.max(newest, (0, import_node_fs55.statSync)((0, import_node_path41.join)(dir, name)).mtimeMs);
50418
51025
  }
50419
51026
  return newest > 0 ? new Date(newest) : null;
50420
51027
  } catch {
@@ -50431,7 +51038,7 @@ async function checkPatches(opts = {}) {
50431
51038
  let osText = opts.osRelease;
50432
51039
  if (osText === void 0) {
50433
51040
  try {
50434
- osText = (0, import_node_fs54.readFileSync)("/etc/os-release", "utf-8");
51041
+ osText = (0, import_node_fs55.readFileSync)("/etc/os-release", "utf-8");
50435
51042
  } catch {
50436
51043
  osText = "";
50437
51044
  }
@@ -50658,26 +51265,26 @@ async function patchesCommand(opts) {
50658
51265
 
50659
51266
  // src/commands/feeds.ts
50660
51267
  var import_node_net18 = require("net");
50661
- var import_node_path42 = require("path");
51268
+ var import_node_path43 = require("path");
50662
51269
  init_paths();
50663
51270
 
50664
51271
  // src/commands/feeds-resolver.ts
50665
- var import_node_child_process22 = require("child_process");
50666
- var import_node_fs55 = require("fs");
50667
- var import_node_path41 = require("path");
51272
+ var import_node_child_process23 = require("child_process");
51273
+ var import_node_fs56 = require("fs");
51274
+ var import_node_path42 = require("path");
50668
51275
  var realIO = {
50669
- exists: (p) => (0, import_node_fs55.existsSync)(p),
51276
+ exists: (p) => (0, import_node_fs56.existsSync)(p),
50670
51277
  read: (p) => {
50671
51278
  try {
50672
- return (0, import_node_fs55.readFileSync)(p, "utf-8");
51279
+ return (0, import_node_fs56.readFileSync)(p, "utf-8");
50673
51280
  } catch {
50674
51281
  return null;
50675
51282
  }
50676
51283
  },
50677
- write: (p, c) => (0, import_node_fs55.writeFileSync)(p, c),
50678
- remove: (p) => (0, import_node_fs55.rmSync)(p, { force: true }),
51284
+ write: (p, c) => (0, import_node_fs56.writeFileSync)(p, c),
51285
+ remove: (p) => (0, import_node_fs56.rmSync)(p, { force: true }),
50679
51286
  run: (cmd, args) => {
50680
- const r = (0, import_node_child_process22.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
51287
+ const r = (0, import_node_child_process23.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
50681
51288
  return { code: r.status ?? 1, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
50682
51289
  }
50683
51290
  };
@@ -50685,17 +51292,17 @@ var APPARMOR_LOCAL = "/etc/apparmor.d/local/usr.sbin.unbound";
50685
51292
  var APPARMOR_PROFILE = "/etc/apparmor.d/usr.sbin.unbound";
50686
51293
  function hookContent(resolver, stateDir) {
50687
51294
  const head = "# Installed by `threatcrush feeds resolver install`; `threatcrush feeds resolver remove` takes it out.\n";
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)}"
51295
+ return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path42.join)(stateDir, RESOLVER_FILES.hosts)}
51296
+ ` : `${head}include: "${(0, import_node_path42.join)(stateDir, RESOLVER_FILES.unbound)}"
50690
51297
  `;
50691
51298
  }
50692
51299
  function apparmorRule(stateDir) {
50693
- return ` ${(0, import_node_path41.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
51300
+ return ` ${(0, import_node_path42.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
50694
51301
  }
50695
51302
  function detectResolvers(io = realIO) {
50696
51303
  const found = [];
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");
51304
+ if (io.exists((0, import_node_path42.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
51305
+ if (io.exists((0, import_node_path42.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
50699
51306
  return found;
50700
51307
  }
50701
51308
  function check(resolver, io) {
@@ -50708,7 +51315,7 @@ function restartIfActive(resolver, io) {
50708
51315
  }
50709
51316
  function installHook(resolver, stateDir, io = realIO) {
50710
51317
  const hook = RESOLVER_HOOKS[resolver];
50711
- const file = (0, import_node_path41.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
51318
+ const file = (0, import_node_path42.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
50712
51319
  if (!io.exists(file)) io.write(file, resolver === "dnsmasq" ? hostsBlocklist([]) : unboundBlocklist([]));
50713
51320
  io.write(hook, hookContent(resolver, stateDir));
50714
51321
  if (resolver === "unbound" && io.exists(APPARMOR_LOCAL)) {
@@ -50769,8 +51376,8 @@ function resolverCommand(sub, stateDir, io = realIO) {
50769
51376
  }
50770
51377
  return failed ? 1 : 0;
50771
51378
  }
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));
51379
+ const hosts = io.read((0, import_node_path42.join)(stateDir, RESOLVER_FILES.hosts));
51380
+ const unbound = io.read((0, import_node_path42.join)(stateDir, RESOLVER_FILES.unbound));
50774
51381
  console.log(` resolvers here: ${found.join(", ") || "none that can block (systemd-resolved only?)"}`);
50775
51382
  for (const r of ["dnsmasq", "unbound"]) {
50776
51383
  console.log(` ${r.padEnd(8)} hook ${io.exists(RESOLVER_HOOKS[r]) ? source_default.green("installed") : source_default.gray("not installed")}`);
@@ -50782,11 +51389,11 @@ function resolverCommand(sub, stateDir, io = realIO) {
50782
51389
  // src/commands/feeds.ts
50783
51390
  async function loadSet() {
50784
51391
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
50785
- const path2 = (0, import_node_path42.join)(dir, "threat-feeds.json");
51392
+ const path2 = (0, import_node_path43.join)(dir, "threat-feeds.json");
50786
51393
  const set = readFeedCache(path2);
50787
51394
  if (set) return { set, from: path2 };
50788
51395
  }
50789
- const settings = threatFeedSettings(loadConfig((0, import_node_path42.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
51396
+ const settings = threatFeedSettings(loadConfig((0, import_node_path43.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
50790
51397
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
50791
51398
  }
50792
51399
  async function feedsCommand(action, value, opts) {
@@ -50830,21 +51437,21 @@ async function feedsCommand(action, value, opts) {
50830
51437
  }
50831
51438
 
50832
51439
  // src/commands/tor.ts
50833
- var import_node_fs56 = require("fs");
51440
+ var import_node_fs57 = require("fs");
50834
51441
  var import_node_net19 = require("net");
50835
- var import_node_path43 = require("path");
51442
+ var import_node_path44 = require("path");
50836
51443
  init_paths();
50837
51444
  async function torCommand(action, value, opts) {
50838
51445
  let exits = /* @__PURE__ */ new Set();
50839
51446
  let from = "";
50840
51447
  let updated = null;
50841
51448
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
50842
- const path2 = (0, import_node_path43.join)(dir, "tor-exits.txt");
51449
+ const path2 = (0, import_node_path44.join)(dir, "tor-exits.txt");
50843
51450
  try {
50844
- if (!(0, import_node_fs56.existsSync)(path2)) continue;
50845
- exits = parseTorExitList((0, import_node_fs56.readFileSync)(path2, "utf-8"));
51451
+ if (!(0, import_node_fs57.existsSync)(path2)) continue;
51452
+ exits = parseTorExitList((0, import_node_fs57.readFileSync)(path2, "utf-8"));
50846
51453
  from = path2;
50847
- updated = (0, import_node_fs56.statSync)(path2).mtime;
51454
+ updated = (0, import_node_fs57.statSync)(path2).mtime;
50848
51455
  break;
50849
51456
  } catch {
50850
51457
  }
@@ -50860,7 +51467,7 @@ async function torCommand(action, value, opts) {
50860
51467
  } catch {
50861
51468
  }
50862
51469
  }
50863
- const remediation = loadConfig((0, import_node_path43.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).remediation;
51470
+ const remediation = loadConfig((0, import_node_path44.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).remediation;
50864
51471
  const ban = remediation?.block_tor_ssh !== false && remediation?.enabled !== false;
50865
51472
  if (action === "check") {
50866
51473
  if (!value || !(0, import_node_net19.isIP)(value)) {
@@ -50892,13 +51499,13 @@ async function torCommand(action, value, opts) {
50892
51499
 
50893
51500
  // src/commands/reputation.ts
50894
51501
  var import_node_os16 = require("os");
50895
- var import_node_fs57 = require("fs");
50896
- var import_node_path44 = require("path");
51502
+ var import_node_fs58 = require("fs");
51503
+ var import_node_path45 = require("path");
50897
51504
  var API_URL7 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
50898
- var CONFIG_PATH4 = (0, import_node_path44.join)((0, import_node_os16.homedir)(), ".threatcrush", "config.json");
51505
+ var CONFIG_PATH4 = (0, import_node_path45.join)((0, import_node_os16.homedir)(), ".threatcrush", "config.json");
50899
51506
  function readConfig3() {
50900
51507
  try {
50901
- return JSON.parse((0, import_node_fs57.readFileSync)(CONFIG_PATH4, "utf-8"));
51508
+ return JSON.parse((0, import_node_fs58.readFileSync)(CONFIG_PATH4, "utf-8"));
50902
51509
  } catch {
50903
51510
  return {};
50904
51511
  }
@@ -51086,7 +51693,7 @@ async function reputationSubscribeCommand(opts) {
51086
51693
  }
51087
51694
 
51088
51695
  // src/commands/privileged.ts
51089
- var import_node_fs58 = require("fs");
51696
+ var import_node_fs59 = require("fs");
51090
51697
  init_paths();
51091
51698
  var SEV2 = {
51092
51699
  critical: source_default.red.bold,
@@ -51099,19 +51706,19 @@ async function privilegedCommand(opts) {
51099
51706
  const snapshot = takeSnapshot({
51100
51707
  readFile: (p) => {
51101
51708
  try {
51102
- return (0, import_node_fs58.readFileSync)(p, "utf-8");
51709
+ return (0, import_node_fs59.readFileSync)(p, "utf-8");
51103
51710
  } catch {
51104
51711
  return null;
51105
51712
  }
51106
51713
  },
51107
51714
  readDir: (p) => {
51108
51715
  try {
51109
- return (0, import_node_fs58.readdirSync)(p);
51716
+ return (0, import_node_fs59.readdirSync)(p);
51110
51717
  } catch {
51111
51718
  return null;
51112
51719
  }
51113
51720
  },
51114
- exists: (p) => (0, import_node_fs58.existsSync)(p)
51721
+ exists: (p) => (0, import_node_fs59.existsSync)(p)
51115
51722
  });
51116
51723
  let events = [];
51117
51724
  let ledgerNote = "";
@@ -51293,7 +51900,7 @@ async function allowlistCommand(opts) {
51293
51900
  }
51294
51901
 
51295
51902
  // src/commands/abuse.ts
51296
- var import_node_fs59 = require("fs");
51903
+ var import_node_fs60 = require("fs");
51297
51904
  init_paths();
51298
51905
  function rows(records) {
51299
51906
  if (records.length === 0) {
@@ -51353,7 +51960,7 @@ function abuseRetractCommand(id, opts = {}) {
51353
51960
  );
51354
51961
  }
51355
51962
  function abuseStatusCommand(opts = {}) {
51356
- const config = loadConfig((0, import_node_fs59.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
51963
+ const config = loadConfig((0, import_node_fs60.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
51357
51964
  const cfg = resolveConfig(config.abuse_reporter);
51358
51965
  const hasKey2 = Boolean(cfg.keys.abuseipdb || cfg.keys.stopforumspam);
51359
51966
  const active2 = cfg.enabled && (cfg.dryRun || hasKey2);
@@ -51376,11 +51983,11 @@ function abuseStatusCommand(opts = {}) {
51376
51983
  init_paths();
51377
51984
 
51378
51985
  // src/upgrade.ts
51379
- var import_node_child_process23 = require("child_process");
51986
+ var import_node_child_process24 = require("child_process");
51380
51987
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
51381
51988
  var defaultRunner = (cmd) => {
51382
51989
  try {
51383
- return (0, import_node_child_process23.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
51990
+ return (0, import_node_child_process24.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
51384
51991
  } catch {
51385
51992
  return null;
51386
51993
  }
@@ -51521,9 +52128,9 @@ function installUserAgent(target = globalThis) {
51521
52128
  }
51522
52129
 
51523
52130
  // src/core/cloud-upload.ts
51524
- var import_node_child_process24 = require("child_process");
52131
+ var import_node_child_process25 = require("child_process");
51525
52132
  var import_node_os17 = require("os");
51526
- var import_node_path45 = require("path");
52133
+ var import_node_path46 = require("path");
51527
52134
  init_cli_config();
51528
52135
  function uploadDisabled(upload, env3 = process.env) {
51529
52136
  if (upload === false) return true;
@@ -51542,8 +52149,8 @@ function cleanUrl(raw) {
51542
52149
  return raw.split(/[?#]/)[0];
51543
52150
  }
51544
52151
  }
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);
52152
+ function repoTarget(path2, run = (args) => (0, import_node_child_process25.execFileSync)("git", args, { cwd: (0, import_node_path46.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
52153
+ const abs = (0, import_node_path46.resolve)(path2);
51547
52154
  try {
51548
52155
  const root = run(["rev-parse", "--show-toplevel"]);
51549
52156
  const sub = abs === root ? "." : abs.slice(root.length + 1);
@@ -51915,25 +52522,25 @@ ${source_default.dim(" C R U S H")}
51915
52522
  var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
51916
52523
  var PKG_NAME2 = "@profullstack/threatcrush";
51917
52524
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
51918
- var INSTALL_CONFIG_PATH = (0, import_node_path46.join)((0, import_node_os18.homedir)(), ".threatcrush", "install.json");
52525
+ var INSTALL_CONFIG_PATH = (0, import_node_path47.join)((0, import_node_os18.homedir)(), ".threatcrush", "install.json");
51919
52526
  function detectPackageManager() {
51920
52527
  try {
51921
- const npmGlobal = (0, import_node_child_process25.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
52528
+ const npmGlobal = (0, import_node_child_process26.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
51922
52529
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
51923
52530
  } catch {
51924
52531
  }
51925
52532
  try {
51926
- (0, import_node_child_process25.execSync)("pnpm --version", { stdio: "pipe" });
52533
+ (0, import_node_child_process26.execSync)("pnpm --version", { stdio: "pipe" });
51927
52534
  return "pnpm";
51928
52535
  } catch {
51929
52536
  }
51930
52537
  try {
51931
- (0, import_node_child_process25.execSync)("yarn --version", { stdio: "pipe" });
52538
+ (0, import_node_child_process26.execSync)("yarn --version", { stdio: "pipe" });
51932
52539
  return "yarn";
51933
52540
  } catch {
51934
52541
  }
51935
52542
  try {
51936
- (0, import_node_child_process25.execSync)("bun --version", { stdio: "pipe" });
52543
+ (0, import_node_child_process26.execSync)("bun --version", { stdio: "pipe" });
51937
52544
  return "bun";
51938
52545
  } catch {
51939
52546
  }
@@ -51941,14 +52548,14 @@ function detectPackageManager() {
51941
52548
  }
51942
52549
  function readInstallConfig() {
51943
52550
  try {
51944
- return JSON.parse((0, import_node_fs60.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
52551
+ return JSON.parse((0, import_node_fs61.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
51945
52552
  } catch {
51946
52553
  return {};
51947
52554
  }
51948
52555
  }
51949
52556
  function packageLooksInstalled(pm, pkgName) {
51950
52557
  try {
51951
- const output = (0, import_node_child_process25.execSync)(globalListCommand(pm, pkgName), {
52558
+ const output = (0, import_node_child_process26.execSync)(globalListCommand(pm, pkgName), {
51952
52559
  encoding: "utf-8",
51953
52560
  stdio: ["pipe", "pipe", "pipe"]
51954
52561
  });
@@ -52051,14 +52658,14 @@ async function promoteUnprivilegedDaemon() {
52051
52658
  function restartSystemdDaemon() {
52052
52659
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
52053
52660
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
52054
- if (!asRoot && (0, import_node_child_process25.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
52661
+ if (!asRoot && (0, import_node_child_process26.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
52055
52662
  const [cmd, ...args] = argv;
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;
52663
+ if ((0, import_node_child_process26.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
52664
+ return (0, import_node_child_process26.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
52058
52665
  }
52059
52666
  function execQuiet(cmd) {
52060
52667
  try {
52061
- return (0, import_node_child_process25.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
52668
+ return (0, import_node_child_process26.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
52062
52669
  } catch {
52063
52670
  return null;
52064
52671
  }
@@ -52354,7 +52961,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
52354
52961
  program2.command("logs").description("Tail daemon logs").action(async () => {
52355
52962
  console.log(LOGO2);
52356
52963
  const logPath2 = PATHS.logFile;
52357
- if (!(0, import_node_fs60.existsSync)(logPath2)) {
52964
+ if (!(0, import_node_fs61.existsSync)(logPath2)) {
52358
52965
  console.log(source_default.yellow(` No log file found at ${logPath2}`));
52359
52966
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
52360
52967
  return;
@@ -52362,7 +52969,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
52362
52969
  console.log(source_default.green(` Tailing ${logPath2}...
52363
52970
  `));
52364
52971
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
52365
- (0, import_node_child_process25.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
52972
+ (0, import_node_child_process26.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
52366
52973
  });
52367
52974
  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) => {
52368
52975
  console.log(LOGO2);
@@ -52374,7 +52981,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
52374
52981
  for (const cmd of commands2) {
52375
52982
  console.log(source_default.green(` \u2192 ${cmd}
52376
52983
  `));
52377
- (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
52984
+ (0, import_node_child_process26.execSync)(cmd, { stdio: "inherit" });
52378
52985
  }
52379
52986
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
52380
52987
  await reportIfStillStale();
@@ -52399,7 +53006,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
52399
53006
  for (const cmd of commands) {
52400
53007
  console.log(source_default.green(` \u2192 ${cmd}
52401
53008
  `));
52402
- (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
53009
+ (0, import_node_child_process26.execSync)(cmd, { stdio: "inherit" });
52403
53010
  }
52404
53011
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
52405
53012
  if (installMode === "desktop") {
@@ -52450,7 +53057,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
52450
53057
  for (const cmd of commands) {
52451
53058
  console.log(source_default.green(` \u2192 ${cmd}
52452
53059
  `));
52453
- (0, import_node_child_process25.execSync)(cmd, { stdio: "inherit" });
53060
+ (0, import_node_child_process26.execSync)(cmd, { stdio: "inherit" });
52454
53061
  }
52455
53062
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
52456
53063
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -52527,10 +53134,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
52527
53134
  });
52528
53135
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
52529
53136
  console.log(LOGO2);
52530
- const configPath = (0, import_node_path46.join)((0, import_node_os18.homedir)(), ".threatcrush", "config.json");
53137
+ const configPath = (0, import_node_path47.join)((0, import_node_os18.homedir)(), ".threatcrush", "config.json");
52531
53138
  let email = "";
52532
53139
  try {
52533
- const config = JSON.parse((0, import_node_fs60.readFileSync)(configPath, "utf-8"));
53140
+ const config = JSON.parse((0, import_node_fs61.readFileSync)(configPath, "utf-8"));
52534
53141
  email = config.email || "";
52535
53142
  } catch {
52536
53143
  }
@@ -52547,9 +53154,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
52547
53154
  return;
52548
53155
  }
52549
53156
  try {
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));
53157
+ const dir = (0, import_node_path47.join)((0, import_node_os18.homedir)(), ".threatcrush");
53158
+ if (!(0, import_node_fs61.existsSync)(dir)) (0, import_node_fs61.mkdirSync)(dir, { recursive: true });
53159
+ (0, import_node_fs61.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
52553
53160
  console.log(source_default.dim(` Saved email to ${configPath}`));
52554
53161
  } catch {
52555
53162
  }