@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/daemon.js CHANGED
@@ -2026,10 +2026,10 @@ var require_toml = __commonJS({
2026
2026
  });
2027
2027
 
2028
2028
  // src/daemon/index.ts
2029
- var import_node_fs34 = require("fs");
2030
- var import_node_child_process12 = require("child_process");
2029
+ var import_node_fs35 = require("fs");
2030
+ var import_node_child_process13 = require("child_process");
2031
2031
  var import_node_os6 = require("os");
2032
- var import_node_path26 = require("path");
2032
+ var import_node_path27 = require("path");
2033
2033
  var import_node_util = require("util");
2034
2034
 
2035
2035
  // src/daemon/paths.ts
@@ -9564,6 +9564,39 @@ function parseNginxLog(line) {
9564
9564
  fields
9565
9565
  };
9566
9566
  }
9567
+ function parseCaddyAccessLog(line) {
9568
+ let entry;
9569
+ try {
9570
+ entry = JSON.parse(line);
9571
+ } catch {
9572
+ return null;
9573
+ }
9574
+ if (entry.logger !== "http.log.access") return null;
9575
+ const request = entry.request;
9576
+ if (!request || typeof request !== "object" || Array.isArray(request)) return null;
9577
+ const req = request;
9578
+ const host = typeof req.host === "string" ? req.host.toLowerCase() : "";
9579
+ if (host !== "agent.database.pit.world") return null;
9580
+ const required = [req.method, req.uri, entry.status, entry.size];
9581
+ if (required.some((value) => typeof value !== "string" && typeof value !== "number")) return null;
9582
+ const timestamp = typeof entry.ts === "number" ? new Date(entry.ts * 1e3) : /* @__PURE__ */ new Date();
9583
+ return {
9584
+ timestamp: Number.isNaN(timestamp.getTime()) ? /* @__PURE__ */ new Date() : timestamp,
9585
+ raw: line,
9586
+ source: "nginx",
9587
+ fields: {
9588
+ ip: typeof req.client_ip === "string" ? req.client_ip : typeof req.remote_ip === "string" ? req.remote_ip : "",
9589
+ method: String(req.method),
9590
+ path: String(req.uri).split("?")[0],
9591
+ protocol: typeof req.proto === "string" ? req.proto : "",
9592
+ status: String(entry.status),
9593
+ size: String(entry.size),
9594
+ referer: "",
9595
+ user_agent: "",
9596
+ host
9597
+ }
9598
+ };
9599
+ }
9567
9600
  function parseAuthLog(line) {
9568
9601
  const match = line.match(AUTH_REGEX);
9569
9602
  if (!match) return null;
@@ -9610,10 +9643,20 @@ function sshdPeerIp(message) {
9610
9643
  function classifySshAuth(entry) {
9611
9644
  const { ip, user, message } = entry.fields;
9612
9645
  if (/failed password/i.test(message)) {
9613
- return { severity: "high", message: `Failed SSH login for ${user || "unknown"} from ${ip || "unknown"}`, source_ip: ip };
9646
+ return {
9647
+ severity: "high",
9648
+ message: `Failed SSH login for ${user || "unknown"} from ${ip || "unknown"}`,
9649
+ source_ip: ip,
9650
+ ...user ? { details: { user } } : {}
9651
+ };
9614
9652
  }
9615
9653
  if (/invalid user/i.test(message)) {
9616
- return { severity: "high", message: `Invalid SSH user: ${user || "unknown"} from ${ip || "unknown"}`, source_ip: ip };
9654
+ return {
9655
+ severity: "high",
9656
+ message: `Invalid SSH user: ${user || "unknown"} from ${ip || "unknown"}`,
9657
+ source_ip: ip,
9658
+ ...user ? { details: { user } } : {}
9659
+ };
9617
9660
  }
9618
9661
  if (/accepted/i.test(message)) {
9619
9662
  const login = parseAcceptedLogin(message);
@@ -9622,7 +9665,7 @@ function classifySshAuth(entry) {
9622
9665
  severity: "info",
9623
9666
  message: `SSH login accepted for ${login?.user || user || "unknown"}`,
9624
9667
  source_ip: sourceIp,
9625
- ...login ? { details: { ssh_user: login.user, auth_method: login.method, port: login.port, ...login.key_type ? { key_type: login.key_type } : {}, ...login.fingerprint ? { fingerprint: login.fingerprint } : {} } } : {}
9668
+ ...login ? { details: { user: login.user, ssh_user: login.user, auth_method: login.method, port: login.port, ...login.key_type ? { key_type: login.key_type } : {}, ...login.fingerprint ? { fingerprint: login.fingerprint } : {} } } : {}
9626
9669
  };
9627
9670
  }
9628
9671
  return null;
@@ -9709,8 +9752,11 @@ var DEFAULT_SOURCES = [
9709
9752
  { path: "/var/log/auth.log", module: "ssh-guard", category: "auth" },
9710
9753
  { path: "/var/log/secure", module: "ssh-guard", category: "auth" },
9711
9754
  { path: "/var/log/nginx/access.log", module: "log-watcher", category: "web" },
9755
+ { path: "/var/log/caddy/agent.database.pit.world.access.log", module: "log-watcher", category: "web" },
9712
9756
  { path: "/var/log/syslog", module: "log-watcher", category: "system" }
9713
9757
  ];
9758
+ var AGENTDB_API_PATH = /^\/v1\/(?:list_databases|inspect_schema|query_readonly|explain_query|cluster_health|backup_status|audit\/events|backup\/(?:create|verify)|tokens(?:\/revoke)?)$/;
9759
+ var AGENTDB_HOST = "agent.database.pit.world";
9714
9760
  var LogWatcher = class {
9715
9761
  constructor(bus2, sources = DEFAULT_SOURCES) {
9716
9762
  this.bus = bus2;
@@ -9771,7 +9817,8 @@ var LogWatcher = class {
9771
9817
  });
9772
9818
  }
9773
9819
  process(line, src) {
9774
- const parsed = autoDetectParser(line);
9820
+ const caddy = parseCaddyAccessLog(line);
9821
+ const parsed = caddy ?? autoDetectParser(line);
9775
9822
  if (!parsed) return;
9776
9823
  let severity = "info";
9777
9824
  let message = line;
@@ -9789,7 +9836,7 @@ var LogWatcher = class {
9789
9836
  ({ severity, message, source_ip: sourceIp } = verdict);
9790
9837
  if (verdict.details) Object.assign(details, verdict.details);
9791
9838
  } else if (parsed.source === "nginx") {
9792
- const entry = parseNginxLog(line);
9839
+ const entry = caddy ?? parseNginxLog(line);
9793
9840
  if (!entry) return;
9794
9841
  sourceIp = entry.fields.ip;
9795
9842
  const status = parseInt(entry.fields.status, 10);
@@ -9803,6 +9850,16 @@ var LogWatcher = class {
9803
9850
  if (Number.isFinite(status)) details.status = status;
9804
9851
  if (entry.fields.method) details.method = entry.fields.method;
9805
9852
  if (entry.fields.path) details.url = entry.fields.path.slice(0, 2048);
9853
+ const agentDbHost = entry.fields.host?.toLowerCase();
9854
+ const isAgentDbApi = AGENTDB_API_PATH.test(reqPath) && (!agentDbHost || agentDbHost === AGENTDB_HOST);
9855
+ if (isAgentDbApi) {
9856
+ details.url = reqPath;
9857
+ details.service = "agentdb";
9858
+ const responseBytes = Number(entry.fields.size);
9859
+ if (Number.isSafeInteger(responseBytes) && responseBytes >= 0) {
9860
+ details.response_bytes = responseBytes;
9861
+ }
9862
+ }
9806
9863
  if (crs.score > 0) {
9807
9864
  Object.assign(details, {
9808
9865
  attack_type: crs.attackType,
@@ -9813,7 +9870,10 @@ var LogWatcher = class {
9813
9870
  }
9814
9871
  if (attack) {
9815
9872
  severity = attack;
9816
- message = `Attack [${type}]: ${entry.fields.method} ${entry.fields.path}`;
9873
+ message = `Attack [${type}]: ${entry.fields.method} ${isAgentDbApi ? reqPath : entry.fields.path}`;
9874
+ } else if (isAgentDbApi) {
9875
+ severity = status >= 500 ? "medium" : status >= 400 ? "low" : "info";
9876
+ message = `AgentDB API ${status}: ${entry.fields.method} ${reqPath}`;
9817
9877
  } else if (status >= 500) {
9818
9878
  severity = "medium";
9819
9879
  message = `Server error ${status}: ${entry.fields.method} ${entry.fields.path}`;
@@ -9846,9 +9906,50 @@ var LogWatcher = class {
9846
9906
  }
9847
9907
  };
9848
9908
 
9909
+ // src/daemon/watchers/journal-provenance.ts
9910
+ var JournalProvenance = class {
9911
+ peers = /* @__PURE__ */ new Map();
9912
+ fields(entry) {
9913
+ const details = {};
9914
+ for (const [source, dest] of Object.entries({ _PID: "pid", _BOOT_ID: "boot_id", __CURSOR: "journal_cursor", _AUDIT_SESSION: "audit_session", _AUDIT_LOGINUID: "login_uid" })) {
9915
+ if (typeof entry[source] === "string") details[dest] = entry[source].slice(0, 200);
9916
+ }
9917
+ const trusted = entry._UID === "0" && ["sshd", "sshd-session", "sshd-auth"].includes(String(entry._COMM));
9918
+ if (!trusted || typeof entry.MESSAGE !== "string") return { details };
9919
+ const at = Number(entry.__REALTIME_TIMESTAMP) / 1e3;
9920
+ const key = typeof entry._BOOT_ID === "string" && typeof entry._PID === "string" ? `${entry._BOOT_ID}:${entry._PID}` : null;
9921
+ for (const [k, peer2] of this.peers) if (!Number.isFinite(at) || at - peer2.at > 12e4 || at < peer2.at) this.peers.delete(k);
9922
+ const direct = sshdPeerIp(entry.MESSAGE);
9923
+ if (direct && key && Number.isFinite(at)) {
9924
+ this.peers.delete(key);
9925
+ this.peers.set(key, { ip: direct, at });
9926
+ if (this.peers.size > 512) this.peers.delete(this.peers.keys().next().value);
9927
+ }
9928
+ const peer = key ? this.peers.get(key) : void 0;
9929
+ const source_ip = direct ?? (peer && Number.isFinite(at) && at >= peer.at && at - peer.at <= 12e4 ? peer.ip : void 0);
9930
+ if (source_ip) details.source_ip_basis = direct ? "current sshd record" : "same boot and sshd PID within 120 seconds";
9931
+ return { ...source_ip ? { source_ip } : {}, details };
9932
+ }
9933
+ };
9934
+
9849
9935
  // src/daemon/watchers/journal-watcher.ts
9850
9936
  var import_node_child_process = require("child_process");
9851
9937
  var SSHD_COMMS = ["sshd", "sshd-session"];
9938
+ var accountNames = /* @__PURE__ */ new Map();
9939
+ function accountNameForUid(value) {
9940
+ if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
9941
+ if (accountNames.has(value)) return accountNames.get(value) ?? null;
9942
+ const result = (0, import_node_child_process.spawnSync)("getent", ["passwd", value], {
9943
+ encoding: "utf-8",
9944
+ timeout: 1e3,
9945
+ maxBuffer: 4096,
9946
+ stdio: ["ignore", "pipe", "ignore"]
9947
+ });
9948
+ const name = result.status === 0 ? result.stdout.split(":", 1)[0] : "";
9949
+ const resolved = /^[a-zA-Z0-9_.@-]{1,256}$/.test(name) ? name : null;
9950
+ accountNames.set(value, resolved);
9951
+ return resolved;
9952
+ }
9852
9953
  function isSshdRecord(entry) {
9853
9954
  return entry._UID === "0" && SSHD_COMMS.includes(entry._COMM);
9854
9955
  }
@@ -9857,6 +9958,7 @@ function sshEventFromJournal(entry) {
9857
9958
  const timestamp = realtimeToDate(entry.__REALTIME_TIMESTAMP) || /* @__PURE__ */ new Date();
9858
9959
  const verdict = classifySshAuth(parseAuthMessage(entry._COMM, entry.MESSAGE, timestamp));
9859
9960
  if (!verdict) return null;
9961
+ const systemAccount = accountNameForUid(entry._UID);
9860
9962
  return {
9861
9963
  timestamp,
9862
9964
  module: "ssh-guard",
@@ -9864,7 +9966,12 @@ function sshEventFromJournal(entry) {
9864
9966
  severity: verdict.severity,
9865
9967
  message: verdict.message,
9866
9968
  source_ip: verdict.source_ip,
9867
- ...verdict.details ? { details: verdict.details } : {}
9969
+ details: {
9970
+ ...verdict.details ?? {},
9971
+ ...typeof entry._UID === "string" && /^\d+$/.test(entry._UID) ? { system_uid: entry._UID } : {},
9972
+ ...systemAccount ? { system_account: systemAccount } : {},
9973
+ ...typeof entry._COMM === "string" ? { process: entry._COMM } : {}
9974
+ }
9868
9975
  };
9869
9976
  }
9870
9977
  function sshdLineFromJournal(entry) {
@@ -9884,6 +9991,7 @@ var JournalWatcher = class _JournalWatcher {
9884
9991
  buffer = "";
9885
9992
  sshdBuffer = "";
9886
9993
  moduleName = "user-journal";
9994
+ provenance = new JournalProvenance();
9887
9995
  active = false;
9888
9996
  // When the daemon runs as root (system mode), tail the SYSTEM journal so
9889
9997
  // we pick up sshd / sudo / kernel / UFW events. Falling back to --user
@@ -9942,8 +10050,9 @@ var JournalWatcher = class _JournalWatcher {
9942
10050
  this.sshdBuffer = this.drain(this.sshdBuffer + chunk, (entry) => {
9943
10051
  const line = sshdLineFromJournal(entry);
9944
10052
  if (line) this.bus.sshdLine?.(line);
10053
+ const context = this.provenance.fields(entry);
9945
10054
  const event = sshEventFromJournal(entry);
9946
- if (event) this.emit(event);
10055
+ if (event) this.emit({ ...event, source_ip: event.source_ip ?? context.source_ip, details: { ...event.details, ...context.details } });
9947
10056
  });
9948
10057
  });
9949
10058
  child.on("error", () => {
@@ -9990,6 +10099,7 @@ var JournalWatcher = class _JournalWatcher {
9990
10099
  return buffer;
9991
10100
  }
9992
10101
  handleEntry(entry) {
10102
+ const context = this.provenance.fields(entry);
9993
10103
  if (this.sshdProc && isSshdRecord(entry)) return;
9994
10104
  const message = entry.MESSAGE;
9995
10105
  if (!message) return;
@@ -10002,7 +10112,17 @@ var JournalWatcher = class _JournalWatcher {
10002
10112
  module: this.moduleName,
10003
10113
  category: "system",
10004
10114
  severity: bumpedSeverity,
10005
- message: `[${ident}] ${message}`.slice(0, 500)
10115
+ ...context.source_ip ? { source_ip: context.source_ip } : {},
10116
+ message: `[${ident}] ${message}`.slice(0, 500),
10117
+ details: {
10118
+ ...context.details,
10119
+ ...typeof entry._UID === "string" && /^\d+$/.test(entry._UID) ? { system_uid: entry._UID } : {},
10120
+ ...accountNameForUid(entry._UID) ? { system_account: accountNameForUid(entry._UID) } : {},
10121
+ ...typeof entry._COMM === "string" ? { process: entry._COMM } : {},
10122
+ ...typeof entry.SYSLOG_IDENTIFIER === "string" ? { identifier: entry.SYSLOG_IDENTIFIER } : {},
10123
+ ...typeof entry._PID === "string" ? { pid: entry._PID } : {},
10124
+ ...typeof entry._SYSTEMD_UNIT === "string" ? { unit: entry._SYSTEMD_UNIT } : {}
10125
+ }
10006
10126
  });
10007
10127
  }
10008
10128
  emit(event) {
@@ -11088,6 +11208,7 @@ function parseConfigText(raw) {
11088
11208
  update: parsed.update,
11089
11209
  threat_feeds: parsed.threat_feeds,
11090
11210
  privileged: parsed.privileged,
11211
+ command_history: parsed.command_history,
11091
11212
  lightning: parsed.lightning,
11092
11213
  storage: parsed.storage,
11093
11214
  // TOML's `[abuse-reporter]` parses to a hyphenated key; expose it under
@@ -11828,7 +11949,7 @@ function str(value) {
11828
11949
  return typeof value === "string" && value ? value : void 0;
11829
11950
  }
11830
11951
  function detectionEvent(serverId, event) {
11831
- const { rule_id, username, user, description, ...rest } = event.details ?? {};
11952
+ const { rule_id, username, user, ssh_user, account, description, ...rest } = event.details ?? {};
11832
11953
  const title = event.module === "rule-engine" ? event.message.replace(/^\[DETECTION\]\s*/, "") : event.message;
11833
11954
  return {
11834
11955
  type: "detection",
@@ -11838,7 +11959,7 @@ function detectionEvent(serverId, event) {
11838
11959
  rule_id: str(rule_id) ?? event.module,
11839
11960
  description: str(description),
11840
11961
  source_ip: event.source_ip && (0, import_node_net5.isIP)(event.source_ip) ? event.source_ip : void 0,
11841
- username: str(username) ?? str(user),
11962
+ username: str(username) ?? str(user) ?? str(ssh_user) ?? str(account),
11842
11963
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
11843
11964
  detected_at: event.timestamp.toISOString()
11844
11965
  };
@@ -15231,6 +15352,14 @@ function isSuppressed(suppressions, index, ruleId) {
15231
15352
  if (!rules) return false;
15232
15353
  return rules.has("*") || rules.has(ruleId);
15233
15354
  }
15355
+ function pemPlaceholder(lines, index) {
15356
+ const first = lines[index] ?? "";
15357
+ const header = /-----BEGIN ((?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?)-----/.exec(first);
15358
+ if (!header) return false;
15359
+ const tail = [first.slice(header.index + header[0].length), ...lines.slice(index + 1, index + 21)].join("\n").replace(/\\n/g, "\n");
15360
+ const end = tail.indexOf(`-----END ${header[1]}-----`);
15361
+ return end >= 0 && ["your-pem-body-here", "your-private-key-here", "your-private-key-body-here"].includes(tail.slice(0, end).trim().toLowerCase());
15362
+ }
15234
15363
  function isTestPath(relativePath) {
15235
15364
  const p = relativePath.replace(/\\/g, "/");
15236
15365
  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);
@@ -15426,7 +15555,7 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
15426
15555
  test: inTests,
15427
15556
  "test-block": inlineTests.has(index),
15428
15557
  suppressed: foreignSecurityMark(line),
15429
- placeholder: isPlaceholderAttribute(line, value),
15558
+ placeholder: isPlaceholderAttribute(line, value) || rule.id === "secret-private-key" && pemPlaceholder(lines, index),
15430
15559
  "self-describing": rule.keywordShaped === true && describesItsOwnKey(line, value)
15431
15560
  });
15432
15561
  findings.push({
@@ -18395,10 +18524,322 @@ var PrivilegeWatch = class {
18395
18524
  }
18396
18525
  };
18397
18526
 
18398
- // src/daemon/workers/ssh-intrusion.ts
18527
+ // src/daemon/workers/command-history.ts
18399
18528
  var import_node_fs26 = require("fs");
18400
- var import_node_path20 = require("path");
18401
18529
  var import_node_child_process8 = require("child_process");
18530
+ var import_node_path20 = require("path");
18531
+ var import_node_zlib = require("zlib");
18532
+ var import_node_crypto7 = require("crypto");
18533
+ var POLL_MS2 = 6e4;
18534
+ var MAX_HISTORY_BYTES = 4 * 1024 * 1024;
18535
+ var MAX_COMPRESSED_HISTORY_BYTES = MAX_HISTORY_BYTES + 65536;
18536
+ var MAX_SNAPSHOTS = 96;
18537
+ var SNAPSHOT_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
18538
+ var HISTORY_TARGETS = {
18539
+ bash: [".bash_history"],
18540
+ zsh: [".zsh_history"],
18541
+ fish: [".local/share/fish/fish_history"],
18542
+ ksh: [".sh_history"]
18543
+ };
18544
+ function commandHistorySettings(section) {
18545
+ return { enabled: section?.enabled === true };
18546
+ }
18547
+ function historyAccounts() {
18548
+ let passwd;
18549
+ try {
18550
+ passwd = (0, import_node_child_process8.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
18551
+ } catch {
18552
+ try {
18553
+ passwd = (0, import_node_fs26.readFileSync)("/etc/passwd", "utf8");
18554
+ } catch {
18555
+ return [];
18556
+ }
18557
+ }
18558
+ const root = typeof process.getuid === "function" && process.getuid() === 0;
18559
+ return passwd.split("\n").flatMap((line) => {
18560
+ const fields = line.split(":");
18561
+ const uid = Number(fields[2]);
18562
+ const gid = Number(fields[3]);
18563
+ const name = fields[0] ?? "";
18564
+ const home = fields[5] ?? "";
18565
+ const shell = fields[6] ?? "";
18566
+ if (!Number.isInteger(uid) || !Number.isInteger(gid) || !(0, import_node_path20.isAbsolute)(home) || home === "/" || home.split("/").includes("..")) return [];
18567
+ if (root ? uid !== 0 && uid < 1e3 : uid !== process.getuid?.()) return [];
18568
+ if (!HISTORY_TARGETS[(0, import_node_path20.basename)(shell)]) return [];
18569
+ return [{ uid, gid, name, home, shell }];
18570
+ });
18571
+ }
18572
+ function descriptorPath(directoryFd, name) {
18573
+ return `/proc/self/fd/${directoryFd}/${name}`;
18574
+ }
18575
+ function openDirectoryChain(path) {
18576
+ if (!(0, import_node_path20.isAbsolute)(path) || path.split(import_node_path20.sep).includes("..")) throw new Error("directory path is not a safe absolute path");
18577
+ const flags = import_node_fs26.constants.O_RDONLY | import_node_fs26.constants.O_DIRECTORY | (import_node_fs26.constants.O_NOFOLLOW ?? 0);
18578
+ let fd = (0, import_node_fs26.openSync)("/", flags);
18579
+ try {
18580
+ for (const part of path.split(import_node_path20.sep).filter((item) => item && item !== ".")) {
18581
+ const next = (0, import_node_fs26.openSync)(descriptorPath(fd, part), flags);
18582
+ (0, import_node_fs26.closeSync)(fd);
18583
+ fd = next;
18584
+ }
18585
+ return fd;
18586
+ } catch (error) {
18587
+ (0, import_node_fs26.closeSync)(fd);
18588
+ throw error;
18589
+ }
18590
+ }
18591
+ function readExact(fd, size) {
18592
+ const data = Buffer.alloc(size);
18593
+ let offset = 0;
18594
+ while (offset < data.length) {
18595
+ const read = (0, import_node_fs26.readSync)(fd, data, offset, data.length - offset, offset);
18596
+ if (read === 0) break;
18597
+ offset += read;
18598
+ }
18599
+ return offset === data.length ? data : null;
18600
+ }
18601
+ function privateDirectory(path) {
18602
+ (0, import_node_fs26.mkdirSync)(path, { recursive: true, mode: 448 });
18603
+ const stat = (0, import_node_fs26.lstatSync)(path);
18604
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("history storage path is not a directory");
18605
+ (0, import_node_fs26.chmodSync)(path, 448);
18606
+ }
18607
+ function safeReadHistory(directoryFd, name, uid) {
18608
+ const noFollow = import_node_fs26.constants.O_NOFOLLOW ?? 0;
18609
+ const fd = (0, import_node_fs26.openSync)(descriptorPath(directoryFd, name), import_node_fs26.constants.O_RDONLY | noFollow);
18610
+ try {
18611
+ const opened = (0, import_node_fs26.fstatSync)(fd);
18612
+ if (!opened.isFile() || opened.nlink !== 1 || opened.uid !== uid) return null;
18613
+ if (opened.size > MAX_HISTORY_BYTES) throw new Error(`history file exceeds ${MAX_HISTORY_BYTES} bytes`);
18614
+ const data = readExact(fd, opened.size);
18615
+ if (data === null) return null;
18616
+ const after = (0, import_node_fs26.fstatSync)(fd);
18617
+ if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs) return null;
18618
+ return data;
18619
+ } finally {
18620
+ (0, import_node_fs26.closeSync)(fd);
18621
+ }
18622
+ }
18623
+ function atomicWrite(path, data, mode = 384, owner, parentFd) {
18624
+ const dirFd = parentFd ?? openDirectoryChain((0, import_node_path20.dirname)(path));
18625
+ const ownsDirFd = parentFd === void 0;
18626
+ const name = (0, import_node_path20.basename)(path);
18627
+ const temp = descriptorPath(dirFd, `${name}.${(0, import_node_crypto7.randomUUID)()}.tmp`);
18628
+ const destination = descriptorPath(dirFd, name);
18629
+ const noFollow = import_node_fs26.constants.O_NOFOLLOW ?? 0;
18630
+ let fd;
18631
+ try {
18632
+ fd = (0, import_node_fs26.openSync)(temp, import_node_fs26.constants.O_WRONLY | import_node_fs26.constants.O_CREAT | import_node_fs26.constants.O_EXCL | noFollow, mode);
18633
+ let offset = 0;
18634
+ while (offset < data.length) offset += (0, import_node_fs26.writeSync)(fd, data, offset, data.length - offset);
18635
+ (0, import_node_fs26.fchmodSync)(fd, mode);
18636
+ if (owner && typeof process.getuid === "function" && process.getuid() === 0) {
18637
+ (0, import_node_fs26.fchownSync)(fd, owner.uid, owner.gid);
18638
+ }
18639
+ (0, import_node_fs26.fsyncSync)(fd);
18640
+ (0, import_node_fs26.closeSync)(fd);
18641
+ fd = void 0;
18642
+ (0, import_node_fs26.renameSync)(temp, destination);
18643
+ } catch (error) {
18644
+ if (fd !== void 0) {
18645
+ try {
18646
+ (0, import_node_fs26.closeSync)(fd);
18647
+ } catch {
18648
+ }
18649
+ }
18650
+ try {
18651
+ (0, import_node_fs26.unlinkSync)(temp);
18652
+ } catch {
18653
+ }
18654
+ throw error;
18655
+ } finally {
18656
+ if (ownsDirFd) (0, import_node_fs26.closeSync)(dirFd);
18657
+ }
18658
+ }
18659
+ function readCurrentBackup(path) {
18660
+ let fd;
18661
+ try {
18662
+ const parentFd = openDirectoryChain((0, import_node_path20.dirname)(path));
18663
+ try {
18664
+ fd = (0, import_node_fs26.openSync)(descriptorPath(parentFd, (0, import_node_path20.basename)(path)), import_node_fs26.constants.O_RDONLY | (import_node_fs26.constants.O_NOFOLLOW ?? 0));
18665
+ } finally {
18666
+ (0, import_node_fs26.closeSync)(parentFd);
18667
+ }
18668
+ const stat = (0, import_node_fs26.fstatSync)(fd);
18669
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_COMPRESSED_HISTORY_BYTES) return null;
18670
+ const compressed = readExact(fd, stat.size);
18671
+ const after = (0, import_node_fs26.fstatSync)(fd);
18672
+ if (!compressed || after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) return null;
18673
+ return (0, import_node_zlib.gunzipSync)(compressed, { maxOutputLength: MAX_HISTORY_BYTES });
18674
+ } catch {
18675
+ return null;
18676
+ } finally {
18677
+ if (fd !== void 0) (0, import_node_fs26.closeSync)(fd);
18678
+ }
18679
+ }
18680
+ function compactTime(date) {
18681
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.(\d{3})Z$/, "$1Z");
18682
+ }
18683
+ var CommandHistoryWatcher = class {
18684
+ constructor(opts) {
18685
+ this.opts = opts;
18686
+ this.pollMs = Math.max(1e4, opts.pollMs ?? POLL_MS2);
18687
+ this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
18688
+ this.listAccounts = opts.listAccounts ?? historyAccounts;
18689
+ this.root = (0, import_node_path20.join)(opts.stateDir, "command-history");
18690
+ }
18691
+ opts;
18692
+ timer = null;
18693
+ scanning = false;
18694
+ pollMs;
18695
+ now;
18696
+ listAccounts;
18697
+ root;
18698
+ start() {
18699
+ if (!this.opts.settings.enabled) {
18700
+ this.opts.log("[command-history] disabled; set [command_history] enabled = true to collect local shell history");
18701
+ return;
18702
+ }
18703
+ if (process.platform !== "linux") {
18704
+ this.opts.log("[command-history] unavailable: only Linux account history paths are supported");
18705
+ return;
18706
+ }
18707
+ try {
18708
+ privateDirectory(this.root);
18709
+ } catch (error) {
18710
+ this.opts.log(`[command-history] cannot create private storage: ${error.message}`);
18711
+ return;
18712
+ }
18713
+ this.opts.log(`[command-history] enabled; private snapshots under ${this.root}, checking every ${Math.round(this.pollMs / 1e3)}s`);
18714
+ void this.scanOnce();
18715
+ this.timer = setInterval(() => {
18716
+ void this.scanOnce();
18717
+ }, this.pollMs);
18718
+ this.timer.unref();
18719
+ }
18720
+ stop() {
18721
+ if (this.timer) clearInterval(this.timer);
18722
+ this.timer = null;
18723
+ }
18724
+ async scanOnce() {
18725
+ if (this.scanning || !this.opts.settings.enabled || process.platform !== "linux") return;
18726
+ this.scanning = true;
18727
+ try {
18728
+ privateDirectory(this.root);
18729
+ for (const account of this.listAccounts()) {
18730
+ if (!Number.isInteger(account.uid) || account.uid < 0 || !(0, import_node_path20.isAbsolute)(account.home)) continue;
18731
+ const targets = this.targetsFor(account);
18732
+ for (const relative4 of targets) this.scanFile(account, relative4);
18733
+ }
18734
+ } catch (error) {
18735
+ this.opts.log(`[command-history] scan failed: ${error.message}`);
18736
+ } finally {
18737
+ this.scanning = false;
18738
+ }
18739
+ }
18740
+ targetsFor(account) {
18741
+ const targets = new Set(HISTORY_TARGETS[(0, import_node_path20.basename)(account.shell)] ?? []);
18742
+ for (const relative4 of Object.values(HISTORY_TARGETS).flat()) {
18743
+ if (targets.has(relative4)) continue;
18744
+ const path = (0, import_node_path20.join)(account.home, relative4);
18745
+ try {
18746
+ (0, import_node_fs26.lstatSync)(path);
18747
+ targets.add(relative4);
18748
+ continue;
18749
+ } catch (error) {
18750
+ if (error.code !== "ENOENT") continue;
18751
+ }
18752
+ const current = (0, import_node_path20.join)(this.root, String(account.uid), `${(0, import_node_path20.basename)(relative4)}.current.gz`);
18753
+ if (readCurrentBackup(current) !== null) targets.add(relative4);
18754
+ }
18755
+ return [...targets];
18756
+ }
18757
+ scanFile(account, relative4) {
18758
+ const path = (0, import_node_path20.join)(account.home, relative4);
18759
+ const store = (0, import_node_path20.join)(this.root, String(account.uid), (0, import_node_path20.basename)(relative4));
18760
+ const current = `${store}.current.gz`;
18761
+ let userParentFd;
18762
+ try {
18763
+ userParentFd = openDirectoryChain((0, import_node_path20.dirname)(path));
18764
+ } catch {
18765
+ this.opts.log(`[command-history] skipped uid=${account.uid} ${(0, import_node_path20.basename)(relative4)} because its parent path is missing or not a real directory`);
18766
+ return;
18767
+ }
18768
+ try {
18769
+ privateDirectory((0, import_node_path20.dirname)(store));
18770
+ const userPath = descriptorPath(userParentFd, (0, import_node_path20.basename)(path));
18771
+ let status;
18772
+ try {
18773
+ status = (0, import_node_fs26.lstatSync)(userPath);
18774
+ } catch (error) {
18775
+ if (error.code !== "ENOENT") throw error;
18776
+ }
18777
+ const backup = readCurrentBackup(current);
18778
+ const suspicious = status && (!status.isFile() || status.isSymbolicLink() || status.nlink !== 1 || status.uid !== account.uid);
18779
+ const missingWithBackup = !status && backup !== null;
18780
+ if (suspicious || missingWithBackup) {
18781
+ const reason = !status ? "deleted" : status.isSymbolicLink() ? "symlinked" : !status.isFile() ? "not a regular file" : status.nlink !== 1 ? "hard-linked" : "owned by another account";
18782
+ const restored = backup ?? Buffer.alloc(0);
18783
+ this.restore(path, restored, account, userParentFd);
18784
+ this.emitTamper(account, relative4, reason, backup !== null);
18785
+ } else if (!status) {
18786
+ this.restore(path, Buffer.alloc(0), account, userParentFd);
18787
+ }
18788
+ const data = safeReadHistory(userParentFd, (0, import_node_path20.basename)(path), account.uid);
18789
+ if (data === null) return;
18790
+ const previous = backup;
18791
+ if (previous?.equals(data)) {
18792
+ this.pruneSnapshots(current);
18793
+ return;
18794
+ }
18795
+ const compressed = (0, import_node_zlib.gzipSync)(data, { level: 6 });
18796
+ const stamp = compactTime(this.now());
18797
+ atomicWrite(`${store}.${stamp}-${(0, import_node_crypto7.randomUUID)().slice(0, 8)}.gz`, compressed);
18798
+ atomicWrite(current, compressed);
18799
+ this.pruneSnapshots(store);
18800
+ } catch (error) {
18801
+ this.opts.log(`[command-history] could not snapshot uid=${account.uid} ${(0, import_node_path20.basename)(relative4)}: ${error.message}`);
18802
+ } finally {
18803
+ (0, import_node_fs26.closeSync)(userParentFd);
18804
+ }
18805
+ }
18806
+ restore(path, content, account, parentFd) {
18807
+ atomicWrite(path, content, 384, account, parentFd);
18808
+ }
18809
+ emitTamper(account, relative4, reason, hadBackup) {
18810
+ const name = /^[A-Za-z0-9_.-]{1,64}$/.test(account.name) ? account.name : `uid ${account.uid}`;
18811
+ const event = {
18812
+ timestamp: this.now(),
18813
+ module: "command-history",
18814
+ category: "system",
18815
+ severity: "medium",
18816
+ message: `Shell history for ${name} (${(0, import_node_path20.basename)(relative4)}) was ${reason}; restored${hadBackup ? " from the latest backup" : " as an empty file"}`,
18817
+ details: { uid: account.uid, account: name, history_file: (0, import_node_path20.basename)(relative4), action: "restored", reason, had_backup: hadBackup }
18818
+ };
18819
+ this.opts.bus.publish(event);
18820
+ this.opts.log(`[command-history] ${event.message}`);
18821
+ }
18822
+ pruneSnapshots(current) {
18823
+ const dir = (0, import_node_path20.dirname)(current);
18824
+ const prefix = `${(0, import_node_path20.basename)(current).replace(/\.current\.gz$/, "")}.`;
18825
+ const snapshots = (0, import_node_fs26.readdirSync)(dir).filter((name) => name !== (0, import_node_path20.basename)(current) && name.startsWith(prefix) && name.endsWith(".gz")).map((name) => ({ path: (0, import_node_path20.join)(dir, name), name, time: (0, import_node_fs26.lstatSync)((0, import_node_path20.join)(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time);
18826
+ const cutoff = this.now().getTime() - SNAPSHOT_RETENTION_MS;
18827
+ const removeCount = Math.max(0, snapshots.length - MAX_SNAPSHOTS);
18828
+ snapshots.forEach((snapshot, index) => {
18829
+ if (snapshot.time < cutoff || index < removeCount) {
18830
+ try {
18831
+ (0, import_node_fs26.unlinkSync)(snapshot.path);
18832
+ } catch {
18833
+ }
18834
+ }
18835
+ });
18836
+ }
18837
+ };
18838
+
18839
+ // src/daemon/workers/ssh-intrusion.ts
18840
+ var import_node_fs27 = require("fs");
18841
+ var import_node_path21 = require("path");
18842
+ var import_node_child_process9 = require("child_process");
18402
18843
 
18403
18844
  // src/core/asn.ts
18404
18845
  var import_node_dns = require("dns");
@@ -18591,35 +19032,35 @@ function parseKeyLoginsByFingerprint(text) {
18591
19032
  }
18592
19033
  function readJson2(path) {
18593
19034
  try {
18594
- return JSON.parse((0, import_node_fs26.readFileSync)(path, "utf-8"));
19035
+ return JSON.parse((0, import_node_fs27.readFileSync)(path, "utf-8"));
18595
19036
  } catch {
18596
19037
  return null;
18597
19038
  }
18598
19039
  }
18599
19040
  function writeJson2(path, value) {
18600
- (0, import_node_fs26.mkdirSync)((0, import_node_path20.dirname)(path), { recursive: true });
18601
- (0, import_node_fs26.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
18602
- (0, import_node_fs26.renameSync)(`${path}.tmp`, path);
19041
+ (0, import_node_fs27.mkdirSync)((0, import_node_path21.dirname)(path), { recursive: true });
19042
+ (0, import_node_fs27.writeFileSync)(`${path}.tmp`, JSON.stringify(value));
19043
+ (0, import_node_fs27.renameSync)(`${path}.tmp`, path);
18603
19044
  }
18604
19045
  var fsIO2 = {
18605
19046
  readFile: (p) => {
18606
19047
  try {
18607
- return (0, import_node_fs26.readFileSync)(p, "utf-8");
19048
+ return (0, import_node_fs27.readFileSync)(p, "utf-8");
18608
19049
  } catch {
18609
19050
  return null;
18610
19051
  }
18611
19052
  },
18612
19053
  readDir: (p) => {
18613
19054
  try {
18614
- return (0, import_node_fs26.readdirSync)(p);
19055
+ return (0, import_node_fs27.readdirSync)(p);
18615
19056
  } catch {
18616
19057
  return null;
18617
19058
  }
18618
19059
  },
18619
- exists: (p) => (0, import_node_fs26.existsSync)(p)
19060
+ exists: (p) => (0, import_node_fs27.existsSync)(p)
18620
19061
  };
18621
19062
  function defaultRun4(cmd, args) {
18622
- const res = (0, import_node_child_process8.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
19063
+ const res = (0, import_node_child_process9.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
18623
19064
  return res.status === 0 ? res.stdout : null;
18624
19065
  }
18625
19066
  var SshIntrusionWatch = class {
@@ -18817,7 +19258,7 @@ var SshIntrusionWatch = class {
18817
19258
  };
18818
19259
 
18819
19260
  // src/daemon/workers/lightning-watch.ts
18820
- var import_node_fs27 = require("fs");
19261
+ var import_node_fs28 = require("fs");
18821
19262
  var DEFAULT_CLN_LOGS = [
18822
19263
  "/home/lightning/.lightning/cln.log",
18823
19264
  "/root/.lightning/cln.log",
@@ -18873,9 +19314,9 @@ var LightningWatch = class {
18873
19314
  if (this.opts.enabled === false) return [];
18874
19315
  const found = [];
18875
19316
  for (const path of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
18876
- if (!(0, import_node_fs27.existsSync)(path)) continue;
19317
+ if (!(0, import_node_fs28.existsSync)(path)) continue;
18877
19318
  try {
18878
- (0, import_node_fs27.accessSync)(path, import_node_fs27.constants.R_OK);
19319
+ (0, import_node_fs28.accessSync)(path, import_node_fs28.constants.R_OK);
18879
19320
  } catch {
18880
19321
  continue;
18881
19322
  }
@@ -18910,8 +19351,8 @@ var LightningWatch = class {
18910
19351
  };
18911
19352
 
18912
19353
  // src/core/tor-exits.ts
18913
- var import_node_fs28 = require("fs");
18914
- var import_node_path21 = require("path");
19354
+ var import_node_fs29 = require("fs");
19355
+ var import_node_path22 = require("path");
18915
19356
  var import_node_net12 = require("net");
18916
19357
  var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
18917
19358
  function parseTorExitList(text) {
@@ -18979,10 +19420,10 @@ var TorExitList = class _TorExitList {
18979
19420
  }
18980
19421
  loadCache() {
18981
19422
  try {
18982
- if (!(0, import_node_fs28.existsSync)(this.opts.cachePath)) return false;
18983
- const parsed = parseTorExitList((0, import_node_fs28.readFileSync)(this.opts.cachePath, "utf-8"));
19423
+ if (!(0, import_node_fs29.existsSync)(this.opts.cachePath)) return false;
19424
+ const parsed = parseTorExitList((0, import_node_fs29.readFileSync)(this.opts.cachePath, "utf-8"));
18984
19425
  if (parsed.size === 0) return false;
18985
- this.load(parsed, (0, import_node_fs28.statSync)(this.opts.cachePath).mtimeMs);
19426
+ this.load(parsed, (0, import_node_fs29.statSync)(this.opts.cachePath).mtimeMs);
18986
19427
  this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
18987
19428
  return true;
18988
19429
  } catch (err) {
@@ -19014,9 +19455,9 @@ var TorExitList = class _TorExitList {
19014
19455
  const before = this.exits.size;
19015
19456
  this.load(parsed);
19016
19457
  try {
19017
- (0, import_node_fs28.mkdirSync)((0, import_node_path21.dirname)(this.opts.cachePath), { recursive: true });
19018
- (0, import_node_fs28.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
19019
- (0, import_node_fs28.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
19458
+ (0, import_node_fs29.mkdirSync)((0, import_node_path22.dirname)(this.opts.cachePath), { recursive: true });
19459
+ (0, import_node_fs29.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
19460
+ (0, import_node_fs29.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
19020
19461
  } catch (err) {
19021
19462
  this.log(`[tor] could not save the exit list cache: ${err.message}`);
19022
19463
  }
@@ -19041,7 +19482,35 @@ function expire(window, now) {
19041
19482
  }
19042
19483
  var EVIDENCE_MESSAGE_CHARS = 500;
19043
19484
  var EVIDENCE_FIELD_CHARS = 200;
19044
- var EVIDENCE_FIELDS = ["unit", "identifier", "process", "comm", "pid", "user", "path", "method", "status", "host", "priority"];
19485
+ var EVIDENCE_FIELDS = [
19486
+ "unit",
19487
+ "identifier",
19488
+ "process",
19489
+ "comm",
19490
+ "pid",
19491
+ "user",
19492
+ "ssh_user",
19493
+ "username",
19494
+ "account",
19495
+ "runas",
19496
+ "command",
19497
+ "system_account",
19498
+ "system_uid",
19499
+ "fingerprint",
19500
+ "key_type",
19501
+ "auth_method",
19502
+ "port",
19503
+ "path",
19504
+ "method",
19505
+ "status",
19506
+ "host",
19507
+ "priority",
19508
+ "boot_id",
19509
+ "journal_cursor",
19510
+ "audit_session",
19511
+ "login_uid",
19512
+ "source_ip_basis"
19513
+ ];
19045
19514
  function evidenceOf(event) {
19046
19515
  const details = event.details ?? {};
19047
19516
  const out = {
@@ -19118,7 +19587,7 @@ var RuleEngine = class {
19118
19587
  title: rule.title,
19119
19588
  description: `${rule.description} (${hitsLabel} events in ${rule.window_seconds}s${spread})`,
19120
19589
  source_ip: aggregate ? void 0 : event.source_ip,
19121
- username: event.details?.user || void 0,
19590
+ username: (event.details?.user ?? event.details?.ssh_user ?? event.details?.username ?? event.details?.account) || void 0,
19122
19591
  raw_metadata: {
19123
19592
  rule_version: rule.version,
19124
19593
  tags: rule.tags,
@@ -19206,8 +19675,8 @@ var RuleEngine = class {
19206
19675
  };
19207
19676
 
19208
19677
  // src/daemon/rules/loader.ts
19209
- var import_node_fs29 = require("fs");
19210
- var import_node_path22 = require("path");
19678
+ var import_node_fs30 = require("fs");
19679
+ var import_node_path23 = require("path");
19211
19680
 
19212
19681
  // src/daemon/rules/default-rules.ts
19213
19682
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -19669,6 +20138,127 @@ var DEFAULT_RULES = [
19669
20138
  description: "Confirm whether a capture tool or new bridge is expected on this host"
19670
20139
  },
19671
20140
  enabled: true
20141
+ },
20142
+ {
20143
+ id: "agentdb-auth-failure-burst",
20144
+ title: "AgentDB Authentication Failure Burst",
20145
+ description: "Repeated rejected credentials against the AgentDB API",
20146
+ version: "1.0.0",
20147
+ category: "auth",
20148
+ severity: "high",
20149
+ source_types: ["log-watcher"],
20150
+ match: {
20151
+ field: "service",
20152
+ operator: "equals",
20153
+ value: "agentdb",
20154
+ and: [{ field: "status", operator: "regex", value: "^(401|403)$" }]
20155
+ },
20156
+ threshold: 5,
20157
+ window_seconds: 60,
20158
+ cooldown_seconds: 300,
20159
+ tags: ["agentdb", "auth", "credential-abuse"],
20160
+ remediation: { action: "alert", description: "Review the source and rotate any credential that may have leaked" },
20161
+ enabled: true
20162
+ },
20163
+ {
20164
+ id: "agentdb-query-burst",
20165
+ title: "AgentDB Query Burst",
20166
+ description: "An unusually large number of database reads reached the service",
20167
+ version: "1.0.0",
20168
+ category: "web",
20169
+ severity: "high",
20170
+ source_types: ["log-watcher"],
20171
+ match: {
20172
+ field: "service",
20173
+ operator: "equals",
20174
+ value: "agentdb",
20175
+ and: [
20176
+ { field: "path", operator: "equals", value: "/v1/query_readonly" },
20177
+ { field: "status", operator: "regex", value: "^2[0-9][0-9]$" }
20178
+ ]
20179
+ },
20180
+ threshold: 60,
20181
+ window_seconds: 60,
20182
+ cooldown_seconds: 300,
20183
+ group_by: "endpoint",
20184
+ tags: ["agentdb", "data-access", "possible-exfiltration"],
20185
+ remediation: { action: "alert", description: "Check the token owner and audit query volume before revoking credentials" },
20186
+ enabled: true
20187
+ },
20188
+ {
20189
+ id: "agentdb-token-creation-burst",
20190
+ title: "AgentDB Credential Creation Burst",
20191
+ description: "An operator credential created several service tokens in a short period",
20192
+ version: "1.0.0",
20193
+ category: "auth",
20194
+ severity: "high",
20195
+ source_types: ["log-watcher"],
20196
+ match: {
20197
+ field: "service",
20198
+ operator: "equals",
20199
+ value: "agentdb",
20200
+ and: [
20201
+ { field: "path", operator: "equals", value: "/v1/tokens" },
20202
+ { field: "status", operator: "regex", value: "^2[0-9][0-9]$" }
20203
+ ]
20204
+ },
20205
+ threshold: 3,
20206
+ window_seconds: 60,
20207
+ cooldown_seconds: 600,
20208
+ group_by: "endpoint",
20209
+ tags: ["agentdb", "credentials", "persistence"],
20210
+ remediation: { action: "alert", description: "Check operator access and identify any newly issued token" },
20211
+ enabled: true
20212
+ },
20213
+ {
20214
+ id: "agentdb-large-query-exports",
20215
+ title: "Repeated Large AgentDB Query Responses",
20216
+ description: "Several large read-only query responses were served in a short period",
20217
+ version: "1.0.0",
20218
+ category: "web",
20219
+ severity: "high",
20220
+ source_types: ["log-watcher"],
20221
+ match: {
20222
+ field: "service",
20223
+ operator: "equals",
20224
+ value: "agentdb",
20225
+ and: [
20226
+ { field: "path", operator: "equals", value: "/v1/query_readonly" },
20227
+ { field: "status", operator: "regex", value: "^2[0-9][0-9]$" },
20228
+ { field: "response_bytes", operator: "regex", value: "^[1-9][0-9]{6,}$" }
20229
+ ]
20230
+ },
20231
+ threshold: 3,
20232
+ window_seconds: 600,
20233
+ cooldown_seconds: 600,
20234
+ group_by: "endpoint",
20235
+ tags: ["agentdb", "data-access", "large-export"],
20236
+ remediation: { action: "alert", description: "Review the source and revoke the token if this export was not expected" },
20237
+ enabled: true
20238
+ },
20239
+ {
20240
+ id: "agentdb-query-throttled",
20241
+ title: "AgentDB Read Limit Triggered",
20242
+ description: "AgentDB rejected a query because the client reached a service limit",
20243
+ version: "1.0.0",
20244
+ category: "web",
20245
+ severity: "medium",
20246
+ source_types: ["log-watcher"],
20247
+ match: {
20248
+ field: "service",
20249
+ operator: "equals",
20250
+ value: "agentdb",
20251
+ and: [
20252
+ { field: "path", operator: "equals", value: "/v1/query_readonly" },
20253
+ { field: "status", operator: "equals", value: "429" }
20254
+ ]
20255
+ },
20256
+ threshold: 1,
20257
+ window_seconds: 60,
20258
+ cooldown_seconds: 300,
20259
+ tags: ["agentdb", "rate-limit", "data-access"],
20260
+ remediation: { action: "alert", description: "Review AgentDB audit metadata for the token and request pattern" },
20261
+ enabled: true
19672
20262
  }
19673
20263
  ];
19674
20264
 
@@ -19677,11 +20267,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
19677
20267
  function loadAllRules(customDir) {
19678
20268
  const rules = [...DEFAULT_RULES];
19679
20269
  const dir = customDir || RULES_DIR;
19680
- if ((0, import_node_fs29.existsSync)(dir)) {
19681
- const files = (0, import_node_fs29.readdirSync)(dir).filter((f) => f.endsWith(".json"));
20270
+ if ((0, import_node_fs30.existsSync)(dir)) {
20271
+ const files = (0, import_node_fs30.readdirSync)(dir).filter((f) => f.endsWith(".json"));
19682
20272
  for (const file of files) {
19683
20273
  try {
19684
- const raw = (0, import_node_fs29.readFileSync)((0, import_node_path22.join)(dir, file), "utf-8");
20274
+ const raw = (0, import_node_fs30.readFileSync)((0, import_node_path23.join)(dir, file), "utf-8");
19685
20275
  const parsed = JSON.parse(raw);
19686
20276
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
19687
20277
  for (const rule of customRules) {
@@ -19712,9 +20302,9 @@ function loadAllRules(customDir) {
19712
20302
  }
19713
20303
 
19714
20304
  // src/daemon/firewall/adapters.ts
19715
- var import_node_child_process9 = require("child_process");
19716
- var import_node_fs30 = require("fs");
19717
- var import_node_path23 = require("path");
20305
+ var import_node_child_process10 = require("child_process");
20306
+ var import_node_fs31 = require("fs");
20307
+ var import_node_path24 = require("path");
19718
20308
  var import_node_net13 = require("net");
19719
20309
  function assertValidFirewallIp(ip) {
19720
20310
  if ((0, import_node_net13.isIP)(ip) !== 4) {
@@ -19727,9 +20317,9 @@ function assertBannableIp(ip) {
19727
20317
  }
19728
20318
  }
19729
20319
  function writeIfAbsent(path, contents) {
19730
- (0, import_node_fs30.mkdirSync)((0, import_node_path23.dirname)(path), { recursive: true });
20320
+ (0, import_node_fs31.mkdirSync)((0, import_node_path24.dirname)(path), { recursive: true });
19731
20321
  try {
19732
- (0, import_node_fs30.writeFileSync)(path, contents, { flag: "wx" });
20322
+ (0, import_node_fs31.writeFileSync)(path, contents, { flag: "wx" });
19733
20323
  } catch (err) {
19734
20324
  if (err.code !== "EEXIST") throw err;
19735
20325
  }
@@ -19748,11 +20338,11 @@ var Fail2banAdapter = class {
19748
20338
  enforces = true;
19749
20339
  jailReady = false;
19750
20340
  isAvailable() {
19751
- const result = (0, import_node_child_process9.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
20341
+ const result = (0, import_node_child_process10.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
19752
20342
  return result.status === 0;
19753
20343
  }
19754
20344
  client(args) {
19755
- return (0, import_node_child_process9.execFileSync)("fail2ban-client", args, {
20345
+ return (0, import_node_child_process10.execFileSync)("fail2ban-client", args, {
19756
20346
  encoding: "utf-8",
19757
20347
  stdio: ["ignore", "pipe", "pipe"]
19758
20348
  });
@@ -19848,35 +20438,35 @@ var NftablesAdapter = class {
19848
20438
  table = "threatcrush";
19849
20439
  set = "blocklist";
19850
20440
  isAvailable() {
19851
- const result = (0, import_node_child_process9.spawnSync)("nft", ["--version"], { stdio: "pipe" });
20441
+ const result = (0, import_node_child_process10.spawnSync)("nft", ["--version"], { stdio: "pipe" });
19852
20442
  return result.status === 0;
19853
20443
  }
19854
20444
  ensureSetup() {
19855
20445
  try {
19856
- (0, import_node_child_process9.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
20446
+ (0, import_node_child_process10.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
19857
20447
  } catch {
19858
- (0, import_node_child_process9.execSync)(`nft add table inet ${this.table}`);
19859
- (0, import_node_child_process9.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
19860
- (0, import_node_child_process9.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
19861
- (0, import_node_child_process9.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
20448
+ (0, import_node_child_process10.execSync)(`nft add table inet ${this.table}`);
20449
+ (0, import_node_child_process10.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
20450
+ (0, import_node_child_process10.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
20451
+ (0, import_node_child_process10.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
19862
20452
  }
19863
20453
  }
19864
20454
  async block(ip) {
19865
20455
  assertValidFirewallIp(ip);
19866
20456
  this.ensureSetup();
19867
- (0, import_node_child_process9.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
20457
+ (0, import_node_child_process10.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
19868
20458
  }
19869
20459
  async unblock(ip) {
19870
20460
  assertValidFirewallIp(ip);
19871
20461
  try {
19872
- (0, import_node_child_process9.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
20462
+ (0, import_node_child_process10.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
19873
20463
  } catch {
19874
20464
  }
19875
20465
  }
19876
20466
  async isBlocked(ip) {
19877
20467
  assertValidFirewallIp(ip);
19878
20468
  try {
19879
- const output = (0, import_node_child_process9.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
20469
+ const output = (0, import_node_child_process10.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19880
20470
  return output.includes(ip);
19881
20471
  } catch {
19882
20472
  return false;
@@ -19884,7 +20474,7 @@ var NftablesAdapter = class {
19884
20474
  }
19885
20475
  async listBlocked() {
19886
20476
  try {
19887
- const output = (0, import_node_child_process9.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
20477
+ const output = (0, import_node_child_process10.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
19888
20478
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
19889
20479
  if (!match) return [];
19890
20480
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -19897,34 +20487,34 @@ var IptablesAdapter = class {
19897
20487
  name = "iptables";
19898
20488
  chain = "THREATCRUSH";
19899
20489
  isAvailable() {
19900
- const result = (0, import_node_child_process9.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
20490
+ const result = (0, import_node_child_process10.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
19901
20491
  return result.status === 0;
19902
20492
  }
19903
20493
  ensureChain() {
19904
20494
  try {
19905
- (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
20495
+ (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
19906
20496
  } catch {
19907
- (0, import_node_child_process9.execSync)(`iptables -N ${this.chain}`);
19908
- (0, import_node_child_process9.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
20497
+ (0, import_node_child_process10.execSync)(`iptables -N ${this.chain}`);
20498
+ (0, import_node_child_process10.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
19909
20499
  }
19910
20500
  }
19911
20501
  async block(ip) {
19912
20502
  assertValidFirewallIp(ip);
19913
20503
  this.ensureChain();
19914
20504
  if (await this.isBlocked(ip)) return;
19915
- (0, import_node_child_process9.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
20505
+ (0, import_node_child_process10.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
19916
20506
  }
19917
20507
  async unblock(ip) {
19918
20508
  assertValidFirewallIp(ip);
19919
20509
  try {
19920
- (0, import_node_child_process9.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
20510
+ (0, import_node_child_process10.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
19921
20511
  } catch {
19922
20512
  }
19923
20513
  }
19924
20514
  async isBlocked(ip) {
19925
20515
  assertValidFirewallIp(ip);
19926
20516
  try {
19927
- const output = (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
20517
+ const output = (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19928
20518
  return output.includes(ip);
19929
20519
  } catch {
19930
20520
  return false;
@@ -19932,7 +20522,7 @@ var IptablesAdapter = class {
19932
20522
  }
19933
20523
  async listBlocked() {
19934
20524
  try {
19935
- const output = (0, import_node_child_process9.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
20525
+ const output = (0, import_node_child_process10.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
19936
20526
  const ips = [];
19937
20527
  for (const line of output.split("\n")) {
19938
20528
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -19988,8 +20578,8 @@ function detectFirewallAdapter(backend = "auto") {
19988
20578
  }
19989
20579
 
19990
20580
  // src/daemon/firewall/remediation.ts
19991
- var import_node_fs31 = require("fs");
19992
- var import_node_child_process10 = require("child_process");
20581
+ var import_node_fs32 = require("fs");
20582
+ var import_node_child_process11 = require("child_process");
19993
20583
  var import_node_net14 = require("net");
19994
20584
 
19995
20585
  // src/daemon/firewall/crawlers.ts
@@ -20058,19 +20648,19 @@ var defaultDiscovery = {
20058
20648
  const snapshot = takeSnapshot({
20059
20649
  readFile: (p) => {
20060
20650
  try {
20061
- return (0, import_node_fs31.readFileSync)(p, "utf-8");
20651
+ return (0, import_node_fs32.readFileSync)(p, "utf-8");
20062
20652
  } catch {
20063
20653
  return null;
20064
20654
  }
20065
20655
  },
20066
20656
  readDir: (p) => {
20067
20657
  try {
20068
- return (0, import_node_fs31.readdirSync)(p);
20658
+ return (0, import_node_fs32.readdirSync)(p);
20069
20659
  } catch {
20070
20660
  return null;
20071
20661
  }
20072
20662
  },
20073
- exists: (p) => (0, import_node_fs31.existsSync)(p)
20663
+ exists: (p) => (0, import_node_fs32.existsSync)(p)
20074
20664
  });
20075
20665
  const out = /* @__PURE__ */ new Set();
20076
20666
  for (const keys of Object.values(snapshot.keys)) {
@@ -20079,7 +20669,7 @@ var defaultDiscovery = {
20079
20669
  return out;
20080
20670
  },
20081
20671
  keyLoginJournal: (sinceSeconds) => new Promise((resolve4) => {
20082
- (0, import_node_child_process10.execFile)(
20672
+ (0, import_node_child_process11.execFile)(
20083
20673
  "journalctl",
20084
20674
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
20085
20675
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -20583,7 +21173,7 @@ var RemediationManager = class {
20583
21173
  }
20584
21174
  logLine(line) {
20585
21175
  try {
20586
- (0, import_node_fs31.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
21176
+ (0, import_node_fs32.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
20587
21177
  `);
20588
21178
  } catch {
20589
21179
  }
@@ -20623,13 +21213,13 @@ function remediationSettings(section) {
20623
21213
  }
20624
21214
 
20625
21215
  // src/daemon/watchdog-service.ts
20626
- var import_node_fs33 = require("fs");
20627
- var import_node_path25 = require("path");
21216
+ var import_node_fs34 = require("fs");
21217
+ var import_node_path26 = require("path");
20628
21218
 
20629
21219
  // src/core/watchdog.ts
20630
- var import_node_fs32 = require("fs");
20631
- var import_node_crypto7 = require("crypto");
20632
- var import_node_path24 = require("path");
21220
+ var import_node_fs33 = require("fs");
21221
+ var import_node_crypto8 = require("crypto");
21222
+ var import_node_path25 = require("path");
20633
21223
  var WATCHDOG_DIRNAME = "watchdog";
20634
21224
  var LOG_FILE2 = "attacks.jsonl";
20635
21225
  var ROTATED_FILE = "attacks.1.jsonl";
@@ -20669,7 +21259,7 @@ function signatureOf(r) {
20669
21259
  return ["msg", r.module, shape].join("|");
20670
21260
  }
20671
21261
  function findingId(signature) {
20672
- return (0, import_node_crypto7.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
21262
+ return (0, import_node_crypto8.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
20673
21263
  }
20674
21264
  function toRecord(event) {
20675
21265
  const d = event.details ?? {};
@@ -20718,12 +21308,12 @@ var WatchdogLog = class {
20718
21308
  stats = { logged: 0, answered: 0, errored: 0 };
20719
21309
  constructor(dir, options = {}) {
20720
21310
  this.dir = dir;
20721
- this.file = (0, import_node_path24.join)(dir, LOG_FILE2);
21311
+ this.file = (0, import_node_path25.join)(dir, LOG_FILE2);
20722
21312
  this.shareGid = options.shareGid;
20723
- (0, import_node_fs32.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
21313
+ (0, import_node_fs33.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
20724
21314
  if (this.shareGid !== void 0) {
20725
- (0, import_node_fs32.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
20726
- (0, import_node_fs32.chmodSync)(dir, 1528);
21315
+ (0, import_node_fs33.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
21316
+ (0, import_node_fs33.chmodSync)(dir, 1528);
20727
21317
  }
20728
21318
  for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
20729
21319
  }
@@ -20752,16 +21342,16 @@ var WatchdogLog = class {
20752
21342
  const chunk = this.buffer.join("\n") + "\n";
20753
21343
  this.buffer = [];
20754
21344
  try {
20755
- if ((0, import_node_fs32.statSync)(this.file).size > ROTATE_BYTES) {
20756
- (0, import_node_fs32.renameSync)(this.file, (0, import_node_path24.join)(this.dir, ROTATED_FILE));
21345
+ if ((0, import_node_fs33.statSync)(this.file).size > ROTATE_BYTES) {
21346
+ (0, import_node_fs33.renameSync)(this.file, (0, import_node_path25.join)(this.dir, ROTATED_FILE));
20757
21347
  }
20758
21348
  } catch {
20759
21349
  }
20760
- (0, import_node_fs32.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
21350
+ (0, import_node_fs33.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
20761
21351
  if (this.shareGid !== void 0) {
20762
21352
  try {
20763
- (0, import_node_fs32.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
20764
- (0, import_node_fs32.chmodSync)(this.file, 432);
21353
+ (0, import_node_fs33.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
21354
+ (0, import_node_fs33.chmodSync)(this.file, 432);
20765
21355
  } catch {
20766
21356
  }
20767
21357
  }
@@ -20782,21 +21372,21 @@ function parseLines(text) {
20782
21372
  function readTail(file, bytes) {
20783
21373
  let fd;
20784
21374
  try {
20785
- fd = (0, import_node_fs32.openSync)(file, "r");
21375
+ fd = (0, import_node_fs33.openSync)(file, "r");
20786
21376
  } catch (err) {
20787
21377
  if (err.code === "ENOENT") return [];
20788
21378
  throw err;
20789
21379
  }
20790
21380
  try {
20791
- const size = (0, import_node_fs32.fstatSync)(fd).size;
21381
+ const size = (0, import_node_fs33.fstatSync)(fd).size;
20792
21382
  const start = Math.max(0, size - bytes);
20793
21383
  const buf = Buffer.alloc(size - start);
20794
- (0, import_node_fs32.readSync)(fd, buf, 0, buf.length, start);
21384
+ (0, import_node_fs33.readSync)(fd, buf, 0, buf.length, start);
20795
21385
  let text = buf.toString("utf8");
20796
21386
  if (start > 0) text = text.slice(text.indexOf("\n") + 1);
20797
21387
  return parseLines(text);
20798
21388
  } finally {
20799
- (0, import_node_fs32.closeSync)(fd);
21389
+ (0, import_node_fs33.closeSync)(fd);
20800
21390
  }
20801
21391
  }
20802
21392
 
@@ -20805,13 +21395,13 @@ function defaultShareGid() {
20805
21395
  const isRoot2 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
20806
21396
  if (!isRoot2) return void 0;
20807
21397
  try {
20808
- return (0, import_node_fs33.statSync)("/var/log/auth.log").gid;
21398
+ return (0, import_node_fs34.statSync)("/var/log/auth.log").gid;
20809
21399
  } catch {
20810
21400
  return void 0;
20811
21401
  }
20812
21402
  }
20813
21403
  function startWatchdog(opts) {
20814
- const dir = opts.config?.dir ?? (0, import_node_path25.join)(opts.stateDir, WATCHDOG_DIRNAME);
21404
+ const dir = opts.config?.dir ?? (0, import_node_path26.join)(opts.stateDir, WATCHDOG_DIRNAME);
20815
21405
  const base = { dir, logged: 0, answered: 0, errored: 0 };
20816
21406
  if (opts.config?.enabled === false) {
20817
21407
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -20902,7 +21492,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
20902
21492
  }
20903
21493
 
20904
21494
  // src/core/node-runtime.ts
20905
- var import_node_child_process11 = require("child_process");
21495
+ var import_node_child_process12 = require("child_process");
20906
21496
  var MIN_DAEMON_NODE_MAJOR = 22;
20907
21497
  function nodeMajor(version) {
20908
21498
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -20918,16 +21508,16 @@ function daemonNodeProblem(version) {
20918
21508
  // src/daemon/index.ts
20919
21509
  function readVersion2() {
20920
21510
  try {
20921
- const pkg = JSON.parse((0, import_node_fs34.readFileSync)((0, import_node_path26.join)(__dirname, "..", "package.json"), "utf-8"));
21511
+ const pkg = JSON.parse((0, import_node_fs35.readFileSync)((0, import_node_path27.join)(__dirname, "..", "package.json"), "utf-8"));
20922
21512
  return pkg.version || "0.0.0";
20923
21513
  } catch {
20924
21514
  return "0.0.0";
20925
21515
  }
20926
21516
  }
20927
21517
  async function runHardeningChecks() {
20928
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
21518
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process13.execFile)(
20929
21519
  process.execPath,
20930
- [(0, import_node_path26.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
21520
+ [(0, import_node_path27.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
20931
21521
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
20932
21522
  );
20933
21523
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -20939,9 +21529,9 @@ async function runHardeningChecks() {
20939
21529
  return patches ? [...findings, patches] : findings;
20940
21530
  }
20941
21531
  async function runPatchCheck() {
20942
- const { stdout } = await (0, import_node_util.promisify)(import_node_child_process12.execFile)(
21532
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process13.execFile)(
20943
21533
  process.execPath,
20944
- [(0, import_node_path26.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
21534
+ [(0, import_node_path27.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
20945
21535
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
20946
21536
  );
20947
21537
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -20949,7 +21539,7 @@ async function runPatchCheck() {
20949
21539
  }
20950
21540
  function logLine(line) {
20951
21541
  try {
20952
- (0, import_node_fs34.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
21542
+ (0, import_node_fs35.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
20953
21543
  `);
20954
21544
  } catch {
20955
21545
  }
@@ -20974,9 +21564,9 @@ async function runDaemon() {
20974
21564
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
20975
21565
  const restartDaemon = () => {
20976
21566
  if (PATHS.mode === "system") {
20977
- (0, import_node_child_process12.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
21567
+ (0, import_node_child_process13.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
20978
21568
  } else {
20979
- (0, import_node_child_process12.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
21569
+ (0, import_node_child_process13.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
20980
21570
  setTimeout(() => process.exit(0), 500).unref();
20981
21571
  }
20982
21572
  };
@@ -20991,7 +21581,7 @@ async function runDaemon() {
20991
21581
  } catch (err) {
20992
21582
  logLine(`[daemon] state db unavailable: ${err.message}`);
20993
21583
  }
20994
- const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path26.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
21584
+ const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path27.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
20995
21585
  const config = loaded.config;
20996
21586
  if (loaded.error) {
20997
21587
  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)"}`);
@@ -21059,7 +21649,7 @@ async function runDaemon() {
21059
21649
  const threatFeeds = new ThreatFeeds({
21060
21650
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
21061
21651
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
21062
- cachePath: (0, import_node_path26.join)(PATHS.stateDir, "threat-feeds.json"),
21652
+ cachePath: (0, import_node_path27.join)(PATHS.stateDir, "threat-feeds.json"),
21063
21653
  bus,
21064
21654
  log: logLine
21065
21655
  });
@@ -21067,14 +21657,21 @@ async function runDaemon() {
21067
21657
  const privilegeWatch = new PrivilegeWatch({
21068
21658
  settings: privilegeSettings(config.privileged),
21069
21659
  bus,
21070
- snapshotPath: (0, import_node_path26.join)(PATHS.stateDir, "privileges.json"),
21071
- loginsPath: (0, import_node_path26.join)(PATHS.stateDir, "login-countries.json"),
21072
- cursorPath: (0, import_node_path26.join)(PATHS.stateDir, "sudo-cursor.json"),
21660
+ snapshotPath: (0, import_node_path27.join)(PATHS.stateDir, "privileges.json"),
21661
+ loginsPath: (0, import_node_path27.join)(PATHS.stateDir, "login-countries.json"),
21662
+ cursorPath: (0, import_node_path27.join)(PATHS.stateDir, "sudo-cursor.json"),
21073
21663
  log: logLine
21074
21664
  });
21075
21665
  privilegeWatch.start();
21666
+ const commandHistory = new CommandHistoryWatcher({
21667
+ settings: commandHistorySettings(config.command_history),
21668
+ bus,
21669
+ stateDir: PATHS.stateDir,
21670
+ log: logLine
21671
+ });
21672
+ commandHistory.start();
21076
21673
  const torExits = new TorExitList({
21077
- cachePath: (0, import_node_path26.join)(PATHS.stateDir, "tor-exits.txt"),
21674
+ cachePath: (0, import_node_path27.join)(PATHS.stateDir, "tor-exits.txt"),
21078
21675
  url: config.remediation?.tor_exit_list_url,
21079
21676
  log: logLine
21080
21677
  });
@@ -21082,7 +21679,7 @@ async function runDaemon() {
21082
21679
  bus,
21083
21680
  manager: remediation,
21084
21681
  tor: torExits,
21085
- historyPath: (0, import_node_path26.join)(PATHS.stateDir, "key-logins.json"),
21682
+ historyPath: (0, import_node_path27.join)(PATHS.stateDir, "key-logins.json"),
21086
21683
  keyLoginWatch: config.privileged?.key_login_watch !== false,
21087
21684
  log: logLine
21088
21685
  });
@@ -21129,7 +21726,7 @@ async function runDaemon() {
21129
21726
  version,
21130
21727
  hostname: (0, import_node_os6.hostname)(),
21131
21728
  minSeverity,
21132
- spoolPath: (0, import_node_path26.join)(PATHS.stateDir, "cloud-spool.jsonl"),
21729
+ spoolPath: (0, import_node_path27.join)(PATHS.stateDir, "cloud-spool.jsonl"),
21133
21730
  log: logLine,
21134
21731
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
21135
21732
  runHardening: runHardeningChecks
@@ -21162,8 +21759,8 @@ async function runDaemon() {
21162
21759
  const autoUpdate = autoUpdateRef = new AutoUpdate({
21163
21760
  version,
21164
21761
  settings: updateSettings(config.update),
21165
- pkgRoot: (0, import_node_path26.join)(__dirname, ".."),
21166
- statePath: (0, import_node_path26.join)(PATHS.stateDir, "auto-update.json"),
21762
+ pkgRoot: (0, import_node_path27.join)(__dirname, ".."),
21763
+ statePath: (0, import_node_path27.join)(PATHS.stateDir, "auto-update.json"),
21167
21764
  bus,
21168
21765
  log: logLine,
21169
21766
  restartDaemon
@@ -21218,6 +21815,10 @@ async function runDaemon() {
21218
21815
  privilegeWatch.stop();
21219
21816
  } catch {
21220
21817
  }
21818
+ try {
21819
+ commandHistory.stop();
21820
+ } catch {
21821
+ }
21221
21822
  try {
21222
21823
  sshIntrusion.stop();
21223
21824
  } catch {