@profullstack/threatcrush 0.13.81 → 0.13.82

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
@@ -5694,7 +5694,7 @@ var init_calendar = __esm({
5694
5694
  function bound2(value) {
5695
5695
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
5696
5696
  }
5697
- function domainOf(series, axis, which) {
5697
+ function domainOf(series, axis, which2) {
5698
5698
  let min = bound2(axis?.min);
5699
5699
  let max = bound2(axis?.max);
5700
5700
  if (min === void 0 || max === void 0) {
@@ -5702,7 +5702,7 @@ function domainOf(series, axis, which) {
5702
5702
  let hi = -Infinity;
5703
5703
  for (const s of series) {
5704
5704
  for (const p of s.points) {
5705
- const v = p?.[which];
5705
+ const v = p?.[which2];
5706
5706
  if (typeof v !== "number" || !Number.isFinite(v))
5707
5707
  continue;
5708
5708
  if (v < lo)
@@ -7972,11 +7972,11 @@ function drawSelect(surface, options) {
7972
7972
  });
7973
7973
  surface.text(width - 2, 0, options.open ? " \u25B4" : " \u25BE", { fg: color, bg: elevate(theme, 0.05) });
7974
7974
  if (options.open && options.options?.length) {
7975
- const list = options.options;
7976
- const height = Math.min(list.length, surface.height - 1);
7975
+ const list2 = options.options;
7976
+ const height = Math.min(list2.length, surface.height - 1);
7977
7977
  for (let i = 0; i < height; i++) {
7978
7978
  const selected = i === (options.selectedIndex ?? 0);
7979
- surface.text(0, i + 1, fit(` ${truncate(list[i], width - 2)}`, width), {
7979
+ surface.text(0, i + 1, fit(` ${truncate(list2[i], width - 2)}`, width), {
7980
7980
  fg: selected ? theme.selectionText : theme.foreground,
7981
7981
  bg: selected ? theme.selection : elevate(theme, 0.08)
7982
7982
  });
@@ -19736,9 +19736,9 @@ async function startActionCenter() {
19736
19736
  row.text(error2 || warning2 || "Fleet detections, server health, and queued actions", { fg: error2 ? severityColors.high : theme.muted, size: "fill" });
19737
19737
  });
19738
19738
  });
19739
- const list = filtered();
19740
- selected = Math.min(selected, Math.max(0, list.length - 1));
19741
- const selectedDetection = list[selected];
19739
+ const list2 = filtered();
19740
+ selected = Math.min(selected, Math.max(0, list2.length - 1));
19741
+ const selectedDetection = list2[selected];
19742
19742
  const serverMap = serverById();
19743
19743
  const online = data.servers.filter((server) => server.connection === "online").length;
19744
19744
  const pending = data.actions.length;
@@ -19746,7 +19746,7 @@ async function startActionCenter() {
19746
19746
  summary(row, theme, "SERVERS ONLINE", `${online}/${data.servers.length}`, theme.success);
19747
19747
  summary(row, theme, "DETECTIONS", String(data.detections.length), severityColors.high);
19748
19748
  summary(row, theme, "QUEUED ACTIONS", String(pending), theme.warning);
19749
- summary(row, theme, "FILTERED EVENTS", String(list.length), theme.accent);
19749
+ summary(row, theme, "FILTERED EVENTS", String(list2.length), theme.accent);
19750
19750
  });
19751
19751
  ui.row({ size: 1 }, (row) => {
19752
19752
  const selectedHost = serverMap.get(serverId);
@@ -19760,12 +19760,12 @@ async function startActionCenter() {
19760
19760
  panel.label("Loading detections\u2026", { fg: theme.muted });
19761
19761
  return;
19762
19762
  }
19763
- if (list.length === 0) {
19763
+ if (list2.length === 0) {
19764
19764
  panel.label(error2 ? "Sign in and refresh to load fleet activity." : "No detections match these filters.", { fg: theme.muted });
19765
19765
  return;
19766
19766
  }
19767
19767
  panel.table({
19768
- rows: list,
19768
+ rows: list2,
19769
19769
  header: true,
19770
19770
  selected,
19771
19771
  followSelection: true,
@@ -23786,10 +23786,10 @@ var source_default = chalk;
23786
23786
 
23787
23787
  // src/index.ts
23788
23788
  var import_readline = __toESM(require("readline"));
23789
- var import_node_child_process30 = require("child_process");
23790
- var import_node_fs76 = require("fs");
23789
+ var import_node_child_process31 = require("child_process");
23790
+ var import_node_fs78 = require("fs");
23791
23791
  var import_node_path58 = require("path");
23792
- var import_node_os24 = require("os");
23792
+ var import_node_os25 = require("os");
23793
23793
 
23794
23794
  // src/commands/monitor.ts
23795
23795
  var import_node_fs11 = require("fs");
@@ -30499,9 +30499,9 @@ var CrsEngine = class {
30499
30499
  continue;
30500
30500
  }
30501
30501
  for (const target of compiled.rule.targets) {
30502
- const list = this.byTarget.get(target) ?? [];
30503
- list.push(compiled);
30504
- this.byTarget.set(target, list);
30502
+ const list2 = this.byTarget.get(target) ?? [];
30503
+ list2.push(compiled);
30504
+ this.byTarget.set(target, list2);
30505
30505
  }
30506
30506
  }
30507
30507
  }
@@ -32424,15 +32424,15 @@ var Emitter = class {
32424
32424
  this.listeners[ev].push(fn);
32425
32425
  }
32426
32426
  removeListener(ev, fn) {
32427
- const list = this.listeners[ev];
32428
- const i = list.indexOf(fn);
32427
+ const list2 = this.listeners[ev];
32428
+ const i = list2.indexOf(fn);
32429
32429
  if (i === -1) {
32430
32430
  return;
32431
32431
  }
32432
- if (i === 0 && list.length === 1) {
32433
- list.length = 0;
32432
+ if (i === 0 && list2.length === 1) {
32433
+ list2.length = 0;
32434
32434
  } else {
32435
- list.splice(i, 1);
32435
+ list2.splice(i, 1);
32436
32436
  }
32437
32437
  }
32438
32438
  emit(ev, code, signal) {
@@ -38424,8 +38424,8 @@ function scanPath(targetPath, options = {}) {
38424
38424
  if ((0, import_node_fs14.fstatSync)(handle).size > maxFileBytes) return;
38425
38425
  if (mayDeclareInterpreter) {
38426
38426
  const prefix = Buffer.alloc(128);
38427
- const read = (0, import_node_fs14.readSync)(handle, prefix, 0, prefix.length, 0);
38428
- declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
38427
+ const read2 = (0, import_node_fs14.readSync)(handle, prefix, 0, prefix.length, 0);
38428
+ declared = languageOfShebang(prefix.subarray(0, read2).toString("utf-8").split("\n", 1)[0] ?? "");
38429
38429
  if (!declared) return;
38430
38430
  }
38431
38431
  text = (0, import_node_fs14.readFileSync)(handle, "utf-8");
@@ -38449,7 +38449,7 @@ function scanPath(targetPath, options = {}) {
38449
38449
  findings2.push(...fileFindings);
38450
38450
  recordSensitiveFile(filename, relativePath, findings2, fileFindings);
38451
38451
  };
38452
- const walk = (currentPath) => {
38452
+ const walk2 = (currentPath) => {
38453
38453
  let entries;
38454
38454
  try {
38455
38455
  entries = (0, import_node_fs14.readdirSync)(currentPath, { withFileTypes: true });
@@ -38466,7 +38466,7 @@ function scanPath(targetPath, options = {}) {
38466
38466
  excluded += 1;
38467
38467
  continue;
38468
38468
  }
38469
- walk(fullPath);
38469
+ walk2(fullPath);
38470
38470
  continue;
38471
38471
  }
38472
38472
  if (!entry.isFile()) continue;
@@ -38478,7 +38478,7 @@ function scanPath(targetPath, options = {}) {
38478
38478
  }
38479
38479
  };
38480
38480
  if (rootIsDirectory) {
38481
- walk(targetPath);
38481
+ walk2(targetPath);
38482
38482
  } else if (isExcluded(toRelative(walkRoot, targetPath))) {
38483
38483
  excluded += 1;
38484
38484
  } else {
@@ -39109,9 +39109,927 @@ function printHuman(outcome) {
39109
39109
  console.log();
39110
39110
  }
39111
39111
 
39112
- // src/commands/init.ts
39113
- var import_node_fs17 = require("fs");
39112
+ // src/commands/host-scan.ts
39113
+ var import_node_fs18 = require("fs");
39114
+
39115
+ // src/core/host-scan/checks.ts
39114
39116
  var import_node_child_process3 = require("child_process");
39117
+ var import_node_fs17 = require("fs");
39118
+ var import_node_os8 = __toESM(require("os"));
39119
+
39120
+ // src/core/host-scan/parsers.ts
39121
+ var import_node_crypto4 = require("crypto");
39122
+ var VERIFY_LINE = /^(missing|[?.A-Za-z0-9]{9})\s+(?:([cdglr])\s+)?(\/.*?)(?:\s+\(([^)]*)\))?\s*$/;
39123
+ function parsePackageVerify(text) {
39124
+ const out = [];
39125
+ for (const raw of text.split("\n")) {
39126
+ const line2 = raw.replace(/\r$/, "");
39127
+ const m = VERIFY_LINE.exec(line2);
39128
+ if (!m) continue;
39129
+ const attrs = m[1];
39130
+ out.push({
39131
+ path: m[3],
39132
+ attrs,
39133
+ fileType: m[2] ?? null,
39134
+ missing: attrs === "missing",
39135
+ digestChanged: attrs !== "missing" && attrs[2] === "5",
39136
+ error: m[4] ?? null
39137
+ });
39138
+ }
39139
+ return out;
39140
+ }
39141
+ var BIN_DIR = /^\/(?:usr\/)?s?bin\//;
39142
+ var PAM_DIR = /^\/(?:usr\/)?lib(?:32|64|x32)?\/(?:[^/]+\/)?security\//;
39143
+ var LIB_DIR = /^\/(?:usr\/)?lib(?:32|64|x32|exec)?\//;
39144
+ function classifyPackagePath(path2) {
39145
+ if (BIN_DIR.test(path2)) return "binary";
39146
+ if (PAM_DIR.test(path2)) return "pam";
39147
+ if (LIB_DIR.test(path2)) return "library";
39148
+ return "other";
39149
+ }
39150
+ function judgePackageVerify(entries) {
39151
+ const verdict = { fail: [], warn: [], ignored: 0, unreadable: 0 };
39152
+ for (const e of entries) {
39153
+ if (e.error) {
39154
+ verdict.unreadable++;
39155
+ continue;
39156
+ }
39157
+ if (e.fileType) {
39158
+ verdict.ignored++;
39159
+ continue;
39160
+ }
39161
+ const cls = classifyPackagePath(e.path);
39162
+ if (cls === "other") {
39163
+ verdict.ignored++;
39164
+ continue;
39165
+ }
39166
+ if (e.digestChanged) {
39167
+ if (cls === "binary" || cls === "pam" || /\.so(?:\.[0-9.]+)?$/.test(e.path)) verdict.fail.push(e);
39168
+ else verdict.warn.push(e);
39169
+ } else if (e.missing) {
39170
+ verdict.warn.push(e);
39171
+ } else {
39172
+ verdict.ignored++;
39173
+ }
39174
+ }
39175
+ return verdict;
39176
+ }
39177
+ var ANSI = /\x1b\[[0-9;]*m/g;
39178
+ var LOG_STAMP = /^\[\d{2}:\d{2}:\d{2}\]\s?/;
39179
+ function parseRkhunter(text) {
39180
+ const warnings = [];
39181
+ let current = null;
39182
+ for (const raw of text.split("\n")) {
39183
+ const line2 = raw.replace(ANSI, "").replace(LOG_STAMP, "").replace(/\r$/, "");
39184
+ const m = /^Warning:\s*(.*)$/.exec(line2);
39185
+ if (m) {
39186
+ if (current !== null) warnings.push(current);
39187
+ current = m[1].trim();
39188
+ continue;
39189
+ }
39190
+ if (current !== null && /^\s+\S/.test(line2)) {
39191
+ current += ` ${line2.trim()}`;
39192
+ continue;
39193
+ }
39194
+ if (current !== null) {
39195
+ warnings.push(current);
39196
+ current = null;
39197
+ }
39198
+ }
39199
+ if (current !== null) warnings.push(current);
39200
+ return warnings;
39201
+ }
39202
+ function isRkhunterRootkitWarning(warning2) {
39203
+ return /rootkit|infected|trojan|backdoor/i.test(warning2);
39204
+ }
39205
+ function parseChkrootkit(text) {
39206
+ const res = { infectedCommands: [], infectedOther: [], warnings: [], other: [] };
39207
+ let group = null;
39208
+ const closeGroup = () => {
39209
+ if (group && group.paths.length) res.warnings.push(group);
39210
+ group = null;
39211
+ };
39212
+ for (const raw of text.split("\n")) {
39213
+ const line2 = raw.replace(ANSI, "").replace(/\r$/, "").trimEnd();
39214
+ if (!line2.trim()) {
39215
+ closeGroup();
39216
+ continue;
39217
+ }
39218
+ const cmd = /^Checking `([^']+)'\.\.\.\s*INFECTED/.exec(line2);
39219
+ if (cmd) {
39220
+ closeGroup();
39221
+ res.infectedCommands.push(cmd[1]);
39222
+ continue;
39223
+ }
39224
+ if (/INFECTED/.test(line2)) {
39225
+ closeGroup();
39226
+ res.infectedOther.push(line2.trim());
39227
+ continue;
39228
+ }
39229
+ const warn = /^WARNING:\s*(.*?):?\s*$/.exec(line2);
39230
+ if (warn) {
39231
+ closeGroup();
39232
+ group = { header: warn[1], paths: [] };
39233
+ continue;
39234
+ }
39235
+ if (group) {
39236
+ if (/\[From (?:Debian|RPM) package:[^\]]*\]\s*$/.test(line2)) continue;
39237
+ group.paths.push(line2.replace(/\s*\[Not from a (?:Debian|RPM) package\]\s*$/, "").trim());
39238
+ continue;
39239
+ }
39240
+ res.other.push(line2.trim());
39241
+ }
39242
+ closeGroup();
39243
+ return res;
39244
+ }
39245
+ function parseUnhide(text) {
39246
+ const out = [];
39247
+ let cur = null;
39248
+ for (const raw of text.split("\n")) {
39249
+ const line2 = raw.trim();
39250
+ const m = /Found HIDDEN PID:\s*(\d+)/i.exec(line2);
39251
+ if (m) {
39252
+ cur = { pid: Number(m[1]), detail: [] };
39253
+ out.push(cur);
39254
+ continue;
39255
+ }
39256
+ if (!line2) {
39257
+ cur = null;
39258
+ continue;
39259
+ }
39260
+ if (cur && /^(Cmdline|Executable|Command|\$?USER|\$?PWD)\b/i.test(line2)) cur.detail.push(line2);
39261
+ }
39262
+ return out;
39263
+ }
39264
+ var KEY_TYPE = /^(?:ssh-(?:rsa|dss|ed25519|xmss)|ecdsa-sha2-nistp(?:256|384|521)|sk-(?:ssh-ed25519|ecdsa-sha2-nistp256)@openssh\.com)(?:-cert-v0[01]@openssh\.com)?$/;
39265
+ function splitOptionsPrefix(line2) {
39266
+ let inQuote = false;
39267
+ for (let i = 0; i < line2.length; i++) {
39268
+ const ch = line2[i];
39269
+ if (ch === "\\" && inQuote) {
39270
+ i++;
39271
+ continue;
39272
+ }
39273
+ if (ch === '"') {
39274
+ inQuote = !inQuote;
39275
+ continue;
39276
+ }
39277
+ if (!inQuote && (ch === " " || ch === " ")) return { options: line2.slice(0, i), rest: line2.slice(i).trimStart() };
39278
+ }
39279
+ return { options: line2, rest: "" };
39280
+ }
39281
+ function parseOptionList(options) {
39282
+ const out = [];
39283
+ let i = 0;
39284
+ while (i < options.length) {
39285
+ let name = "";
39286
+ while (i < options.length && options[i] !== "=" && options[i] !== ",") name += options[i++];
39287
+ let value = null;
39288
+ if (options[i] === "=") {
39289
+ i++;
39290
+ if (options[i] === '"') {
39291
+ i++;
39292
+ value = "";
39293
+ while (i < options.length && options[i] !== '"') {
39294
+ if (options[i] === "\\" && options[i + 1] === '"') {
39295
+ value += '"';
39296
+ i += 2;
39297
+ continue;
39298
+ }
39299
+ value += options[i++];
39300
+ }
39301
+ i++;
39302
+ } else {
39303
+ value = "";
39304
+ while (i < options.length && options[i] !== ",") value += options[i++];
39305
+ }
39306
+ }
39307
+ if (options[i] === ",") i++;
39308
+ if (name.trim()) out.push({ name: name.trim().toLowerCase(), value });
39309
+ }
39310
+ return out;
39311
+ }
39312
+ function keyFingerprint(blob) {
39313
+ try {
39314
+ const buf = Buffer.from(blob, "base64");
39315
+ if (!buf.length) return null;
39316
+ return `SHA256:${(0, import_node_crypto4.createHash)("sha256").update(buf).digest("base64").replace(/=+$/, "")}`;
39317
+ } catch {
39318
+ return null;
39319
+ }
39320
+ }
39321
+ function parseAuthorizedKeys(text, file = "authorized_keys") {
39322
+ const keys = [];
39323
+ text.split("\n").forEach((raw, idx) => {
39324
+ const line2 = raw.replace(/\r$/, "").trim();
39325
+ if (!line2 || line2.startsWith("#")) return;
39326
+ let optionText = "";
39327
+ let rest = line2;
39328
+ const first = line2.split(/\s+/, 1)[0];
39329
+ if (!KEY_TYPE.test(first)) {
39330
+ const split = splitOptionsPrefix(line2);
39331
+ optionText = split.options;
39332
+ rest = split.rest;
39333
+ }
39334
+ const parts = rest.split(/\s+/);
39335
+ const type = parts[0] ?? "";
39336
+ const blob = parts[1] ?? "";
39337
+ if (!KEY_TYPE.test(type) || !blob) return;
39338
+ const options = optionText ? parseOptionList(optionText) : [];
39339
+ const get = (n) => options.find((o) => o.name === n)?.value ?? null;
39340
+ keys.push({
39341
+ file,
39342
+ line: idx + 1,
39343
+ type,
39344
+ blob,
39345
+ comment: parts.slice(2).join(" "),
39346
+ options,
39347
+ command: get("command"),
39348
+ from: get("from"),
39349
+ restrict: options.some((o) => o.name === "restrict"),
39350
+ fingerprint: keyFingerprint(blob)
39351
+ });
39352
+ });
39353
+ return keys;
39354
+ }
39355
+ function isUnrestrictedKey(key) {
39356
+ return key.command === null && key.from === null;
39357
+ }
39358
+ function parseDenyList(text) {
39359
+ const blobs = /* @__PURE__ */ new Set();
39360
+ const fingerprints = /* @__PURE__ */ new Set();
39361
+ for (const raw of text.split("\n")) {
39362
+ const line2 = raw.replace(/#.*$/, "").trim();
39363
+ if (!line2) continue;
39364
+ if (/^SHA256:/.test(line2)) {
39365
+ fingerprints.add(line2.split(/\s+/)[0].replace(/=+$/, ""));
39366
+ continue;
39367
+ }
39368
+ const parsed = parseAuthorizedKeys(line2);
39369
+ if (parsed.length) {
39370
+ blobs.add(parsed[0].blob);
39371
+ continue;
39372
+ }
39373
+ if (/^[A-Za-z0-9+/]+={0,2}$/.test(line2)) blobs.add(line2);
39374
+ }
39375
+ return { blobs, fingerprints };
39376
+ }
39377
+ function keyIsDenied(key, deny) {
39378
+ return deny.blobs.has(key.blob) || key.fingerprint !== null && deny.fingerprints.has(key.fingerprint);
39379
+ }
39380
+ function parseSshdT(text) {
39381
+ const out = /* @__PURE__ */ new Map();
39382
+ for (const raw of text.split("\n")) {
39383
+ const line2 = raw.trim();
39384
+ if (!line2 || line2.startsWith("#")) continue;
39385
+ const m = /^(\S+)\s+(.*)$/.exec(line2);
39386
+ if (!m) continue;
39387
+ const key = m[1].toLowerCase();
39388
+ const list2 = out.get(key) ?? [];
39389
+ list2.push(m[2]);
39390
+ out.set(key, list2);
39391
+ }
39392
+ return out;
39393
+ }
39394
+ function judgeSshdConfig(cfg) {
39395
+ const issues = [];
39396
+ const root = cfg.get("permitrootlogin")?.[0];
39397
+ if (root !== void 0 && root.toLowerCase() !== "no") {
39398
+ issues.push({ setting: "PermitRootLogin", value: root, reason: "root can log in over SSH (set PermitRootLogin no)" });
39399
+ }
39400
+ const pw = cfg.get("passwordauthentication")?.[0];
39401
+ if (pw !== void 0 && pw.toLowerCase() === "yes") {
39402
+ issues.push({ setting: "PasswordAuthentication", value: pw, reason: "password logins are accepted (set PasswordAuthentication no)" });
39403
+ }
39404
+ return issues;
39405
+ }
39406
+ function expandAuthorizedKeysFiles(spec, home, user) {
39407
+ return spec.split(/\s+/).filter((s) => s && s.toLowerCase() !== "none").map((p) => {
39408
+ const expanded = p.replace(/%%|%h|%u|%U/g, (t) => t === "%%" ? "%" : t === "%h" ? home : t === "%u" ? user : "");
39409
+ return expanded.startsWith("/") ? expanded : `${home.replace(/\/$/, "")}/${expanded}`;
39410
+ });
39411
+ }
39412
+ function parsePasswd(text) {
39413
+ const out = [];
39414
+ for (const raw of text.split("\n")) {
39415
+ const f = raw.trim().split(":");
39416
+ if (f.length < 7 || raw.startsWith("#")) continue;
39417
+ out.push({ name: f[0], uid: Number(f[2]), gid: Number(f[3]), home: f[5], shell: f[6] });
39418
+ }
39419
+ return out;
39420
+ }
39421
+ function uidZeroNonRoot(passwd) {
39422
+ return passwd.filter((p) => p.uid === 0 && p.name !== "root").map((p) => p.name);
39423
+ }
39424
+ function groupMembers(groupText, passwd, group) {
39425
+ for (const raw of groupText.split("\n")) {
39426
+ const f = raw.trim().split(":");
39427
+ if (f.length < 4 || f[0] !== group) continue;
39428
+ const gid = Number(f[2]);
39429
+ const listed = f[3].split(",").map((s) => s.trim()).filter(Boolean);
39430
+ const primary = passwd.filter((p) => p.gid === gid).map((p) => p.name);
39431
+ return { gid, members: [.../* @__PURE__ */ new Set([...listed, ...primary])].sort() };
39432
+ }
39433
+ return { gid: null, members: [] };
39434
+ }
39435
+ function parseProcModules(text) {
39436
+ return text.split("\n").map((l) => l.trim().split(/\s+/)[0]).filter(Boolean);
39437
+ }
39438
+ var RISKY_SOURCES = /* @__PURE__ */ new Set(["/", "/var/run/docker.sock", "/run/docker.sock"]);
39439
+ function judgeDockerInspect(json2) {
39440
+ let list2;
39441
+ try {
39442
+ list2 = JSON.parse(json2);
39443
+ } catch {
39444
+ return [];
39445
+ }
39446
+ if (!Array.isArray(list2)) return [];
39447
+ const out = [];
39448
+ for (const c of list2) {
39449
+ const reasons = [];
39450
+ const hc = c.HostConfig ?? {};
39451
+ if (hc.Privileged === true) reasons.push("--privileged");
39452
+ if (hc.PidMode === "host") reasons.push("--pid=host");
39453
+ const sources = /* @__PURE__ */ new Set();
39454
+ for (const m of c.Mounts ?? []) if (m.Type === "bind" && typeof m.Source === "string") sources.add(m.Source);
39455
+ for (const b of hc.Binds ?? []) if (typeof b === "string") sources.add(b.split(":")[0]);
39456
+ for (const s of sources) {
39457
+ const norm = s.length > 1 ? s.replace(/\/+$/, "") : s;
39458
+ if (RISKY_SOURCES.has(norm)) reasons.push(`bind mount of ${norm}`);
39459
+ }
39460
+ if (reasons.length) out.push({ name: String(c.Name ?? "").replace(/^\//, ""), id: String(c.Id ?? "").slice(0, 12), reasons: [...new Set(reasons)] });
39461
+ }
39462
+ return out;
39463
+ }
39464
+ function parseSince(spec) {
39465
+ const m = /^(\d+)\s*([smhdw])$/i.exec(spec.trim());
39466
+ if (!m) throw new Error(`invalid --since "${spec}" (expected e.g. 7d, 12h, 30m)`);
39467
+ const mult = { s: 1e3, m: 6e4, h: 36e5, d: 864e5, w: 7 * 864e5 };
39468
+ return Number(m[1]) * mult[m[2].toLowerCase()];
39469
+ }
39470
+ function parseDpkgSearch(text) {
39471
+ const owned = /* @__PURE__ */ new Set();
39472
+ for (const raw of text.split("\n")) {
39473
+ const m = /^(.+?):\s+(\/.*)$/.exec(raw.trim());
39474
+ if (m && !/^diversion by/.test(raw)) owned.add(m[2]);
39475
+ }
39476
+ return owned;
39477
+ }
39478
+
39479
+ // src/core/host-scan/checks.ts
39480
+ function run(cmd, args, timeoutMs = 12e4, input) {
39481
+ const r = (0, import_node_child_process3.spawnSync)(cmd, args, {
39482
+ encoding: "utf-8",
39483
+ timeout: timeoutMs,
39484
+ maxBuffer: 256 * 1024 * 1024,
39485
+ input,
39486
+ env: { ...process.env, LC_ALL: "C", LANG: "C", PATH: `${process.env.PATH ?? ""}:/usr/local/sbin:/usr/sbin:/sbin` }
39487
+ });
39488
+ const err = r.error;
39489
+ return {
39490
+ code: r.status,
39491
+ stdout: r.stdout ?? "",
39492
+ stderr: r.stderr ?? "",
39493
+ missing: err?.code === "ENOENT",
39494
+ timedOut: err?.code === "ETIMEDOUT" || r.signal === "SIGTERM"
39495
+ };
39496
+ }
39497
+ function which(cmd) {
39498
+ for (const dir of `${process.env.PATH ?? ""}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`.split(":")) {
39499
+ if (!dir) continue;
39500
+ const p = `${dir}/${cmd}`;
39501
+ try {
39502
+ if ((0, import_node_fs17.statSync)(p).isFile()) return p;
39503
+ } catch {
39504
+ }
39505
+ }
39506
+ return null;
39507
+ }
39508
+ function read(path2) {
39509
+ try {
39510
+ return (0, import_node_fs17.readFileSync)(path2, "utf-8");
39511
+ } catch {
39512
+ return null;
39513
+ }
39514
+ }
39515
+ function installHint(tool, pkg) {
39516
+ return pkg === "rpm" ? `sudo dnf install -y ${tool} # EPEL on RHEL` : `sudo apt-get install -y ${tool}`;
39517
+ }
39518
+ function summarizeItems(items, passReason) {
39519
+ const fails = items.filter((i) => i.status === "fail").length;
39520
+ const warns = items.filter((i) => i.status === "warn").length;
39521
+ if (fails) return { status: "fail", reason: `${fails} failing${warns ? `, ${warns} warning` : ""} item(s)` };
39522
+ if (warns) return { status: "warn", reason: `${warns} item(s) to review` };
39523
+ return { status: "pass", reason: passReason };
39524
+ }
39525
+ function checkPackageIntegrity(ctx) {
39526
+ let out;
39527
+ if (ctx.pkg === "dpkg") out = run("dpkg", ["--verify"], 30 * 6e4);
39528
+ else if (ctx.pkg === "rpm") out = run("rpm", ["-Va", "--nomtime"], 30 * 6e4);
39529
+ else return { status: "skip", reason: "no dpkg or rpm package database on this host", items: [] };
39530
+ if (out.timedOut) return { status: "warn", reason: `${ctx.pkg} verify timed out`, items: [] };
39531
+ const verdict = judgePackageVerify(parsePackageVerify(out.stdout));
39532
+ const items = [
39533
+ ...verdict.fail.map((e) => ({ status: "fail", message: `contents differ from the package (${e.attrs})`, path: e.path })),
39534
+ ...verdict.warn.map((e) => ({ status: "warn", message: e.missing ? "packaged file is missing" : `contents differ from the package (${e.attrs})`, path: e.path }))
39535
+ ];
39536
+ const s = summarizeItems(items, `every packaged binary, PAM module and library matches ${ctx.pkg}`);
39537
+ if (verdict.unreadable) s.reason += ` (${verdict.unreadable} path(s) unreadable)`;
39538
+ return { ...s, items, partial: !ctx.root && verdict.unreadable > 0 };
39539
+ }
39540
+ function checkRkhunter(ctx) {
39541
+ if (!which("rkhunter")) return { status: "warn", reason: "rkhunter is not installed", items: [], install: installHint("rkhunter", ctx.pkg) };
39542
+ const out = run("rkhunter", ["--check", "--sk", "--nocolors", "--rwo", "--noappend-log"], 30 * 6e4);
39543
+ if (out.timedOut) return { status: "warn", reason: "rkhunter timed out after 30 minutes", items: [] };
39544
+ const warnings = parseRkhunter(`${out.stdout}
39545
+ ${out.stderr}`);
39546
+ const items = warnings.map((w) => ({ status: isRkhunterRootkitWarning(w) ? "fail" : "warn", message: w }));
39547
+ return { ...summarizeItems(items, "rkhunter reported no warnings"), items };
39548
+ }
39549
+ function commandMatchesPackage(cmd, ctx) {
39550
+ if (ctx.pkg !== "dpkg") return null;
39551
+ const bin = which(cmd);
39552
+ if (!bin) return null;
39553
+ let real = bin;
39554
+ try {
39555
+ real = (0, import_node_fs17.realpathSync)(bin);
39556
+ } catch {
39557
+ }
39558
+ const owner = run("dpkg", ["-S", real]);
39559
+ const pkg = owner.code === 0 ? owner.stdout.split(":")[0].split(",")[0].trim() : "";
39560
+ if (!pkg) return null;
39561
+ const verify = run("dpkg", ["--verify", pkg]);
39562
+ const changed = judgePackageVerify(parsePackageVerify(verify.stdout)).fail;
39563
+ return verify.code === 0 && changed.length === 0 ? pkg : null;
39564
+ }
39565
+ function checkChkrootkit(ctx) {
39566
+ if (!which("chkrootkit")) return { status: "warn", reason: "chkrootkit is not installed", items: [], install: installHint("chkrootkit", ctx.pkg) };
39567
+ const out = run("chkrootkit", ["-q"], 30 * 6e4);
39568
+ if (out.timedOut) return { status: "warn", reason: "chkrootkit timed out after 30 minutes", items: [] };
39569
+ const res = parseChkrootkit(out.stdout);
39570
+ const items = [];
39571
+ for (const cmd of res.infectedCommands) {
39572
+ const pkg = commandMatchesPackage(cmd, ctx);
39573
+ items.push(pkg ? { status: "warn", message: `chkrootkit flags \`${cmd}' INFECTED, but it matches package ${pkg} (known false positive)`, details: { command: cmd, package: pkg } } : { status: "fail", message: `chkrootkit: \`${cmd}' INFECTED`, details: { command: cmd } });
39574
+ }
39575
+ for (const l of res.infectedOther) items.push({ status: "fail", message: l });
39576
+ for (const g of res.warnings) for (const p of g.paths) items.push({ status: "warn", message: g.header, path: p });
39577
+ for (const l of res.other) items.push({ status: "warn", message: l });
39578
+ return { ...summarizeItems(items, "chkrootkit reported nothing"), items };
39579
+ }
39580
+ function procPids() {
39581
+ const s = /* @__PURE__ */ new Set();
39582
+ try {
39583
+ for (const d of (0, import_node_fs17.readdirSync)("/proc")) if (/^\d+$/.test(d)) s.add(Number(d));
39584
+ } catch {
39585
+ }
39586
+ return s;
39587
+ }
39588
+ function tgidOf(pid) {
39589
+ const st = read(`/proc/${pid}/status`);
39590
+ const m = st && /^Tgid:\s*(\d+)/m.exec(st);
39591
+ return m ? Number(m[1]) : null;
39592
+ }
39593
+ var UNHIDE_BUDGET_MS = 5 * 6e4;
39594
+ function checkHiddenProcesses(ctx) {
39595
+ const listed = procPids();
39596
+ const pidMax = Math.min(Number(read("/proc/sys/kernel/pid_max")?.trim()) || 32768, 4194304);
39597
+ const suspects = [];
39598
+ for (let pid = 1; pid <= pidMax; pid++) {
39599
+ if (listed.has(pid)) continue;
39600
+ if (!(0, import_node_fs17.statSync)(`/proc/${pid}`, { throwIfNoEntry: false })) continue;
39601
+ if (tgidOf(pid) === pid) suspects.push(pid);
39602
+ }
39603
+ const relisted = procPids();
39604
+ const items = suspects.filter((pid) => !relisted.has(pid) && (0, import_node_fs17.existsSync)(`/proc/${pid}`)).map((pid) => ({ status: "fail", message: `PID ${pid} exists but is hidden from the /proc listing`, details: { pid, comm: read(`/proc/${pid}/comm`)?.trim() } }));
39605
+ const ps = run("ps", ["-e", "-o", "pid="]);
39606
+ if (ps.code === 0) {
39607
+ const psPids = new Set(ps.stdout.split("\n").map((l) => Number(l.trim())).filter((n) => n > 0));
39608
+ const after = procPids();
39609
+ for (const pid of listed) {
39610
+ if (psPids.has(pid) || !after.has(pid)) continue;
39611
+ const ps2 = run("ps", ["-p", String(pid), "-o", "pid="]);
39612
+ if (ps2.stdout.trim() || !(0, import_node_fs17.existsSync)(`/proc/${pid}`)) continue;
39613
+ items.push({ status: "fail", message: `PID ${pid} is in /proc but not in ps output`, details: { pid, comm: read(`/proc/${pid}/comm`)?.trim() } });
39614
+ }
39615
+ }
39616
+ let unhideNote = "install unhide for deeper checks";
39617
+ const unhide = which("unhide");
39618
+ if (unhide && ctx.root) {
39619
+ const out = run("unhide", ["quick"], UNHIDE_BUDGET_MS);
39620
+ if (out.timedOut) {
39621
+ unhideNote = `unhide quick did not finish in ${UNHIDE_BUDGET_MS / 6e4} min (pid_max ${pidMax}); built-in sweep only`;
39622
+ } else {
39623
+ unhideNote = "unhide quick also run";
39624
+ const now = procPids();
39625
+ for (const f of parseUnhide(out.stdout)) {
39626
+ if (!(0, import_node_fs17.existsSync)(`/proc/${f.pid}`) || now.has(f.pid) || items.some((i) => i.details?.pid === f.pid)) continue;
39627
+ items.push({ status: "fail", message: `unhide: hidden PID ${f.pid}`, details: { pid: f.pid, detail: f.detail } });
39628
+ }
39629
+ }
39630
+ } else if (unhide) {
39631
+ unhideNote = "unhide needs root";
39632
+ }
39633
+ const res = summarizeItems(items, `no hidden processes (sweep of ${pidMax} PIDs)`);
39634
+ res.reason += `; ${unhideNote}`;
39635
+ return { ...res, items, partial: !ctx.root, install: unhide ? void 0 : installHint("unhide", ctx.pkg) };
39636
+ }
39637
+ function checkKernelModules(ctx) {
39638
+ const procModules = read("/proc/modules");
39639
+ if (procModules === null) return { status: "skip", reason: "/proc/modules is not readable", items: [] };
39640
+ const loaded = new Set(parseProcModules(procModules));
39641
+ const items = [];
39642
+ let sysModules = [];
39643
+ try {
39644
+ sysModules = (0, import_node_fs17.readdirSync)("/sys/module");
39645
+ } catch {
39646
+ }
39647
+ const suspects = sysModules.filter((m) => !loaded.has(m) && read(`/sys/module/${m}/initstate`) !== null);
39648
+ const reloaded = suspects.length ? new Set(parseProcModules(read("/proc/modules") ?? "")) : loaded;
39649
+ for (const m of suspects) {
39650
+ const init = read(`/sys/module/${m}/initstate`);
39651
+ if (init === null) continue;
39652
+ if (!reloaded.has(m)) {
39653
+ items.push({ status: "fail", message: `module ${m} is in /sys/module (${init.trim()}) but hidden from /proc/modules`, details: { module: m } });
39654
+ }
39655
+ }
39656
+ const release = import_node_os8.default.release();
39657
+ const trees = [`/lib/modules/${release}/`, `/usr/lib/modules/${release}/`];
39658
+ if (which("modinfo")) {
39659
+ for (const m of loaded) {
39660
+ const r = run("modinfo", ["-n", m], 1e4);
39661
+ const file = r.stdout.trim();
39662
+ if (r.code !== 0 || !file) {
39663
+ items.push({ status: "fail", message: `loaded module ${m} has no file in /lib/modules/${release}`, details: { module: m } });
39664
+ } else if (file !== "(builtin)" && !trees.some((t) => file.startsWith(t))) {
39665
+ items.push({ status: "fail", message: `loaded module ${m} comes from outside the running kernel's tree`, path: file, details: { module: m } });
39666
+ }
39667
+ }
39668
+ }
39669
+ const taint = Number(read("/proc/sys/kernel/tainted")?.trim() ?? "0");
39670
+ const res = summarizeItems(items, `${loaded.size} loaded modules, all listed and from /lib/modules/${release}`);
39671
+ if (taint) res.reason += ` (kernel taint flags ${taint})`;
39672
+ return { ...res, items };
39673
+ }
39674
+ function checkLdPreload(readFile4 = read, exists = import_node_fs17.existsSync) {
39675
+ const path2 = "/etc/ld.so.preload";
39676
+ if (!exists(path2)) return { status: "pass", reason: `${path2} does not exist`, items: [] };
39677
+ const body = readFile4(path2);
39678
+ const libs = (body ?? "").split(/\s+/).filter(Boolean);
39679
+ return {
39680
+ status: "fail",
39681
+ reason: libs.length ? `${path2} preloads ${libs.length} librar${libs.length === 1 ? "y" : "ies"} into every process` : `${path2} exists`,
39682
+ items: [{ status: "fail", message: body === null ? "exists (unreadable)" : libs.length ? `preloads ${libs.join(", ")}` : "exists (empty)", path: path2, details: { libraries: libs } }]
39683
+ };
39684
+ }
39685
+ function checkSuspiciousExe(ctx) {
39686
+ const items = [];
39687
+ let unreadable = 0;
39688
+ for (const pid of procPids()) {
39689
+ let exe;
39690
+ try {
39691
+ exe = (0, import_node_fs17.readlinkSync)(`/proc/${pid}/exe`);
39692
+ } catch {
39693
+ unreadable++;
39694
+ continue;
39695
+ }
39696
+ const deleted = exe.endsWith(" (deleted)");
39697
+ const temp = /^\/(?:tmp|dev\/shm|var\/tmp)\//.test(exe);
39698
+ if (!deleted && !temp) continue;
39699
+ if (tgidOf(pid) !== pid) continue;
39700
+ const cmdline = (read(`/proc/${pid}/cmdline`) ?? "").replace(/\0/g, " ").trim().slice(0, 160);
39701
+ let user = "";
39702
+ try {
39703
+ const uid = (0, import_node_fs17.statSync)(`/proc/${pid}`).uid;
39704
+ user = ctx.passwd.find((p) => p.uid === uid)?.name ?? String(uid);
39705
+ } catch {
39706
+ }
39707
+ items.push({
39708
+ status: "warn",
39709
+ message: `${deleted ? "deleted executable" : "runs from a temp dir"}: pid ${pid}${user ? ` (${user})` : ""} ${cmdline}`,
39710
+ path: exe,
39711
+ details: { pid, user, cmdline }
39712
+ });
39713
+ }
39714
+ const res = summarizeItems(items, "no process runs a deleted or /tmp, /dev/shm, /var/tmp executable");
39715
+ if (!ctx.root && unreadable) res.reason += ` (${unreadable} processes not readable without root)`;
39716
+ return { ...res, items, partial: !ctx.root };
39717
+ }
39718
+ var sshdCache;
39719
+ function sshdConfig() {
39720
+ if (sshdCache !== void 0) return sshdCache;
39721
+ const bin = which("sshd") ?? ((0, import_node_fs17.existsSync)("/usr/sbin/sshd") ? "/usr/sbin/sshd" : null);
39722
+ if (!bin) return sshdCache = null;
39723
+ const out = run(bin, ["-T"]);
39724
+ sshdCache = out.code === 0 && out.stdout.trim() ? parseSshdT(out.stdout) : null;
39725
+ return sshdCache;
39726
+ }
39727
+ function accountHomes(passwd) {
39728
+ const seen = /* @__PURE__ */ new Map();
39729
+ for (const p of passwd) if (p.home && p.home !== "/" && p.home !== "/nonexistent") seen.set(p.home, p.name);
39730
+ seen.set("/root", seen.get("/root") ?? "root");
39731
+ try {
39732
+ for (const d of (0, import_node_fs17.readdirSync)("/home")) if (!seen.has(`/home/${d}`)) seen.set(`/home/${d}`, d);
39733
+ } catch {
39734
+ }
39735
+ return [...seen].map(([home, user]) => ({ home, user }));
39736
+ }
39737
+ function checkSshKeys(ctx) {
39738
+ const cfg = sshdConfig();
39739
+ const spec = cfg?.get("authorizedkeysfile")?.[0] ?? ".ssh/authorized_keys .ssh/authorized_keys2";
39740
+ let deny = { blobs: /* @__PURE__ */ new Set(), fingerprints: /* @__PURE__ */ new Set() };
39741
+ const items = [];
39742
+ if (ctx.opts.denyKeysFile) {
39743
+ const text = read(ctx.opts.denyKeysFile);
39744
+ if (text === null) items.push({ status: "fail", message: `deny list ${ctx.opts.denyKeysFile} is not readable` });
39745
+ else deny = parseDenyList(text);
39746
+ }
39747
+ const keys = [];
39748
+ let unreadable = 0;
39749
+ const files = /* @__PURE__ */ new Set();
39750
+ for (const { home, user } of accountHomes(ctx.passwd)) {
39751
+ for (const file of expandAuthorizedKeysFiles(spec, home, user)) {
39752
+ if (files.has(file)) continue;
39753
+ files.add(file);
39754
+ let text = null;
39755
+ try {
39756
+ if (!(0, import_node_fs17.lstatSync)(file).isFile()) continue;
39757
+ text = (0, import_node_fs17.readFileSync)(file, "utf-8");
39758
+ } catch (e) {
39759
+ if (e.code === "EACCES") unreadable++;
39760
+ continue;
39761
+ }
39762
+ for (const k of parseAuthorizedKeys(text, file)) keys.push({ ...k, user });
39763
+ }
39764
+ }
39765
+ const byBlob = /* @__PURE__ */ new Map();
39766
+ for (const k of keys) byBlob.set(k.blob, [...byBlob.get(k.blob) ?? [], k]);
39767
+ for (const k of keys) {
39768
+ const where2 = `${k.file}:${k.line}`;
39769
+ const label = `${k.fingerprint ?? k.type} ${k.comment || "(no comment)"}`;
39770
+ if (keyIsDenied(k, deny)) items.push({ status: "fail", message: `deny-listed key for ${k.user}: ${label}`, path: where2, details: { fingerprint: k.fingerprint } });
39771
+ if (isUnrestrictedKey(k)) items.push({ status: "warn", message: `unrestricted key (no command= or from=) for ${k.user}: ${label}`, path: where2, details: { fingerprint: k.fingerprint, restrict: k.restrict } });
39772
+ }
39773
+ for (const [, dupes] of byBlob) {
39774
+ if (dupes.length < 2) continue;
39775
+ items.push({ status: "warn", message: `same key appears ${dupes.length} times: ${dupes[0].fingerprint} (${dupes.map((d) => `${d.file}:${d.line}`).join(", ")})`, details: { fingerprint: dupes[0].fingerprint } });
39776
+ }
39777
+ const res = summarizeItems(items, `${keys.length} key(s) in ${files.size} candidate file(s), all restricted`);
39778
+ res.reason = `${keys.length} key(s); ${res.reason}`;
39779
+ if (unreadable) res.reason += ` (${unreadable} file(s) unreadable without root)`;
39780
+ return { ...res, items, partial: !ctx.root };
39781
+ }
39782
+ function checkSshdConfig(ctx) {
39783
+ const cfg = sshdConfig();
39784
+ if (!cfg) {
39785
+ if (!which("sshd") && !(0, import_node_fs17.existsSync)("/usr/sbin/sshd")) return { status: "skip", reason: "sshd is not installed", items: [] };
39786
+ return { status: "skip", reason: ctx.root ? "`sshd -T` failed" : "`sshd -T` needs root", items: [] };
39787
+ }
39788
+ const items = judgeSshdConfig(cfg).map((i) => ({ status: "warn", message: `${i.setting} ${i.value}: ${i.reason}` }));
39789
+ return { ...summarizeItems(items, "PermitRootLogin no and PasswordAuthentication no"), items };
39790
+ }
39791
+ function checkDockerContainers() {
39792
+ if (!which("docker")) return { status: "skip", reason: "docker is not installed", items: [] };
39793
+ const ps = run("docker", ["ps", "-q", "--no-trunc"], 6e4);
39794
+ if (ps.code !== 0) return { status: "skip", reason: `docker ps failed: ${(ps.stderr.trim().split("\n")[0] || "no access").slice(0, 120)}`, items: [] };
39795
+ const ids = ps.stdout.split("\n").map((s) => s.trim()).filter(Boolean);
39796
+ if (!ids.length) return { status: "pass", reason: "no running containers", items: [] };
39797
+ const inspect = run("docker", ["inspect", ...ids], 12e4);
39798
+ const risks = judgeDockerInspect(inspect.stdout);
39799
+ const items = risks.map((r) => ({ status: "warn", message: `${r.name || r.id}: ${r.reasons.join(", ")} (root on the host)`, details: { ...r } }));
39800
+ return { ...summarizeItems(items, `${ids.length} running container(s), none privileged, host-PID or mounting / or the Docker socket`), items };
39801
+ }
39802
+ function checkDockerGroup(ctx) {
39803
+ const group = read("/etc/group") ?? "";
39804
+ const { gid, members } = groupMembers(group, ctx.passwd, "docker");
39805
+ if (gid === null) return { status: "pass", reason: "no docker group", items: [] };
39806
+ const items = members.map((m) => ({ status: "warn", message: `${m} is in the docker group (equivalent to root)` }));
39807
+ return { ...summarizeItems(items, "docker group is empty"), items };
39808
+ }
39809
+ var PERSISTENCE_ROOTS = [
39810
+ "/etc/crontab",
39811
+ "/etc/cron.d",
39812
+ "/etc/cron.hourly",
39813
+ "/etc/cron.daily",
39814
+ "/etc/cron.weekly",
39815
+ "/etc/cron.monthly",
39816
+ "/etc/anacrontab",
39817
+ "/var/spool/cron",
39818
+ "/etc/systemd/system",
39819
+ "/etc/pam.d",
39820
+ "/etc/ssh/sshd_config",
39821
+ "/etc/ssh/sshd_config.d",
39822
+ "/etc/sudoers",
39823
+ "/etc/sudoers.d",
39824
+ "/etc/ld.so.preload",
39825
+ "/etc/rc.local",
39826
+ "/etc/profile.d",
39827
+ "/etc/udev/rules.d",
39828
+ "/etc/init.d",
39829
+ "/etc/update-motd.d"
39830
+ ];
39831
+ function walk(path2, out, depth = 0) {
39832
+ let unreadable = 0;
39833
+ let st;
39834
+ try {
39835
+ st = (0, import_node_fs17.lstatSync)(path2);
39836
+ } catch (e) {
39837
+ return e.code === "EACCES" ? 1 : 0;
39838
+ }
39839
+ if (st.isSymbolicLink() || st.isFile()) {
39840
+ out.push({ path: path2, mtime: Math.max(st.mtimeMs, st.ctimeMs) });
39841
+ return 0;
39842
+ }
39843
+ if (!st.isDirectory() || depth > 8) return 0;
39844
+ let entries;
39845
+ try {
39846
+ entries = (0, import_node_fs17.readdirSync)(path2);
39847
+ } catch {
39848
+ return 1;
39849
+ }
39850
+ for (const e of entries) unreadable += walk(`${path2}/${e}`, out, depth + 1);
39851
+ return unreadable;
39852
+ }
39853
+ function checkPersistence(ctx) {
39854
+ const roots = [...PERSISTENCE_ROOTS];
39855
+ for (const { home } of accountHomes(ctx.passwd)) {
39856
+ roots.push(`${home}/.config/systemd`, `${home}/.ssh/authorized_keys`, `${home}/.ssh/authorized_keys2`);
39857
+ }
39858
+ const files = [];
39859
+ let unreadable = 0;
39860
+ for (const r of new Set(roots)) unreadable += walk(r, files);
39861
+ const cutoff = Date.now() - ctx.opts.sinceMs;
39862
+ const recent = files.filter((f) => f.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
39863
+ const items = recent.map((f) => ({ status: "warn", message: `changed ${new Date(f.mtime).toISOString().slice(0, 16).replace("T", " ")}Z`, path: f.path }));
39864
+ const res = summarizeItems(items, `no cron, systemd, PAM, sshd, sudoers or key file changed in the window (${files.length} files)`);
39865
+ if (unreadable) res.reason += ` (${unreadable} path(s) unreadable)`;
39866
+ return { ...res, items, partial: !ctx.root && unreadable > 0 };
39867
+ }
39868
+ function checkUidZero(passwdText) {
39869
+ if (passwdText === null) return { status: "skip", reason: "/etc/passwd is not readable", items: [] };
39870
+ const extra = uidZeroNonRoot(parsePasswd(passwdText));
39871
+ const items = extra.map((n) => ({ status: "fail", message: `account ${n} has uid 0` }));
39872
+ return { ...summarizeItems(items, "root is the only uid 0 account"), items };
39873
+ }
39874
+ var SUID_PRUNE = ["/proc", "/sys", "/dev", "/run", "/var/lib/docker", "/var/lib/containerd", "/var/lib/containers", "/snap", "/var/snap", "/var/lib/lxd"];
39875
+ function checkSuid(ctx) {
39876
+ if (!ctx.pkg) return { status: "skip", reason: "no package database to compare against", items: [] };
39877
+ const prune = SUID_PRUNE.flatMap((p, i) => [...i ? ["-o"] : [], "-path", p]);
39878
+ const find = run("find", ["/", "-xdev", "(", ...prune, ")", "-prune", "-o", "-type", "f", "(", "-perm", "-4000", "-o", "-perm", "-2000", ")", "-print"], 20 * 6e4);
39879
+ const paths = find.stdout.split("\n").map((s) => s.trim()).filter(Boolean);
39880
+ const owned = /* @__PURE__ */ new Set();
39881
+ if (ctx.pkg === "dpkg") {
39882
+ const alt = (p) => p.startsWith("/usr/") && /^\/usr\/(s?bin|lib)/.test(p) ? p.slice(4) : /^\/(s?bin|lib)\//.test(p) ? `/usr${p}` : null;
39883
+ const queries = [...new Set(paths.flatMap((p) => [p, alt(p)].filter((x) => !!x)))];
39884
+ for (let i = 0; i < queries.length; i += 200) {
39885
+ const r = run("dpkg", ["-S", ...queries.slice(i, i + 200)]);
39886
+ for (const p of parseDpkgSearch(r.stdout)) owned.add(p);
39887
+ }
39888
+ for (const p of paths) {
39889
+ const a = alt(p);
39890
+ if (a && owned.has(a)) owned.add(p);
39891
+ }
39892
+ } else {
39893
+ for (const p of paths) if (run("rpm", ["-qf", p]).code === 0) owned.add(p);
39894
+ }
39895
+ const items = paths.filter((p) => !owned.has(p)).map((p) => {
39896
+ let mode = "";
39897
+ try {
39898
+ mode = ((0, import_node_fs17.statSync)(p).mode & 4095).toString(8);
39899
+ } catch {
39900
+ }
39901
+ return { status: "warn", message: `setuid/setgid binary not owned by any package${mode ? ` (mode ${mode})` : ""}`, path: p };
39902
+ });
39903
+ const res = summarizeItems(items, `${paths.length} setuid/setgid file(s), all from packages`);
39904
+ return { ...res, items, partial: !ctx.root };
39905
+ }
39906
+ var HOST_CHECKS = [
39907
+ { id: "package-integrity", title: "Package file integrity", needsRoot: false, run: checkPackageIntegrity },
39908
+ { id: "rkhunter", title: "rkhunter", needsRoot: true, run: checkRkhunter },
39909
+ { id: "chkrootkit", title: "chkrootkit", needsRoot: true, run: checkChkrootkit },
39910
+ { id: "hidden-processes", title: "Hidden processes", needsRoot: false, run: checkHiddenProcesses },
39911
+ { id: "kernel-modules", title: "Kernel modules", needsRoot: false, run: checkKernelModules },
39912
+ { id: "ld-preload", title: "/etc/ld.so.preload", needsRoot: false, run: () => checkLdPreload() },
39913
+ { id: "suspicious-exe", title: "Deleted / temp-dir executables", needsRoot: false, run: checkSuspiciousExe },
39914
+ { id: "ssh-keys", title: "SSH authorized_keys", needsRoot: false, run: checkSshKeys },
39915
+ { id: "sshd-config", title: "sshd configuration", needsRoot: true, run: checkSshdConfig },
39916
+ { id: "docker-containers", title: "Docker containers", needsRoot: false, run: () => checkDockerContainers() },
39917
+ { id: "docker-group", title: "Docker group members", needsRoot: false, run: checkDockerGroup },
39918
+ { id: "persistence", title: "Persistence changed recently", needsRoot: false, run: checkPersistence },
39919
+ { id: "uid0-accounts", title: "uid 0 accounts", needsRoot: false, run: () => checkUidZero(read("/etc/passwd")) },
39920
+ { id: "suid-sgid", title: "SUID/SGID outside packages", needsRoot: false, run: checkSuid }
39921
+ ];
39922
+ function detectPackageManager() {
39923
+ if (which("dpkg") && (0, import_node_fs17.existsSync)("/var/lib/dpkg/status")) return "dpkg";
39924
+ if (which("rpm") && ((0, import_node_fs17.existsSync)("/var/lib/rpm") || (0, import_node_fs17.existsSync)("/usr/lib/sysimage/rpm"))) return "rpm";
39925
+ return null;
39926
+ }
39927
+ function runHostScan(opts, select) {
39928
+ const started = Date.now();
39929
+ sshdCache = void 0;
39930
+ const root = typeof process.getuid === "function" ? process.getuid() === 0 : false;
39931
+ const ctx = { root, opts, passwd: parsePasswd(read("/etc/passwd") ?? ""), pkg: detectPackageManager() };
39932
+ const checks = [];
39933
+ for (const def of HOST_CHECKS) {
39934
+ if (select?.only?.length && !select.only.includes(def.id)) continue;
39935
+ if (select?.skip?.includes(def.id)) continue;
39936
+ if (def.needsRoot && !root) {
39937
+ checks.push({ id: def.id, title: def.title, status: "skip", reason: "needs root (run with sudo)", items: [] });
39938
+ continue;
39939
+ }
39940
+ opts.log?.(`running ${def.id}...`);
39941
+ const t = Date.now();
39942
+ let res;
39943
+ try {
39944
+ res = def.run(ctx);
39945
+ } catch (e) {
39946
+ res = { status: "warn", reason: `check errored: ${e.message}`, items: [] };
39947
+ }
39948
+ checks.push({ id: def.id, title: def.title, ...res, duration_ms: Date.now() - t });
39949
+ }
39950
+ const summary2 = { pass: 0, warn: 0, fail: 0, skip: 0 };
39951
+ for (const c of checks) summary2[c.status]++;
39952
+ return {
39953
+ host: import_node_os8.default.hostname(),
39954
+ kernel: import_node_os8.default.release(),
39955
+ root,
39956
+ started_at: new Date(started).toISOString(),
39957
+ duration_ms: Date.now() - started,
39958
+ since_ms: opts.sinceMs,
39959
+ summary: summary2,
39960
+ skipped: checks.filter((c) => c.status === "skip").map((c) => ({ id: c.id, reason: c.reason })),
39961
+ checks
39962
+ };
39963
+ }
39964
+
39965
+ // src/commands/host-scan.ts
39966
+ var STATUS_STYLE = {
39967
+ pass: source_default.green,
39968
+ warn: source_default.yellow,
39969
+ fail: source_default.red.bold,
39970
+ skip: source_default.gray
39971
+ };
39972
+ function list(v) {
39973
+ return v ? v.split(",").map((s) => s.trim()).filter(Boolean) : void 0;
39974
+ }
39975
+ function renderHostScan(report, maxItems = 25) {
39976
+ const lines = [];
39977
+ lines.push(` ${source_default.white.bold("Host integrity scan")} ${report.host} (kernel ${report.kernel})${report.root ? "" : source_default.yellow(" not root: partial")}`);
39978
+ lines.push("");
39979
+ for (const c of report.checks) {
39980
+ const tag = STATUS_STYLE[c.status](c.status.toUpperCase().padEnd(4));
39981
+ lines.push(` ${tag} ${source_default.white(c.title)} ${source_default.gray(c.reason)}${c.partial ? source_default.yellow(" [partial]") : ""}`);
39982
+ for (const item of c.items.slice(0, maxItems)) {
39983
+ const mark = item.status === "fail" ? source_default.red("x") : source_default.yellow("!");
39984
+ lines.push(` ${mark} ${item.message}${item.path ? source_default.gray(` ${item.path}`) : ""}`);
39985
+ }
39986
+ if (c.items.length > maxItems) lines.push(source_default.gray(` ... ${c.items.length - maxItems} more (use --json for all)`));
39987
+ if (c.install) lines.push(source_default.gray(` install: ${c.install}`));
39988
+ }
39989
+ const s = report.summary;
39990
+ lines.push("");
39991
+ lines.push(` ${source_default.green(`${s.pass} pass`)}, ${source_default.yellow(`${s.warn} warn`)}, ${source_default.red(`${s.fail} fail`)}, ${source_default.gray(`${s.skip} skipped`)} (${(report.duration_ms / 1e3).toFixed(1)}s)`);
39992
+ if (!report.root && report.skipped.length) {
39993
+ lines.push(source_default.yellow(` Skipped without root: ${report.skipped.map((k) => k.id).join(", ")}. Re-run with sudo for a full scan.`));
39994
+ }
39995
+ return lines.join("\n");
39996
+ }
39997
+ async function hostScanCommand(opts = {}) {
39998
+ let sinceMs;
39999
+ try {
40000
+ sinceMs = parseSince(opts.since ?? "7d");
40001
+ } catch (e) {
40002
+ console.error(source_default.red(e.message));
40003
+ process.exitCode = 2;
40004
+ return null;
40005
+ }
40006
+ const only = list(opts.checks);
40007
+ const skip = list(opts.skipChecks);
40008
+ const known = new Set(HOST_CHECKS.map((c) => c.id));
40009
+ const unknown = [...only ?? [], ...skip ?? []].filter((id) => !known.has(id));
40010
+ if (unknown.length) {
40011
+ console.error(source_default.red(`Unknown check(s): ${unknown.join(", ")}. Known: ${[...known].join(", ")}`));
40012
+ process.exitCode = 2;
40013
+ return null;
40014
+ }
40015
+ const report = runHostScan({
40016
+ sinceMs,
40017
+ denyKeysFile: opts.denyKeys,
40018
+ log: opts.json ? void 0 : (l) => process.stderr.write(source_default.gray(` ${l}
40019
+ `))
40020
+ }, { only, skip });
40021
+ const text = opts.json ? JSON.stringify(report, null, 2) : renderHostScan(report);
40022
+ if (opts.output) (0, import_node_fs18.writeFileSync)(opts.output, opts.json ? `${text}
40023
+ ` : `${renderHostScan(report, Infinity).replace(/\x1b\[[0-9;]*m/g, "")}
40024
+ `);
40025
+ console.log(text);
40026
+ if (report.summary.fail > 0) process.exitCode = 1;
40027
+ return report;
40028
+ }
40029
+
40030
+ // src/commands/init.ts
40031
+ var import_node_fs19 = require("fs");
40032
+ var import_node_child_process4 = require("child_process");
39115
40033
  init_cli_config();
39116
40034
 
39117
40035
  // src/core/prompt.ts
@@ -39189,15 +40107,15 @@ function ask(question, opts = {}) {
39189
40107
  init_cli_config();
39190
40108
 
39191
40109
  // src/core/link-login.ts
39192
- var import_node_crypto4 = require("crypto");
39193
- var import_node_os8 = require("os");
40110
+ var import_node_crypto5 = require("crypto");
40111
+ var import_node_os9 = require("os");
39194
40112
  init_cli_config();
39195
40113
  function createPkce() {
39196
- const verifier = (0, import_node_crypto4.randomBytes)(32).toString("base64url");
39197
- const challenge = (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
40114
+ const verifier = (0, import_node_crypto5.randomBytes)(32).toString("base64url");
40115
+ const challenge = (0, import_node_crypto5.createHash)("sha256").update(verifier).digest("base64url");
39198
40116
  return { verifier, challenge };
39199
40117
  }
39200
- async function startLinkLogin(pkce, deviceName = (0, import_node_os8.hostname)()) {
40118
+ async function startLinkLogin(pkce, deviceName = (0, import_node_os9.hostname)()) {
39201
40119
  const res = await fetch(`${apiUrl()}/api/auth/cli/start`, {
39202
40120
  method: "POST",
39203
40121
  headers: { "Content-Type": "application/json" },
@@ -39483,7 +40401,7 @@ var SERVICES_TO_DETECT = [
39483
40401
  ];
39484
40402
  function isProcessRunning(name) {
39485
40403
  try {
39486
- (0, import_node_child_process3.execSync)(`pgrep -x ${name}`, { stdio: "pipe" });
40404
+ (0, import_node_child_process4.execSync)(`pgrep -x ${name}`, { stdio: "pipe" });
39487
40405
  return true;
39488
40406
  } catch {
39489
40407
  return false;
@@ -39491,14 +40409,14 @@ function isProcessRunning(name) {
39491
40409
  }
39492
40410
  function binaryExists(name) {
39493
40411
  try {
39494
- (0, import_node_child_process3.execSync)(`which ${name}`, { stdio: "pipe" });
40412
+ (0, import_node_child_process4.execSync)(`which ${name}`, { stdio: "pipe" });
39495
40413
  return true;
39496
40414
  } catch {
39497
40415
  return false;
39498
40416
  }
39499
40417
  }
39500
40418
  function findLogPath(paths) {
39501
- return paths.find((p) => (0, import_node_fs17.existsSync)(p));
40419
+ return paths.find((p) => (0, import_node_fs19.existsSync)(p));
39502
40420
  }
39503
40421
  async function promptYesNo(question, fallback) {
39504
40422
  const hint = fallback ? "(Y/n)" : "(y/N)";
@@ -39642,11 +40560,11 @@ async function initCommand(opts = {}) {
39642
40560
  }
39643
40561
  } else {
39644
40562
  const spinner2 = ora({ text: "Writing configuration files...", color: "green" }).start();
39645
- (0, import_node_fs17.mkdirSync)(confDDir, { recursive: true });
39646
- (0, import_node_fs17.mkdirSync)("/var/log/threatcrush", { recursive: true });
39647
- (0, import_node_fs17.mkdirSync)("/var/lib/threatcrush", { recursive: true });
40563
+ (0, import_node_fs19.mkdirSync)(confDDir, { recursive: true });
40564
+ (0, import_node_fs19.mkdirSync)("/var/log/threatcrush", { recursive: true });
40565
+ (0, import_node_fs19.mkdirSync)("/var/lib/threatcrush", { recursive: true });
39648
40566
  const mainConfig = generateDefaultConfig(detected2.map((d) => d.name));
39649
- (0, import_node_fs17.writeFileSync)(`${configDir}/threatcrushd.conf`, mainConfig);
40567
+ (0, import_node_fs19.writeFileSync)(`${configDir}/threatcrushd.conf`, mainConfig);
39650
40568
  for (const svc of detected2) {
39651
40569
  const svcDef = SERVICES_TO_DETECT.find((s) => s.name === svc.name);
39652
40570
  if (!svcDef) continue;
@@ -39655,7 +40573,7 @@ async function initCommand(opts = {}) {
39655
40573
  ...svcDef.moduleConfig,
39656
40574
  log_path: svc.logPath || svcDef.logPaths[0]
39657
40575
  });
39658
- (0, import_node_fs17.writeFileSync)(`${confDDir}/${modName}.conf`, modConfig);
40576
+ (0, import_node_fs19.writeFileSync)(`${confDDir}/${modName}.conf`, modConfig);
39659
40577
  }
39660
40578
  spinner2.succeed("Configuration written successfully");
39661
40579
  console.log();
@@ -39673,8 +40591,8 @@ async function initCommand(opts = {}) {
39673
40591
  }
39674
40592
  function checkWriteAccess(dir) {
39675
40593
  try {
39676
- if (!(0, import_node_fs17.existsSync)(dir)) {
39677
- (0, import_node_fs17.mkdirSync)(dir, { recursive: true });
40594
+ if (!(0, import_node_fs19.existsSync)(dir)) {
40595
+ (0, import_node_fs19.mkdirSync)(dir, { recursive: true });
39678
40596
  }
39679
40597
  return true;
39680
40598
  } catch {
@@ -39692,7 +40610,7 @@ var BUILTIN_MODULES = [
39692
40610
  ];
39693
40611
 
39694
40612
  // src/core/module-loader.ts
39695
- var import_node_fs18 = require("fs");
40613
+ var import_node_fs20 = require("fs");
39696
40614
  var import_node_path16 = require("path");
39697
40615
  var import_toml2 = __toESM(require_toml());
39698
40616
  init_paths();
@@ -39704,19 +40622,19 @@ function discoverModules(moduleDir, confDir) {
39704
40622
  (0, import_node_path16.resolve)(process.cwd(), "modules")
39705
40623
  ];
39706
40624
  const builtinDir = (0, import_node_path16.resolve)(__dirname || ".", "..", "modules");
39707
- if ((0, import_node_fs18.existsSync)(builtinDir)) {
40625
+ if ((0, import_node_fs20.existsSync)(builtinDir)) {
39708
40626
  searchPaths.push(builtinDir);
39709
40627
  }
39710
40628
  for (const basePath of searchPaths) {
39711
- if (!(0, import_node_fs18.existsSync)(basePath)) continue;
39712
- const entries = (0, import_node_fs18.readdirSync)(basePath, { withFileTypes: true });
40629
+ if (!(0, import_node_fs20.existsSync)(basePath)) continue;
40630
+ const entries = (0, import_node_fs20.readdirSync)(basePath, { withFileTypes: true });
39713
40631
  for (const entry of entries) {
39714
40632
  if (!entry.isDirectory()) continue;
39715
40633
  const modPath = (0, import_node_path16.join)(basePath, entry.name);
39716
40634
  const manifestPath = (0, import_node_path16.join)(modPath, "mod.toml");
39717
- if (!(0, import_node_fs18.existsSync)(manifestPath)) continue;
40635
+ if (!(0, import_node_fs20.existsSync)(manifestPath)) continue;
39718
40636
  try {
39719
- const raw = (0, import_node_fs18.readFileSync)(manifestPath, "utf-8");
40637
+ const raw = (0, import_node_fs20.readFileSync)(manifestPath, "utf-8");
39720
40638
  const manifest = import_toml2.default.parse(raw);
39721
40639
  const config = configs.get(manifest.module.name) || { enabled: true };
39722
40640
  modules.push({
@@ -39742,21 +40660,21 @@ function discoverModules(moduleDir, confDir) {
39742
40660
  init_ipc_client();
39743
40661
 
39744
40662
  // src/daemon/pidfile.ts
39745
- var import_node_fs19 = require("fs");
40663
+ var import_node_fs21 = require("fs");
39746
40664
  init_paths();
39747
40665
  function writePidFile() {
39748
40666
  ensureRuntimeDirs();
39749
- (0, import_node_fs19.writeFileSync)(PATHS.pidFile, String(process.pid), "utf-8");
40667
+ (0, import_node_fs21.writeFileSync)(PATHS.pidFile, String(process.pid), "utf-8");
39750
40668
  }
39751
40669
  function readPidFile() {
39752
- if (!(0, import_node_fs19.existsSync)(PATHS.pidFile)) return null;
39753
- const raw = (0, import_node_fs19.readFileSync)(PATHS.pidFile, "utf-8").trim();
40670
+ if (!(0, import_node_fs21.existsSync)(PATHS.pidFile)) return null;
40671
+ const raw = (0, import_node_fs21.readFileSync)(PATHS.pidFile, "utf-8").trim();
39754
40672
  const pid = parseInt(raw, 10);
39755
40673
  return Number.isFinite(pid) ? pid : null;
39756
40674
  }
39757
40675
  function removePidFile() {
39758
40676
  try {
39759
- if ((0, import_node_fs19.existsSync)(PATHS.pidFile)) (0, import_node_fs19.unlinkSync)(PATHS.pidFile);
40677
+ if ((0, import_node_fs21.existsSync)(PATHS.pidFile)) (0, import_node_fs21.unlinkSync)(PATHS.pidFile);
39760
40678
  } catch {
39761
40679
  }
39762
40680
  }
@@ -39768,7 +40686,7 @@ function procStatState(stat) {
39768
40686
  function isZombie(pid) {
39769
40687
  let stat;
39770
40688
  try {
39771
- stat = (0, import_node_fs19.readFileSync)(`/proc/${pid}/stat`, "utf-8");
40689
+ stat = (0, import_node_fs21.readFileSync)(`/proc/${pid}/stat`, "utf-8");
39772
40690
  } catch {
39773
40691
  return false;
39774
40692
  }
@@ -39894,22 +40812,22 @@ function formatUptime2(seconds) {
39894
40812
  }
39895
40813
 
39896
40814
  // src/commands/modules.ts
39897
- var import_node_child_process4 = require("child_process");
39898
- var import_node_fs21 = require("fs");
40815
+ var import_node_child_process5 = require("child_process");
40816
+ var import_node_fs23 = require("fs");
39899
40817
  var import_node_path18 = require("path");
39900
40818
  var import_toml3 = __toESM(require_toml());
39901
40819
  init_paths();
39902
40820
 
39903
40821
  // src/daemon/module-trust.ts
39904
- var import_node_crypto5 = require("crypto");
39905
- var import_node_fs20 = require("fs");
40822
+ var import_node_crypto6 = require("crypto");
40823
+ var import_node_fs22 = require("fs");
39906
40824
  var import_node_path17 = require("path");
39907
40825
  init_paths();
39908
40826
  var TRUST_FILE = (0, import_node_path17.join)(PATHS.configDir, "trusted-modules.json");
39909
40827
  var PUBLISHER_KEYS_FILE = (0, import_node_path17.join)(PATHS.configDir, "publisher-keys.json");
39910
40828
  var DIGEST_EXCLUDED_DIRS = /* @__PURE__ */ new Set([".git"]);
39911
40829
  function collectFiles(root, dir = root, out = []) {
39912
- for (const entry of (0, import_node_fs20.readdirSync)(dir, { withFileTypes: true }).sort(
40830
+ for (const entry of (0, import_node_fs22.readdirSync)(dir, { withFileTypes: true }).sort(
39913
40831
  (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
39914
40832
  )) {
39915
40833
  const full = (0, import_node_path17.join)(dir, entry.name);
@@ -39925,26 +40843,26 @@ function collectFiles(root, dir = root, out = []) {
39925
40843
  return out;
39926
40844
  }
39927
40845
  function computeModuleDigest(modulePath) {
39928
- const hash = (0, import_node_crypto5.createHash)("sha256");
40846
+ const hash = (0, import_node_crypto6.createHash)("sha256");
39929
40847
  for (const entry of collectFiles(modulePath)) {
39930
40848
  const relPath = (0, import_node_path17.relative)(modulePath, entry.path).split(import_node_path17.sep).join("/");
39931
40849
  hash.update(relPath);
39932
40850
  hash.update("\0");
39933
40851
  if (entry.isSymlink) {
39934
40852
  hash.update("symlink:");
39935
- hash.update((0, import_node_fs20.readlinkSync)(entry.path));
40853
+ hash.update((0, import_node_fs22.readlinkSync)(entry.path));
39936
40854
  } else {
39937
40855
  hash.update("file:");
39938
- hash.update((0, import_node_fs20.readFileSync)(entry.path));
40856
+ hash.update((0, import_node_fs22.readFileSync)(entry.path));
39939
40857
  }
39940
40858
  hash.update("\0");
39941
40859
  }
39942
40860
  return hash.digest("hex");
39943
40861
  }
39944
40862
  function readTrustFile() {
39945
- if (!(0, import_node_fs20.existsSync)(TRUST_FILE)) return { version: 1, modules: {} };
40863
+ if (!(0, import_node_fs22.existsSync)(TRUST_FILE)) return { version: 1, modules: {} };
39946
40864
  try {
39947
- const parsed = JSON.parse((0, import_node_fs20.readFileSync)(TRUST_FILE, "utf-8"));
40865
+ const parsed = JSON.parse((0, import_node_fs22.readFileSync)(TRUST_FILE, "utf-8"));
39948
40866
  if (parsed.version !== 1 || typeof parsed.modules !== "object" || !parsed.modules) {
39949
40867
  return { version: 1, modules: {} };
39950
40868
  }
@@ -39954,9 +40872,9 @@ function readTrustFile() {
39954
40872
  }
39955
40873
  }
39956
40874
  function writeTrustFile(file) {
39957
- (0, import_node_fs20.writeFileSync)(TRUST_FILE, JSON.stringify(file, null, 2) + "\n", { mode: 384 });
40875
+ (0, import_node_fs22.writeFileSync)(TRUST_FILE, JSON.stringify(file, null, 2) + "\n", { mode: 384 });
39958
40876
  try {
39959
- (0, import_node_fs20.chmodSync)(TRUST_FILE, 384);
40877
+ (0, import_node_fs22.chmodSync)(TRUST_FILE, 384);
39960
40878
  } catch {
39961
40879
  }
39962
40880
  }
@@ -39982,9 +40900,9 @@ function listTrustedModules() {
39982
40900
  return readTrustFile().modules;
39983
40901
  }
39984
40902
  function readPublisherKeys() {
39985
- if (!(0, import_node_fs20.existsSync)(PUBLISHER_KEYS_FILE)) return {};
40903
+ if (!(0, import_node_fs22.existsSync)(PUBLISHER_KEYS_FILE)) return {};
39986
40904
  try {
39987
- const parsed = JSON.parse((0, import_node_fs20.readFileSync)(PUBLISHER_KEYS_FILE, "utf-8"));
40905
+ const parsed = JSON.parse((0, import_node_fs22.readFileSync)(PUBLISHER_KEYS_FILE, "utf-8"));
39988
40906
  return parsed && typeof parsed === "object" ? parsed : {};
39989
40907
  } catch {
39990
40908
  return {};
@@ -39997,12 +40915,12 @@ function verifyModuleSignature(modulePath, digest) {
39997
40915
  if (pinnedKeyIds.length === 0) {
39998
40916
  return { ok: true };
39999
40917
  }
40000
- if (!(0, import_node_fs20.existsSync)(sigPath)) {
40918
+ if (!(0, import_node_fs22.existsSync)(sigPath)) {
40001
40919
  return { ok: false, reason: "publisher keys are pinned but the module ships no mod.sig" };
40002
40920
  }
40003
40921
  let parsed;
40004
40922
  try {
40005
- parsed = JSON.parse((0, import_node_fs20.readFileSync)(sigPath, "utf-8"));
40923
+ parsed = JSON.parse((0, import_node_fs22.readFileSync)(sigPath, "utf-8"));
40006
40924
  } catch {
40007
40925
  return { ok: false, reason: "mod.sig is not valid JSON" };
40008
40926
  }
@@ -40014,7 +40932,7 @@ function verifyModuleSignature(modulePath, digest) {
40014
40932
  return { ok: false, reason: `mod.sig references unpinned key "${parsed.keyId}"` };
40015
40933
  }
40016
40934
  try {
40017
- const valid = (0, import_node_crypto5.verify)(
40935
+ const valid = (0, import_node_crypto6.verify)(
40018
40936
  null,
40019
40937
  Buffer.from(digest, "hex"),
40020
40938
  publicKey,
@@ -40066,7 +40984,7 @@ function moduleDestination(dir, name, label) {
40066
40984
  return (0, import_node_path18.join)(dir, safeModuleDirName(name, label));
40067
40985
  }
40068
40986
  function assertSafeTarballEntries(tarPath) {
40069
- const listing = (0, import_node_child_process4.execFileSync)("tar", ["-tzf", tarPath], { encoding: "utf-8" });
40987
+ const listing = (0, import_node_child_process5.execFileSync)("tar", ["-tzf", tarPath], { encoding: "utf-8" });
40070
40988
  for (const entry of listing.split("\n").map((line2) => line2.trim()).filter(Boolean)) {
40071
40989
  const normalized = entry.replace(/\\/g, "/");
40072
40990
  const segments = normalized.split("/");
@@ -40077,11 +40995,11 @@ function assertSafeTarballEntries(tarPath) {
40077
40995
  }
40078
40996
  function validateManifest(modPath) {
40079
40997
  const manifestPath = (0, import_node_path18.join)(modPath, "mod.toml");
40080
- if (!(0, import_node_fs21.existsSync)(manifestPath)) {
40998
+ if (!(0, import_node_fs23.existsSync)(manifestPath)) {
40081
40999
  return { ok: false, error: `mod.toml not found at ${manifestPath}` };
40082
41000
  }
40083
41001
  try {
40084
- const raw = (0, import_node_fs21.readFileSync)(manifestPath, "utf-8");
41002
+ const raw = (0, import_node_fs23.readFileSync)(manifestPath, "utf-8");
40085
41003
  const parsed = import_toml3.default.parse(raw);
40086
41004
  const name = parsed.module?.name;
40087
41005
  const version = parsed.module?.version;
@@ -40144,7 +41062,7 @@ async function modulesInstallCommand(source) {
40144
41062
  const dir = modulesDir();
40145
41063
  if (source.startsWith("./") || source.startsWith("/") || source.startsWith("~")) {
40146
41064
  const absPath = (0, import_node_path18.resolve)(source.startsWith("~") ? source.replace("~", process.env.HOME || "") : source);
40147
- if (!(0, import_node_fs21.existsSync)(absPath)) {
41065
+ if (!(0, import_node_fs23.existsSync)(absPath)) {
40148
41066
  console.log(source_default.red(` \u2717 Path not found: ${absPath}
40149
41067
  `));
40150
41068
  return;
@@ -40163,7 +41081,7 @@ async function modulesInstallCommand(source) {
40163
41081
  `));
40164
41082
  return;
40165
41083
  }
40166
- if ((0, import_node_fs21.existsSync)(dest2)) {
41084
+ if ((0, import_node_fs23.existsSync)(dest2)) {
40167
41085
  console.log(source_default.yellow(` ! ${check2.name} is already installed at ${dest2}`));
40168
41086
  console.log(source_default.dim(` Run ${source_default.white(`threatcrush modules remove ${check2.name}`)} first.
40169
41087
  `));
@@ -40171,7 +41089,7 @@ async function modulesInstallCommand(source) {
40171
41089
  }
40172
41090
  const spinner2 = ora({ text: `Copying module files...`, color: "green" }).start();
40173
41091
  try {
40174
- (0, import_node_fs21.cpSync)(absPath, dest2, { recursive: true, dereference: true });
41092
+ (0, import_node_fs23.cpSync)(absPath, dest2, { recursive: true, dereference: true });
40175
41093
  spinner2.succeed(`Installed ${source_default.white(check2.name)} v${check2.version} \u2192 ${dest2}`);
40176
41094
  } catch (err) {
40177
41095
  spinner2.fail(`Copy failed: ${err.message}`);
@@ -40194,7 +41112,7 @@ async function modulesInstallCommand(source) {
40194
41112
  `));
40195
41113
  return;
40196
41114
  }
40197
- if ((0, import_node_fs21.existsSync)(dest2)) {
41115
+ if ((0, import_node_fs23.existsSync)(dest2)) {
40198
41116
  console.log(source_default.yellow(` ! ${name} is already installed at ${dest2}`));
40199
41117
  console.log(source_default.dim(` Run ${source_default.white(`threatcrush modules remove ${name}`)} first.
40200
41118
  `));
@@ -40202,7 +41120,7 @@ async function modulesInstallCommand(source) {
40202
41120
  }
40203
41121
  const spinner2 = ora({ text: `Cloning ${gitUrl}...`, color: "green" }).start();
40204
41122
  try {
40205
- (0, import_node_child_process4.execFileSync)("git", ["clone", "--depth", "1", "--", gitUrl, dest2], { stdio: "pipe" });
41123
+ (0, import_node_child_process5.execFileSync)("git", ["clone", "--depth", "1", "--", gitUrl, dest2], { stdio: "pipe" });
40206
41124
  } catch (err) {
40207
41125
  spinner2.fail(`Clone failed: ${err.message}`);
40208
41126
  return;
@@ -40211,7 +41129,7 @@ async function modulesInstallCommand(source) {
40211
41129
  if (!check2.ok) {
40212
41130
  spinner2.fail(check2.error);
40213
41131
  try {
40214
- (0, import_node_fs21.rmSync)(dest2, { recursive: true, force: true });
41132
+ (0, import_node_fs23.rmSync)(dest2, { recursive: true, force: true });
40215
41133
  } catch {
40216
41134
  }
40217
41135
  return;
@@ -40258,7 +41176,7 @@ async function modulesInstallCommand(source) {
40258
41176
  `));
40259
41177
  return;
40260
41178
  }
40261
- if ((0, import_node_fs21.existsSync)(dest)) {
41179
+ if ((0, import_node_fs23.existsSync)(dest)) {
40262
41180
  console.log(source_default.yellow(` ! ${mod.slug} is already installed at ${dest}
40263
41181
  `));
40264
41182
  return;
@@ -40266,7 +41184,7 @@ async function modulesInstallCommand(source) {
40266
41184
  if (install.npm_package) {
40267
41185
  const npmSpinner = ora({ text: `Installing ${install.npm_package}...`, color: "green" }).start();
40268
41186
  try {
40269
- (0, import_node_child_process4.execFileSync)("npm", ["install", "-g", "--", install.npm_package], { stdio: "pipe" });
41187
+ (0, import_node_child_process5.execFileSync)("npm", ["install", "-g", "--", install.npm_package], { stdio: "pipe" });
40270
41188
  npmSpinner.succeed(`Package ${install.npm_package} installed globally`);
40271
41189
  } catch (err) {
40272
41190
  npmSpinner.fail(`npm install failed: ${err.message}`);
@@ -40275,7 +41193,7 @@ async function modulesInstallCommand(source) {
40275
41193
  } else if (install.git_url) {
40276
41194
  const cloneSpinner = ora({ text: "Cloning module repository...", color: "green" }).start();
40277
41195
  try {
40278
- (0, import_node_child_process4.execFileSync)("git", ["clone", "--depth", "1", "--", install.git_url, dest], { stdio: "pipe" });
41196
+ (0, import_node_child_process5.execFileSync)("git", ["clone", "--depth", "1", "--", install.git_url, dest], { stdio: "pipe" });
40279
41197
  } catch (err) {
40280
41198
  cloneSpinner.fail(`Clone failed: ${err.message}`);
40281
41199
  return;
@@ -40284,7 +41202,7 @@ async function modulesInstallCommand(source) {
40284
41202
  if (!check2.ok) {
40285
41203
  cloneSpinner.fail(check2.error);
40286
41204
  try {
40287
- (0, import_node_fs21.rmSync)(dest, { recursive: true, force: true });
41205
+ (0, import_node_fs23.rmSync)(dest, { recursive: true, force: true });
40288
41206
  } catch {
40289
41207
  }
40290
41208
  return;
@@ -40299,10 +41217,10 @@ async function modulesInstallCommand(source) {
40299
41217
  return;
40300
41218
  }
40301
41219
  const tar = (0, import_node_path18.join)(dir, `${mod.slug}.tar.gz`);
40302
- (0, import_node_fs21.writeFileSync)(tar, Buffer.from(await res.arrayBuffer()));
41220
+ (0, import_node_fs23.writeFileSync)(tar, Buffer.from(await res.arrayBuffer()));
40303
41221
  assertSafeTarballEntries(tar);
40304
- (0, import_node_child_process4.execFileSync)("tar", ["-xzf", tar, "-C", dir], { stdio: "pipe" });
40305
- (0, import_node_fs21.rmSync)(tar, { force: true });
41222
+ (0, import_node_child_process5.execFileSync)("tar", ["-xzf", tar, "-C", dir], { stdio: "pipe" });
41223
+ (0, import_node_fs23.rmSync)(tar, { force: true });
40306
41224
  const check2 = validateManifest(dest);
40307
41225
  if (!check2.ok) {
40308
41226
  dlSpinner.fail(check2.error);
@@ -40334,7 +41252,7 @@ async function modulesRemoveCommand(name) {
40334
41252
  `));
40335
41253
  return;
40336
41254
  }
40337
- if (!(0, import_node_fs21.existsSync)(target)) {
41255
+ if (!(0, import_node_fs23.existsSync)(target)) {
40338
41256
  console.log(source_default.yellow(` ! No module named "${name}" in ${dir}
40339
41257
  `));
40340
41258
  return;
@@ -40344,7 +41262,7 @@ async function modulesRemoveCommand(name) {
40344
41262
  console.log(source_default.yellow(` ! Directory name "${name}" does not match manifest name "${check2.name}"`));
40345
41263
  }
40346
41264
  try {
40347
- (0, import_node_fs21.rmSync)(target, { recursive: true, force: true });
41265
+ (0, import_node_fs23.rmSync)(target, { recursive: true, force: true });
40348
41266
  untrustModule(name);
40349
41267
  console.log(source_default.green(` \u2713 Removed ${name} from ${dir}
40350
41268
  `));
@@ -40369,7 +41287,7 @@ async function modulesTrustCommand(name) {
40369
41287
  `));
40370
41288
  return;
40371
41289
  }
40372
- if (!(0, import_node_fs21.existsSync)(target)) {
41290
+ if (!(0, import_node_fs23.existsSync)(target)) {
40373
41291
  console.log(source_default.yellow(` ! No module named "${name}" in ${dir}
40374
41292
  `));
40375
41293
  return;
@@ -40804,8 +41722,8 @@ async function pentestCommand(targetUrl) {
40804
41722
  }
40805
41723
 
40806
41724
  // src/commands/av.ts
40807
- var import_node_fs28 = require("fs");
40808
- var import_node_os13 = require("os");
41725
+ var import_node_fs30 = require("fs");
41726
+ var import_node_os14 = require("os");
40809
41727
  var import_node_path24 = require("path");
40810
41728
 
40811
41729
  // ../../packages/av/src/sha256.ts
@@ -41328,16 +42246,16 @@ function buildContext(name, bytes, kind, size) {
41328
42246
  let wide = "";
41329
42247
  if (kind === "pe" || kind === "lnk" || kind === "ole") {
41330
42248
  const parts = [];
41331
- let run2 = "";
42249
+ let run3 = "";
41332
42250
  for (let i = 0; i + 1 < bytes.length; i += 2) {
41333
42251
  const lo = bytes[i];
41334
- if (bytes[i + 1] === 0 && lo >= 32 && lo < 127) run2 += String.fromCharCode(lo);
42252
+ if (bytes[i + 1] === 0 && lo >= 32 && lo < 127) run3 += String.fromCharCode(lo);
41335
42253
  else {
41336
- if (run2.length >= 4) parts.push(run2);
41337
- run2 = "";
42254
+ if (run3.length >= 4) parts.push(run3);
42255
+ run3 = "";
41338
42256
  }
41339
42257
  }
41340
- if (run2.length >= 4) parts.push(run2);
42258
+ if (run3.length >= 4) parts.push(run3);
41341
42259
  wide = parts.join("\n");
41342
42260
  }
41343
42261
  return { name, ext: extOf(name), kind, size, bytes, text, wide };
@@ -41512,10 +42430,10 @@ function summarize2(results, engines, startedAt, skipped = 0) {
41512
42430
  }
41513
42431
 
41514
42432
  // ../../packages/av/src/node/locations.ts
41515
- var import_node_fs22 = require("fs");
41516
- var import_node_os9 = require("os");
42433
+ var import_node_fs24 = require("fs");
42434
+ var import_node_os10 = require("os");
41517
42435
  var import_node_path19 = require("path");
41518
- function quickScanTargets(platform = process.platform, env3 = process.env, home = (0, import_node_os9.homedir)()) {
42436
+ function quickScanTargets(platform = process.platform, env3 = process.env, home = (0, import_node_os10.homedir)()) {
41519
42437
  const t = [
41520
42438
  { path: (0, import_node_path19.join)(home, "Downloads"), depth: 3 },
41521
42439
  { path: (0, import_node_path19.join)(home, "Desktop"), depth: 2 }
@@ -41540,7 +42458,7 @@ function quickScanTargets(platform = process.platform, env3 = process.env, home
41540
42458
  { path: "/Library/LaunchDaemons", depth: 1 },
41541
42459
  { path: "/Users/Shared", depth: 2 },
41542
42460
  { path: "/tmp", depth: 2 },
41543
- { path: (0, import_node_os9.tmpdir)(), depth: 2 }
42461
+ { path: (0, import_node_os10.tmpdir)(), depth: 2 }
41544
42462
  );
41545
42463
  } else {
41546
42464
  t.push(
@@ -41555,12 +42473,12 @@ function quickScanTargets(platform = process.platform, env3 = process.env, home
41555
42473
  );
41556
42474
  }
41557
42475
  const seen = /* @__PURE__ */ new Set();
41558
- return t.filter((x) => !seen.has(x.path) && (seen.add(x.path), (0, import_node_fs22.existsSync)(x.path)));
42476
+ return t.filter((x) => !seen.has(x.path) && (seen.add(x.path), (0, import_node_fs24.existsSync)(x.path)));
41559
42477
  }
41560
- function fullScanTargets(platform = process.platform, env3 = process.env, home = (0, import_node_os9.homedir)()) {
42478
+ function fullScanTargets(platform = process.platform, env3 = process.env, home = (0, import_node_os10.homedir)()) {
41561
42479
  const quick = quickScanTargets(platform, env3, home).filter((x) => !x.path.startsWith(home));
41562
42480
  const extra = platform === "linux" ? [{ path: "/opt", depth: Infinity }, { path: "/usr/local/bin", depth: 1 }] : [];
41563
- return [{ path: home, depth: Infinity }, ...quick, ...extra.filter((x) => (0, import_node_fs22.existsSync)(x.path))];
42481
+ return [{ path: home, depth: Infinity }, ...quick, ...extra.filter((x) => (0, import_node_fs24.existsSync)(x.path))];
41564
42482
  }
41565
42483
 
41566
42484
  // ../../packages/av/src/node/walk.ts
@@ -41665,20 +42583,20 @@ async function* walkFiles(targets, opts = {}) {
41665
42583
  }
41666
42584
 
41667
42585
  // ../../packages/av/src/node/scan-file.ts
41668
- var import_node_crypto6 = require("crypto");
41669
- var import_node_fs23 = require("fs");
42586
+ var import_node_crypto7 = require("crypto");
42587
+ var import_node_fs25 = require("fs");
41670
42588
  var CHUNK = 1 << 20;
41671
- var OPEN_FLAGS = import_node_fs23.constants.O_RDONLY | (import_node_fs23.constants.O_NOFOLLOW ?? 0) | (import_node_fs23.constants.O_NONBLOCK ?? 0);
42589
+ var OPEN_FLAGS = import_node_fs25.constants.O_RDONLY | (import_node_fs25.constants.O_NOFOLLOW ?? 0) | (import_node_fs25.constants.O_NONBLOCK ?? 0);
41672
42590
  var head = Buffer.allocUnsafe(64 * 1024);
41673
42591
 
41674
42592
  // ../../packages/av/src/node/scan-worker.ts
41675
42593
  var import_node_worker_threads = require("worker_threads");
41676
42594
 
41677
42595
  // ../../packages/av/src/node/clamav.ts
41678
- var import_node_child_process5 = require("child_process");
41679
- var import_node_fs24 = require("fs");
42596
+ var import_node_child_process6 = require("child_process");
42597
+ var import_node_fs26 = require("fs");
41680
42598
  var import_promises2 = require("fs/promises");
41681
- var import_node_os10 = require("os");
42599
+ var import_node_os11 = require("os");
41682
42600
  var import_node_path21 = require("path");
41683
42601
  var WINDOWS_DIRS = ["C:\\Program Files\\ClamAV", "C:\\Program Files (x86)\\ClamAV", "C:\\ProgramData\\chocolatey\\bin"];
41684
42602
  function findBinary(name, env3 = process.env, platform = process.platform) {
@@ -41688,13 +42606,13 @@ function findBinary(name, env3 = process.env, platform = process.platform) {
41688
42606
  if (platform === "darwin") dirs.push("/opt/homebrew/bin", "/usr/local/bin");
41689
42607
  for (const d of dirs) {
41690
42608
  const p = (0, import_node_path21.join)(d, exe);
41691
- if ((0, import_node_fs24.existsSync)(p)) return p;
42609
+ if ((0, import_node_fs26.existsSync)(p)) return p;
41692
42610
  }
41693
42611
  return null;
41694
42612
  }
41695
- function run(bin, args, timeoutMs, signal) {
42613
+ function run2(bin, args, timeoutMs, signal) {
41696
42614
  return new Promise((resolve9) => {
41697
- const child = (0, import_node_child_process5.spawn)(bin, args, { windowsHide: true, signal });
42615
+ const child = (0, import_node_child_process6.spawn)(bin, args, { windowsHide: true, signal });
41698
42616
  let stdout = "";
41699
42617
  let stderr = "";
41700
42618
  child.stdout.on("data", (d) => stdout += d);
@@ -41717,7 +42635,7 @@ async function detectClamAV() {
41717
42635
  let mode = null;
41718
42636
  let binary = null;
41719
42637
  if (clamdscan) {
41720
- const ping = await run(clamdscan, ["--ping", "1"], 5e3);
42638
+ const ping = await run2(clamdscan, ["--ping", "1"], 5e3);
41721
42639
  if (ping.code === 0) {
41722
42640
  mode = "clamdscan";
41723
42641
  binary = clamdscan;
@@ -41728,7 +42646,7 @@ async function detectClamAV() {
41728
42646
  binary = clamscan;
41729
42647
  }
41730
42648
  if (!binary) return none;
41731
- const v = await run(binary, ["--version"], 15e3);
42649
+ const v = await run2(binary, ["--version"], 15e3);
41732
42650
  const version = v.stdout.trim().split("\n")[0] || null;
41733
42651
  const parts = version?.split("/") ?? [];
41734
42652
  return { available: v.code === 0, binary, mode, version, signaturesDate: parts.length >= 3 ? parts.slice(2).join("/").trim() : null };
@@ -41738,9 +42656,9 @@ function parseClamOutput(stdout) {
41738
42656
  for (const line2 of stdout.split(/\r?\n/)) {
41739
42657
  const m = /^(.*): (\S+) FOUND$/.exec(line2.trim());
41740
42658
  if (!m) continue;
41741
- const list = out.get(m[1]) ?? [];
41742
- list.push(m[2]);
41743
- out.set(m[1], list);
42659
+ const list2 = out.get(m[1]) ?? [];
42660
+ list2.push(m[2]);
42661
+ out.set(m[1], list2);
41744
42662
  }
41745
42663
  return out;
41746
42664
  }
@@ -41759,14 +42677,14 @@ function clamDetection(sig) {
41759
42677
  async function clamScanFiles(info2, files, opts = {}) {
41760
42678
  const detections = /* @__PURE__ */ new Map();
41761
42679
  if (!info2.available || !info2.binary || files.length === 0) return { detections, error: null };
41762
- const dir = await (0, import_promises2.mkdtemp)((0, import_node_path21.join)((0, import_node_os10.tmpdir)(), "crushav-"));
41763
- const list = (0, import_node_path21.join)(dir, "files.txt");
42680
+ const dir = await (0, import_promises2.mkdtemp)((0, import_node_path21.join)((0, import_node_os11.tmpdir)(), "crushav-"));
42681
+ const list2 = (0, import_node_path21.join)(dir, "files.txt");
41764
42682
  try {
41765
- await (0, import_promises2.writeFile)(list, `${files.join("\n")}
42683
+ await (0, import_promises2.writeFile)(list2, `${files.join("\n")}
41766
42684
  `);
41767
- const args = ["--no-summary", "--infected", "--stdout", `--file-list=${list}`];
42685
+ const args = ["--no-summary", "--infected", "--stdout", `--file-list=${list2}`];
41768
42686
  if (info2.mode === "clamdscan") args.push("--fdpass", "--multiscan");
41769
- const r = await run(info2.binary, args, opts.timeoutMs ?? 60 * 60 * 1e3, opts.signal);
42687
+ const r = await run2(info2.binary, args, opts.timeoutMs ?? 60 * 60 * 1e3, opts.signal);
41770
42688
  for (const [path2, sigs] of parseClamOutput(r.stdout)) detections.set(path2, sigs.map(clamDetection));
41771
42689
  const error2 = r.code === null || r.code === 2 && detections.size === 0 && !r.stdout.trim() ? r.stderr.trim().split("\n").pop() ?? "clamav failed" : null;
41772
42690
  return { detections, error: error2 };
@@ -41786,13 +42704,13 @@ function clamInstallHint(platform = process.platform) {
41786
42704
  }
41787
42705
 
41788
42706
  // ../../packages/av/src/node/quarantine.ts
41789
- var import_node_crypto7 = require("crypto");
41790
- var import_node_fs25 = require("fs");
42707
+ var import_node_crypto8 = require("crypto");
42708
+ var import_node_fs27 = require("fs");
41791
42709
  var import_promises3 = require("fs/promises");
41792
- var import_node_os11 = require("os");
42710
+ var import_node_os12 = require("os");
41793
42711
  var import_node_path22 = require("path");
41794
42712
  var KEY = 165;
41795
- function quarantineDir(home = (0, import_node_os11.homedir)()) {
42713
+ function quarantineDir(home = (0, import_node_os12.homedir)()) {
41796
42714
  return process.env.CRUSHAV_QUARANTINE_DIR ?? (0, import_node_path22.join)(home, ".threatcrush", "quarantine");
41797
42715
  }
41798
42716
  function xor(buf) {
@@ -41802,8 +42720,8 @@ function xor(buf) {
41802
42720
  }
41803
42721
  async function quarantineFile(path2, detections = [], dir = quarantineDir()) {
41804
42722
  const data = await (0, import_promises3.readFile)(path2);
41805
- const sha256 = (0, import_node_crypto7.createHash)("sha256").update(data).digest("hex");
41806
- const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g, "").slice(0, 14)}-${(0, import_node_crypto7.randomBytes)(4).toString("hex")}`;
42723
+ const sha256 = (0, import_node_crypto8.createHash)("sha256").update(data).digest("hex");
42724
+ const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g, "").slice(0, 14)}-${(0, import_node_crypto8.randomBytes)(4).toString("hex")}`;
41807
42725
  await (0, import_promises3.mkdir)(dir, { recursive: true, mode: 448 });
41808
42726
  const entry = {
41809
42727
  id,
@@ -41816,7 +42734,7 @@ async function quarantineFile(path2, detections = [], dir = quarantineDir()) {
41816
42734
  const bin = (0, import_node_path22.join)(dir, `${id}.bin`);
41817
42735
  await (0, import_promises3.writeFile)(bin, xor(data), { mode: 384 });
41818
42736
  const check2 = xor(await (0, import_promises3.readFile)(bin));
41819
- if ((0, import_node_crypto7.createHash)("sha256").update(check2).digest("hex") !== sha256) {
42737
+ if ((0, import_node_crypto8.createHash)("sha256").update(check2).digest("hex") !== sha256) {
41820
42738
  await (0, import_promises3.rm)(bin, { force: true });
41821
42739
  throw new Error("quarantine copy did not verify; original left in place");
41822
42740
  }
@@ -41825,7 +42743,7 @@ async function quarantineFile(path2, detections = [], dir = quarantineDir()) {
41825
42743
  return entry;
41826
42744
  }
41827
42745
  async function listQuarantine(dir = quarantineDir()) {
41828
- if (!(0, import_node_fs25.existsSync)(dir)) return [];
42746
+ if (!(0, import_node_fs27.existsSync)(dir)) return [];
41829
42747
  const out = [];
41830
42748
  for (const f of await (0, import_promises3.readdir)(dir)) {
41831
42749
  if (!f.endsWith(".json")) continue;
@@ -41839,7 +42757,7 @@ async function listQuarantine(dir = quarantineDir()) {
41839
42757
  async function entryOf(id, dir) {
41840
42758
  if (!/^[\w-]+$/.test(id)) throw new Error(`bad quarantine id: ${id}`);
41841
42759
  const p = (0, import_node_path22.join)(dir, `${id}.json`);
41842
- if (!(0, import_node_fs25.existsSync)(p)) throw new Error(`no quarantined file with id ${id}`);
42760
+ if (!(0, import_node_fs27.existsSync)(p)) throw new Error(`no quarantined file with id ${id}`);
41843
42761
  return JSON.parse(await (0, import_promises3.readFile)(p, "utf8"));
41844
42762
  }
41845
42763
  async function restoreQuarantined(id, to, dir = quarantineDir()) {
@@ -41864,19 +42782,19 @@ async function deleteQuarantined(id, dir = quarantineDir()) {
41864
42782
  }
41865
42783
 
41866
42784
  // ../../packages/av/src/node/scan.ts
41867
- var import_node_crypto8 = require("crypto");
41868
- var import_node_fs26 = require("fs");
42785
+ var import_node_crypto9 = require("crypto");
42786
+ var import_node_fs28 = require("fs");
41869
42787
  var import_promises4 = require("fs/promises");
41870
- var import_node_os12 = require("os");
42788
+ var import_node_os13 = require("os");
41871
42789
  var import_node_worker_threads2 = require("worker_threads");
41872
42790
  var LOOKUP_KINDS = /* @__PURE__ */ new Set(["pe", "elf", "macho", "script", "lnk", "ole", "zip", "pdf", "dex", "rtf"]);
41873
42791
  var MAX_LOOKUPS = 5e3;
41874
42792
  async function readForScan(path2, size, cap) {
41875
- const hash = (0, import_node_crypto8.createHash)("sha256");
42793
+ const hash = (0, import_node_crypto9.createHash)("sha256");
41876
42794
  const head2 = Buffer.allocUnsafe(Math.min(size, cap));
41877
42795
  let filled = 0;
41878
42796
  await new Promise((resolve9, reject) => {
41879
- const s = (0, import_node_fs26.createReadStream)(path2, { highWaterMark: 1 << 20 });
42797
+ const s = (0, import_node_fs28.createReadStream)(path2, { highWaterMark: 1 << 20 });
41880
42798
  s.on("data", (chunk2) => {
41881
42799
  const c = chunk2;
41882
42800
  hash.update(c);
@@ -41902,9 +42820,9 @@ async function scanPaths(targets, opts = {}) {
41902
42820
  opts.onProgress?.({ type: "skip", path: path2, reason });
41903
42821
  };
41904
42822
  let signatures = opts.signatures;
41905
- if (opts.signatureFile && (0, import_node_fs26.existsSync)(opts.signatureFile)) {
42823
+ if (opts.signatureFile && (0, import_node_fs28.existsSync)(opts.signatureFile)) {
41906
42824
  signatures = signatures ?? new SignatureSet();
41907
- signatures.load((0, import_node_fs26.readFileSync)(opts.signatureFile, "utf8"));
42825
+ signatures.load((0, import_node_fs28.readFileSync)(opts.signatureFile, "utf8"));
41908
42826
  }
41909
42827
  const clamav = opts.clamav === "off" ? null : await detectClamAV();
41910
42828
  if (opts.clamav === "require" && !clamav?.available) throw new Error("ClamAV is not installed (or clamscan is not on PATH)");
@@ -41926,11 +42844,11 @@ async function scanPaths(targets, opts = {}) {
41926
42844
  if (o.kind === "result") record(o.result);
41927
42845
  else if (o.kind === "skip") skip(o.path, o.reason);
41928
42846
  };
41929
- const walk = () => walkFiles(targets, { signal: opts.signal, onSkip: skip });
42847
+ const walk2 = () => walkFiles(targets, { signal: opts.signal, onSkip: skip });
41930
42848
  if (opts.workerScript) {
41931
- await scanInWorkers(walk(), {
42849
+ await scanInWorkers(walk2(), {
41932
42850
  script: opts.workerScript,
41933
- workers: Math.max(1, opts.concurrency ?? (0, import_node_os12.availableParallelism)()),
42851
+ workers: Math.max(1, opts.concurrency ?? (0, import_node_os13.availableParallelism)()),
41934
42852
  init: { cap, maxFile, signatures: signatures?.entries() },
41935
42853
  signal: opts.signal,
41936
42854
  take
@@ -41956,7 +42874,7 @@ async function scanPaths(targets, opts = {}) {
41956
42874
  record({ path: path2, size, sha256: null, kind: "unknown", verdict: "error", detections: [], note: code });
41957
42875
  }
41958
42876
  };
41959
- for await (const path2 of walk()) {
42877
+ for await (const path2 of walk2()) {
41960
42878
  if (opts.signal?.aborted) break;
41961
42879
  const p = scanOne(path2).finally(() => queue.delete(p));
41962
42880
  queue.add(p);
@@ -42065,7 +42983,7 @@ function applyAll(results, reps) {
42065
42983
  }
42066
42984
 
42067
42985
  // ../../packages/av/src/node/watch.ts
42068
- var import_node_fs27 = require("fs");
42986
+ var import_node_fs29 = require("fs");
42069
42987
  var import_promises5 = require("fs/promises");
42070
42988
  var import_node_path23 = require("path");
42071
42989
  var IN_PROGRESS = /\.(?:crdownload|part|partial|download|tmp)$/i;
@@ -42097,7 +43015,7 @@ function watchTargets(targets, opts) {
42097
43015
  };
42098
43016
  for (const t of targets) {
42099
43017
  try {
42100
- const w = (0, import_node_fs27.watch)(t.path, { recursive: t.depth > 1, persistent: true }, (_event, file) => {
43018
+ const w = (0, import_node_fs29.watch)(t.path, { recursive: t.depth > 1, persistent: true }, (_event, file) => {
42101
43019
  if (!file) return;
42102
43020
  const rel = String(file);
42103
43021
  if (IN_PROGRESS.test(rel)) return;
@@ -42123,11 +43041,11 @@ function watchTargets(targets, opts) {
42123
43041
 
42124
43042
  // src/commands/av.ts
42125
43043
  init_cli_config();
42126
- var SIGNATURE_FILE = (0, import_node_path24.join)((0, import_node_os13.homedir)(), ".threatcrush", "av", "signatures.txt");
43044
+ var SIGNATURE_FILE = (0, import_node_path24.join)((0, import_node_os14.homedir)(), ".threatcrush", "av", "signatures.txt");
42127
43045
  function avWorkerScript() {
42128
43046
  if (typeof __dirname === "undefined") return void 0;
42129
43047
  const p = (0, import_node_path24.join)(__dirname, "av-worker.js");
42130
- return (0, import_node_fs28.existsSync)(p) ? p : void 0;
43048
+ return (0, import_node_fs30.existsSync)(p) ? p : void 0;
42131
43049
  }
42132
43050
  var icon2 = (v) => v === "malicious" ? source_default.red("\u2716 MALWARE") : v === "suspicious" ? source_default.yellow("\u25B2 SUSPICIOUS") : v === "error" ? source_default.gray("? ERROR") : source_default.green("\u2713 clean");
42133
43051
  async function avScanCommand(paths, opts = {}) {
@@ -42143,7 +43061,7 @@ async function avScanCommand(paths, opts = {}) {
42143
43061
  targets = quickScanTargets();
42144
43062
  label = "quick scan (downloads, desktop, temp and startup locations)";
42145
43063
  }
42146
- const missing = targets.filter((t) => !(0, import_node_fs28.existsSync)(t.path));
43064
+ const missing = targets.filter((t) => !(0, import_node_fs30.existsSync)(t.path));
42147
43065
  if (paths.length && missing.length) {
42148
43066
  console.error(source_default.red(` Not found: ${missing.map((m) => m.path).join(", ")}`));
42149
43067
  process.exitCode = 2;
@@ -42230,7 +43148,7 @@ async function avStatusCommand(opts = {}) {
42230
43148
  const status = {
42231
43149
  engine: "CrushAV",
42232
43150
  heuristic_rules: RULES.length,
42233
- custom_signatures: (0, import_node_fs28.existsSync)(SIGNATURE_FILE) ? SIGNATURE_FILE : null,
43151
+ custom_signatures: (0, import_node_fs30.existsSync)(SIGNATURE_FILE) ? SIGNATURE_FILE : null,
42234
43152
  clamav: clam,
42235
43153
  reputation_endpoint: `${apiUrl()}/api/av/lookup`,
42236
43154
  quarantine_dir: quarantineDir(),
@@ -42337,7 +43255,7 @@ async function avTestCommand() {
42337
43255
  }
42338
43256
 
42339
43257
  // src/commands/ai-scan.ts
42340
- var import_node_fs30 = require("fs");
43258
+ var import_node_fs32 = require("fs");
42341
43259
 
42342
43260
  // src/aiscan/probes.ts
42343
43261
  function makeCanary() {
@@ -42554,8 +43472,8 @@ ${stripShebang(source)}
42554
43472
  }
42555
43473
 
42556
43474
  // src/core/usage-ping.ts
42557
- var import_node_crypto9 = require("crypto");
42558
- var import_node_fs29 = require("fs");
43475
+ var import_node_crypto10 = require("crypto");
43476
+ var import_node_fs31 = require("fs");
42559
43477
  var import_node_path25 = require("path");
42560
43478
  init_cli_config();
42561
43479
  var STATE_FILE = "usage-ping.json";
@@ -42568,14 +43486,14 @@ function usagePingDisabled(env3 = process.env) {
42568
43486
  function installId(dir = CLI_CONFIG_DIR) {
42569
43487
  const file = (0, import_node_path25.join)(dir, STATE_FILE);
42570
43488
  try {
42571
- const j = JSON.parse((0, import_node_fs29.readFileSync)(file, "utf-8"));
43489
+ const j = JSON.parse((0, import_node_fs31.readFileSync)(file, "utf-8"));
42572
43490
  if (j.install_id) return { id: j.install_id, fresh: false };
42573
43491
  } catch {
42574
43492
  }
42575
- const id = (0, import_node_crypto9.randomUUID)();
43493
+ const id = (0, import_node_crypto10.randomUUID)();
42576
43494
  try {
42577
- if (!(0, import_node_fs29.existsSync)(dir)) (0, import_node_fs29.mkdirSync)(dir, { recursive: true });
42578
- (0, import_node_fs29.writeFileSync)(file, JSON.stringify({ install_id: id, created_at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
43495
+ if (!(0, import_node_fs31.existsSync)(dir)) (0, import_node_fs31.mkdirSync)(dir, { recursive: true });
43496
+ (0, import_node_fs31.writeFileSync)(file, JSON.stringify({ install_id: id, created_at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
42579
43497
  } catch {
42580
43498
  }
42581
43499
  return { id, fresh: true };
@@ -42683,7 +43601,7 @@ async function aiScanMoshCommand(file, args) {
42683
43601
  console.log();
42684
43602
  let source;
42685
43603
  try {
42686
- source = (0, import_node_fs30.readFileSync)(file, "utf-8");
43604
+ source = (0, import_node_fs32.readFileSync)(file, "utf-8");
42687
43605
  } catch (err) {
42688
43606
  logger.error(`Cannot read ${file}: ${err.message}`);
42689
43607
  process.exitCode = 1;
@@ -42712,22 +43630,22 @@ async function aiScanMoshCommand(file, args) {
42712
43630
  }
42713
43631
 
42714
43632
  // src/commands/orgs.ts
42715
- var import_node_os14 = require("os");
42716
- var import_node_fs31 = require("fs");
43633
+ var import_node_os15 = require("os");
43634
+ var import_node_fs33 = require("fs");
42717
43635
  var import_node_path26 = require("path");
42718
43636
  var API_URL3 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
42719
- var CONFIG_PATH = (0, import_node_path26.join)((0, import_node_os14.homedir)(), ".threatcrush", "config.json");
43637
+ var CONFIG_PATH = (0, import_node_path26.join)((0, import_node_os15.homedir)(), ".threatcrush", "config.json");
42720
43638
  function readConfig() {
42721
43639
  try {
42722
- return JSON.parse((0, import_node_fs31.readFileSync)(CONFIG_PATH, "utf-8"));
43640
+ return JSON.parse((0, import_node_fs33.readFileSync)(CONFIG_PATH, "utf-8"));
42723
43641
  } catch {
42724
43642
  return {};
42725
43643
  }
42726
43644
  }
42727
43645
  function writeConfig(config) {
42728
- const dir = (0, import_node_path26.join)((0, import_node_os14.homedir)(), ".threatcrush");
42729
- if (!(0, import_node_fs31.existsSync)(dir)) (0, import_node_fs31.mkdirSync)(dir, { recursive: true });
42730
- (0, import_node_fs31.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
43646
+ const dir = (0, import_node_path26.join)((0, import_node_os15.homedir)(), ".threatcrush");
43647
+ if (!(0, import_node_fs33.existsSync)(dir)) (0, import_node_fs33.mkdirSync)(dir, { recursive: true });
43648
+ (0, import_node_fs33.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
42731
43649
  }
42732
43650
  function getAuthHeaders() {
42733
43651
  const config = readConfig();
@@ -42862,14 +43780,14 @@ async function useOrganization(slug) {
42862
43780
  }
42863
43781
 
42864
43782
  // src/commands/credits.ts
42865
- var import_node_os15 = require("os");
42866
- var import_node_fs32 = require("fs");
43783
+ var import_node_os16 = require("os");
43784
+ var import_node_fs34 = require("fs");
42867
43785
  var import_node_path27 = require("path");
42868
43786
  var API_URL4 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
42869
- var CONFIG_PATH2 = (0, import_node_path27.join)((0, import_node_os15.homedir)(), ".threatcrush", "config.json");
43787
+ var CONFIG_PATH2 = (0, import_node_path27.join)((0, import_node_os16.homedir)(), ".threatcrush", "config.json");
42870
43788
  function sessionToken() {
42871
43789
  try {
42872
- const cfg = JSON.parse((0, import_node_fs32.readFileSync)(CONFIG_PATH2, "utf-8"));
43790
+ const cfg = JSON.parse((0, import_node_fs34.readFileSync)(CONFIG_PATH2, "utf-8"));
42873
43791
  return cfg.token ?? null;
42874
43792
  } catch {
42875
43793
  return null;
@@ -43035,7 +43953,7 @@ function formatTotal(monthly) {
43035
43953
 
43036
43954
  // src/commands/servers.ts
43037
43955
  var import_node_readline2 = __toESM(require("readline"));
43038
- var import_node_os16 = require("os");
43956
+ var import_node_os17 = require("os");
43039
43957
  init_cli_config();
43040
43958
  function connectionStatus(server, now = Date.now()) {
43041
43959
  const seen = server.last_seen ? Date.parse(server.last_seen) : NaN;
@@ -43134,7 +44052,7 @@ async function chooseOrg(orgs, flag, ask2) {
43134
44052
  async function linkServer(opts = {}, ask2 = askChoice) {
43135
44053
  if (!hasSession()) throw new Error("Not logged in. Run: threatcrush login");
43136
44054
  const org = await chooseOrg(await fetchOrgs(), opts.org, ask2);
43137
- const host = opts.hostname ?? (0, import_node_os16.hostname)();
44055
+ const host = opts.hostname ?? (0, import_node_os17.hostname)();
43138
44056
  const listRes = await cloudFetch(`/api/orgs/${org.id}/servers`);
43139
44057
  if (!listRes.ok) throw new Error(`Failed to list servers in /${org.slug} (${listRes.status})`);
43140
44058
  const { servers = [] } = await listRes.json();
@@ -43251,16 +44169,16 @@ function timeAgo(dateStr) {
43251
44169
  }
43252
44170
 
43253
44171
  // src/commands/connect.ts
43254
- var import_node_os17 = require("os");
43255
- var import_node_fs33 = require("fs");
44172
+ var import_node_os18 = require("os");
44173
+ var import_node_fs35 = require("fs");
43256
44174
  var import_node_path28 = require("path");
43257
- var import_node_child_process6 = require("child_process");
44175
+ var import_node_child_process7 = require("child_process");
43258
44176
  var import_node_net4 = require("net");
43259
44177
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
43260
- var CONFIG_PATH3 = (0, import_node_path28.join)((0, import_node_os17.homedir)(), ".threatcrush", "config.json");
44178
+ var CONFIG_PATH3 = (0, import_node_path28.join)((0, import_node_os18.homedir)(), ".threatcrush", "config.json");
43261
44179
  function readConfig2() {
43262
44180
  try {
43263
- return JSON.parse((0, import_node_fs33.readFileSync)(CONFIG_PATH3, "utf-8"));
44181
+ return JSON.parse((0, import_node_fs35.readFileSync)(CONFIG_PATH3, "utf-8"));
43264
44182
  } catch {
43265
44183
  return {};
43266
44184
  }
@@ -43413,7 +44331,7 @@ async function sshConnect(options) {
43413
44331
  `));
43414
44332
  console.log(source_default.dim(" (Spawning SSH session \u2014 exit with Ctrl+D or type 'exit')\n"));
43415
44333
  const sshArgs = sshArgv({ hostname: hostname7, username: user, port, identity });
43416
- const ssh = (0, import_node_child_process6.spawn)("ssh", sshArgs, { stdio: "inherit" });
44334
+ const ssh = (0, import_node_child_process7.spawn)("ssh", sshArgs, { stdio: "inherit" });
43417
44335
  ssh.on("error", (err) => {
43418
44336
  console.log(source_default.red(`
43419
44337
  SSH error: ${err.message}
@@ -43431,22 +44349,22 @@ async function sshConnect(options) {
43431
44349
  }
43432
44350
 
43433
44351
  // src/commands/daemon.ts
43434
- var import_node_child_process22 = require("child_process");
43435
- var import_node_fs60 = require("fs");
44352
+ var import_node_child_process23 = require("child_process");
44353
+ var import_node_fs62 = require("fs");
43436
44354
  var import_node_path47 = require("path");
43437
- var import_node_fs61 = require("fs");
44355
+ var import_node_fs63 = require("fs");
43438
44356
 
43439
44357
  // src/daemon/index.ts
43440
- var import_node_fs59 = require("fs");
43441
- var import_node_child_process21 = require("child_process");
43442
- var import_node_os19 = require("os");
44358
+ var import_node_fs61 = require("fs");
44359
+ var import_node_child_process22 = require("child_process");
44360
+ var import_node_os20 = require("os");
43443
44361
  var import_node_path46 = require("path");
43444
44362
  var import_node_util4 = require("util");
43445
44363
  init_paths();
43446
44364
 
43447
44365
  // src/daemon/ipc-server.ts
43448
44366
  var import_node_net5 = require("net");
43449
- var import_node_fs34 = require("fs");
44367
+ var import_node_fs36 = require("fs");
43450
44368
  init_paths();
43451
44369
  init_control_token();
43452
44370
 
@@ -43504,9 +44422,9 @@ var IpcServer = class {
43504
44422
  controlToken = "";
43505
44423
  async start() {
43506
44424
  this.controlToken = issueControlToken();
43507
- if ((0, import_node_fs34.existsSync)(PATHS.socket)) {
44425
+ if ((0, import_node_fs36.existsSync)(PATHS.socket)) {
43508
44426
  try {
43509
- (0, import_node_fs34.unlinkSync)(PATHS.socket);
44427
+ (0, import_node_fs36.unlinkSync)(PATHS.socket);
43510
44428
  } catch {
43511
44429
  }
43512
44430
  }
@@ -43544,14 +44462,14 @@ var IpcServer = class {
43544
44462
  return new Promise((resolve9) => {
43545
44463
  if (!this.server) {
43546
44464
  try {
43547
- if ((0, import_node_fs34.existsSync)(PATHS.socket)) (0, import_node_fs34.unlinkSync)(PATHS.socket);
44465
+ if ((0, import_node_fs36.existsSync)(PATHS.socket)) (0, import_node_fs36.unlinkSync)(PATHS.socket);
43548
44466
  } catch {
43549
44467
  }
43550
44468
  return resolve9();
43551
44469
  }
43552
44470
  this.server.close(() => {
43553
44471
  try {
43554
- if ((0, import_node_fs34.existsSync)(PATHS.socket)) (0, import_node_fs34.unlinkSync)(PATHS.socket);
44472
+ if ((0, import_node_fs36.existsSync)(PATHS.socket)) (0, import_node_fs36.unlinkSync)(PATHS.socket);
43555
44473
  } catch {
43556
44474
  }
43557
44475
  resolve9();
@@ -43731,7 +44649,7 @@ var IpcServer = class {
43731
44649
  }
43732
44650
  }
43733
44651
  };
43734
- function admGid(readGroup = () => (0, import_node_fs34.readFileSync)("/etc/group", "utf-8"), statAuthLog = () => (0, import_node_fs34.statSync)("/var/log/auth.log")) {
44652
+ function admGid(readGroup = () => (0, import_node_fs36.readFileSync)("/etc/group", "utf-8"), statAuthLog = () => (0, import_node_fs36.statSync)("/var/log/auth.log")) {
43735
44653
  try {
43736
44654
  for (const line2 of readGroup().split("\n")) {
43737
44655
  const [name, , gid] = line2.split(":");
@@ -43747,14 +44665,14 @@ function admGid(readGroup = () => (0, import_node_fs34.readFileSync)("/etc/group
43747
44665
  }
43748
44666
 
43749
44667
  // src/daemon/module-host.ts
43750
- var import_node_fs40 = require("fs");
44668
+ var import_node_fs42 = require("fs");
43751
44669
  var import_node_path31 = require("path");
43752
44670
  var import_node_url = require("url");
43753
44671
  var import_toml5 = __toESM(require_toml());
43754
44672
  init_paths();
43755
44673
 
43756
44674
  // src/daemon/watchers/log-watcher.ts
43757
- var import_node_fs35 = require("fs");
44675
+ var import_node_fs37 = require("fs");
43758
44676
  var import_node_path29 = require("path");
43759
44677
  var import_toml4 = __toESM(require_toml());
43760
44678
  var DEFAULT_SOURCES = [
@@ -43770,23 +44688,23 @@ function configuredWebSources(configFile, confD) {
43770
44688
  if (!Array.isArray(v)) return;
43771
44689
  for (const p of v) if (typeof p === "string" && p.startsWith("/")) paths.push(p);
43772
44690
  };
43773
- const read = (file) => {
44691
+ const read2 = (file) => {
43774
44692
  try {
43775
- return import_toml4.default.parse((0, import_node_fs35.readFileSync)(file, "utf-8"));
44693
+ return import_toml4.default.parse((0, import_node_fs37.readFileSync)(file, "utf-8"));
43776
44694
  } catch {
43777
44695
  return null;
43778
44696
  }
43779
44697
  };
43780
- const main = (0, import_node_fs35.existsSync)(configFile) ? read(configFile) : null;
44698
+ const main = (0, import_node_fs37.existsSync)(configFile) ? read2(configFile) : null;
43781
44699
  take(main?.modules?.["log-watcher"]?.paths);
43782
44700
  take(main?.["log-watcher"]?.paths);
43783
- if ((0, import_node_fs35.existsSync)(confD)) {
44701
+ if ((0, import_node_fs37.existsSync)(confD)) {
43784
44702
  let files = [];
43785
44703
  try {
43786
- files = (0, import_node_fs35.readdirSync)(confD).filter((f) => f.endsWith(".conf")).sort();
44704
+ files = (0, import_node_fs37.readdirSync)(confD).filter((f) => f.endsWith(".conf")).sort();
43787
44705
  } catch {
43788
44706
  }
43789
- for (const f of files) take(read((0, import_node_path29.join)(confD, f))?.["log-watcher"]?.paths);
44707
+ for (const f of files) take(read2((0, import_node_path29.join)(confD, f))?.["log-watcher"]?.paths);
43790
44708
  }
43791
44709
  const known = new Set(DEFAULT_SOURCES.map((s) => s.path));
43792
44710
  const out = [];
@@ -43812,9 +44730,9 @@ var LogWatcher = class {
43812
44730
  start() {
43813
44731
  const started = [];
43814
44732
  for (const src of this.sources) {
43815
- if (!(0, import_node_fs35.existsSync)(src.path)) continue;
44733
+ if (!(0, import_node_fs37.existsSync)(src.path)) continue;
43816
44734
  try {
43817
- (0, import_node_fs35.accessSync)(src.path, import_node_fs35.constants.R_OK);
44735
+ (0, import_node_fs37.accessSync)(src.path, import_node_fs37.constants.R_OK);
43818
44736
  } catch {
43819
44737
  continue;
43820
44738
  }
@@ -43975,13 +44893,13 @@ var JournalProvenance = class {
43975
44893
  };
43976
44894
 
43977
44895
  // src/daemon/watchers/journal-watcher.ts
43978
- var import_node_child_process7 = require("child_process");
44896
+ var import_node_child_process8 = require("child_process");
43979
44897
  var SSHD_COMMS = ["sshd", "sshd-session"];
43980
44898
  var accountNames = /* @__PURE__ */ new Map();
43981
44899
  function accountNameForUid(value) {
43982
44900
  if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
43983
44901
  if (accountNames.has(value)) return accountNames.get(value) ?? null;
43984
- const result = (0, import_node_child_process7.spawnSync)("getent", ["passwd", value], {
44902
+ const result = (0, import_node_child_process8.spawnSync)("getent", ["passwd", value], {
43985
44903
  encoding: "utf-8",
43986
44904
  timeout: 1e3,
43987
44905
  maxBuffer: 4096,
@@ -44044,14 +44962,14 @@ var JournalWatcher = class _JournalWatcher {
44044
44962
  return isRoot4 ? [] : ["--user"];
44045
44963
  }
44046
44964
  static isAvailable() {
44047
- const probe = (0, import_node_child_process7.spawnSync)("journalctl", [...this.scopeArgs(), "-n", "0", "--no-pager"], {
44965
+ const probe = (0, import_node_child_process8.spawnSync)("journalctl", [...this.scopeArgs(), "-n", "0", "--no-pager"], {
44048
44966
  stdio: ["ignore", "ignore", "ignore"]
44049
44967
  });
44050
44968
  return probe.status === 0;
44051
44969
  }
44052
44970
  start() {
44053
44971
  if (!_JournalWatcher.isAvailable()) return false;
44054
- const child = (0, import_node_child_process7.spawn)(
44972
+ const child = (0, import_node_child_process8.spawn)(
44055
44973
  "journalctl",
44056
44974
  [..._JournalWatcher.scopeArgs(), "-o", "json", "-f", "--since", "now"],
44057
44975
  { stdio: ["ignore", "pipe", "pipe"] }
@@ -44076,14 +44994,14 @@ var JournalWatcher = class _JournalWatcher {
44076
44994
  * nothing and looking like protection.
44077
44995
  */
44078
44996
  startSshd() {
44079
- const probe = (0, import_node_child_process7.spawnSync)("journalctl", ["-q", "-n", "1", "-o", "cat", "--no-pager", "_UID=0"], {
44997
+ const probe = (0, import_node_child_process8.spawnSync)("journalctl", ["-q", "-n", "1", "-o", "cat", "--no-pager", "_UID=0"], {
44080
44998
  stdio: ["ignore", "pipe", "ignore"],
44081
44999
  encoding: "utf-8"
44082
45000
  });
44083
45001
  if (probe.error || probe.status !== 0) return "unavailable";
44084
45002
  if (!probe.stdout.trim()) return "unreadable";
44085
45003
  const matches2 = ["_UID=0", ...SSHD_COMMS.map((comm) => `_COMM=${comm}`)];
44086
- const child = (0, import_node_child_process7.spawn)("journalctl", ["-o", "json", "-f", "--since", "now", ...matches2], {
45004
+ const child = (0, import_node_child_process8.spawn)("journalctl", ["-o", "json", "-f", "--since", "now", ...matches2], {
44087
45005
  stdio: ["ignore", "pipe", "ignore"]
44088
45006
  });
44089
45007
  if (!child.stdout) return "unavailable";
@@ -44199,8 +45117,8 @@ function realtimeToDate(rt) {
44199
45117
  }
44200
45118
 
44201
45119
  // src/modules/network-monitor/index.ts
44202
- var import_node_child_process8 = require("child_process");
44203
- var import_node_fs36 = require("fs");
45120
+ var import_node_child_process9 = require("child_process");
45121
+ var import_node_fs38 = require("fs");
44204
45122
  var NetworkMonitor = class {
44205
45123
  constructor(bus2) {
44206
45124
  this.bus = bus2;
@@ -44262,9 +45180,9 @@ var NetworkMonitor = class {
44262
45180
  return this.active;
44263
45181
  }
44264
45182
  hasConntrackOrSs() {
44265
- const ss = (0, import_node_child_process8.spawnSync)("ss", ["--version"], { stdio: "pipe" });
45183
+ const ss = (0, import_node_child_process9.spawnSync)("ss", ["--version"], { stdio: "pipe" });
44266
45184
  if (ss.status === 0) return true;
44267
- return (0, import_node_fs36.existsSync)("/proc/net/tcp");
45185
+ return (0, import_node_fs38.existsSync)("/proc/net/tcp");
44268
45186
  }
44269
45187
  /**
44270
45188
  * The TCP ports this host actually listens on.
@@ -44279,7 +45197,7 @@ var NetworkMonitor = class {
44279
45197
  listeningPorts() {
44280
45198
  const ports = /* @__PURE__ */ new Set();
44281
45199
  try {
44282
- const out = (0, import_node_child_process8.spawnSync)("ss", ["-ltnH"], { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"], timeout: 3e3 });
45200
+ const out = (0, import_node_child_process9.spawnSync)("ss", ["-ltnH"], { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"], timeout: 3e3 });
44283
45201
  if (out.status === 0 && out.stdout) {
44284
45202
  for (const line2 of out.stdout.split("\n")) {
44285
45203
  const parts = line2.trim().split(/\s+/);
@@ -44310,7 +45228,7 @@ var NetworkMonitor = class {
44310
45228
  const listening = this.listeningPorts();
44311
45229
  if (listening.size === 0) return records;
44312
45230
  try {
44313
- const ct = (0, import_node_child_process8.spawnSync)("conntrack", ["-L", "-p", "tcp", "-o", "extended"], {
45231
+ const ct = (0, import_node_child_process9.spawnSync)("conntrack", ["-L", "-p", "tcp", "-o", "extended"], {
44314
45232
  encoding: "utf-8",
44315
45233
  stdio: ["pipe", "pipe", "pipe"],
44316
45234
  timeout: 3e3
@@ -44330,7 +45248,7 @@ var NetworkMonitor = class {
44330
45248
  } catch {
44331
45249
  }
44332
45250
  try {
44333
- const ss = (0, import_node_child_process8.spawnSync)("ss", ["-tnp", "-H"], {
45251
+ const ss = (0, import_node_child_process9.spawnSync)("ss", ["-tnp", "-H"], {
44334
45252
  encoding: "utf-8",
44335
45253
  stdio: ["pipe", "pipe", "pipe"],
44336
45254
  timeout: 3e3
@@ -44394,7 +45312,7 @@ var NetworkMonitor = class {
44394
45312
  }
44395
45313
  analyzeSynFlood(connections) {
44396
45314
  try {
44397
- const ss = (0, import_node_child_process8.spawnSync)("ss", ["-tn", "state", "syn-recv", "-H"], {
45315
+ const ss = (0, import_node_child_process9.spawnSync)("ss", ["-tn", "state", "syn-recv", "-H"], {
44398
45316
  encoding: "utf-8",
44399
45317
  stdio: ["pipe", "pipe", "pipe"],
44400
45318
  timeout: 3e3
@@ -44451,18 +45369,18 @@ var NetworkMonitor = class {
44451
45369
  };
44452
45370
 
44453
45371
  // src/modules/dns-monitor/index.ts
44454
- var import_node_fs39 = require("fs");
44455
- var import_node_child_process10 = require("child_process");
45372
+ var import_node_fs41 = require("fs");
45373
+ var import_node_child_process11 = require("child_process");
44456
45374
  var import_node_readline3 = require("readline");
44457
45375
 
44458
45376
  // src/core/threat-feeds/index.ts
44459
- var import_node_fs38 = require("fs");
45377
+ var import_node_fs40 = require("fs");
44460
45378
  var import_node_path30 = require("path");
44461
45379
  var import_node_net7 = require("net");
44462
45380
 
44463
45381
  // src/daemon/firewall/protected.ts
44464
- var import_node_child_process9 = require("child_process");
44465
- var import_node_fs37 = require("fs");
45382
+ var import_node_child_process10 = require("child_process");
45383
+ var import_node_fs39 = require("fs");
44466
45384
  var import_node_net6 = require("net");
44467
45385
  var DEFAULT_PROTECTED = [
44468
45386
  "127.0.0.0/8",
@@ -44584,8 +45502,8 @@ function ipMatches(ip, entry) {
44584
45502
  const mask = 255 << 8 - remainder & 255;
44585
45503
  return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
44586
45504
  }
44587
- function isProtected(ip, list) {
44588
- return list.some((entry) => ipMatches(ip, entry));
45505
+ function isProtected(ip, list2) {
45506
+ return list2.some((entry) => ipMatches(ip, entry));
44589
45507
  }
44590
45508
  function currentSshClient(env3 = process.env) {
44591
45509
  const source = env3.SSH_CLIENT || env3.SSH_CONNECTION;
@@ -44596,7 +45514,7 @@ function currentSshClient(env3 = process.env) {
44596
45514
  function establishedSshPeers() {
44597
45515
  const peers = /* @__PURE__ */ new Set();
44598
45516
  try {
44599
- const out = (0, import_node_child_process9.execFileSync)("ss", ["-tnpH"], {
45517
+ const out = (0, import_node_child_process10.execFileSync)("ss", ["-tnpH"], {
44600
45518
  encoding: "utf-8",
44601
45519
  stdio: ["ignore", "pipe", "ignore"],
44602
45520
  timeout: 3e3
@@ -44624,14 +45542,14 @@ function moshClients(procDir = "/proc") {
44624
45542
  const found = /* @__PURE__ */ new Set();
44625
45543
  let pids = [];
44626
45544
  try {
44627
- pids = (0, import_node_fs37.readdirSync)(procDir).filter((p) => /^\d+$/.test(p));
45545
+ pids = (0, import_node_fs39.readdirSync)(procDir).filter((p) => /^\d+$/.test(p));
44628
45546
  } catch {
44629
45547
  return [];
44630
45548
  }
44631
45549
  for (const pid of pids) {
44632
45550
  try {
44633
- if ((0, import_node_fs37.readFileSync)(`${procDir}/${pid}/comm`, "utf-8").trim() !== "mosh-server") continue;
44634
- const ip = sshClientFromEnviron((0, import_node_fs37.readFileSync)(`${procDir}/${pid}/environ`, "latin1"));
45551
+ if ((0, import_node_fs39.readFileSync)(`${procDir}/${pid}/comm`, "utf-8").trim() !== "mosh-server") continue;
45552
+ const ip = sshClientFromEnviron((0, import_node_fs39.readFileSync)(`${procDir}/${pid}/environ`, "latin1"));
44635
45553
  if (ip) found.add(ip);
44636
45554
  } catch {
44637
45555
  }
@@ -44656,7 +45574,7 @@ function defaultGateways() {
44656
45574
  const found = /* @__PURE__ */ new Set();
44657
45575
  for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
44658
45576
  try {
44659
- const out = (0, import_node_child_process9.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
45577
+ const out = (0, import_node_child_process10.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
44660
45578
  for (const line2 of out.split("\n")) {
44661
45579
  const match = line2.match(/\bvia\s+(\S+)/);
44662
45580
  if (match && (0, import_node_net6.isIP)(match[1])) found.add(match[1]);
@@ -44837,17 +45755,17 @@ async function fetchFeeds(settings, fetchImpl = fetch) {
44837
45755
  }
44838
45756
  function readFeedCache(path2) {
44839
45757
  try {
44840
- const set = JSON.parse((0, import_node_fs38.readFileSync)(path2, "utf-8"));
45758
+ const set = JSON.parse((0, import_node_fs40.readFileSync)(path2, "utf-8"));
44841
45759
  return set && typeof set.ips === "object" && typeof set.domains === "object" ? set : null;
44842
45760
  } catch {
44843
45761
  return null;
44844
45762
  }
44845
45763
  }
44846
45764
  function writeFeedCache(path2, set) {
44847
- (0, import_node_fs38.mkdirSync)((0, import_node_path30.dirname)(path2), { recursive: true });
45765
+ (0, import_node_fs40.mkdirSync)((0, import_node_path30.dirname)(path2), { recursive: true });
44848
45766
  const tmp = `${path2}.tmp`;
44849
- (0, import_node_fs38.writeFileSync)(tmp, JSON.stringify(set));
44850
- (0, import_node_fs38.renameSync)(tmp, path2);
45767
+ (0, import_node_fs40.writeFileSync)(tmp, JSON.stringify(set));
45768
+ (0, import_node_fs40.renameSync)(tmp, path2);
44851
45769
  }
44852
45770
  var RESOLVER_FILES = {
44853
45771
  hosts: "blocked-domains.hosts",
@@ -44960,7 +45878,7 @@ var DnsMonitor = class {
44960
45878
  /** True if a systemd unit is loaded on this host (so we do not tail nothing). */
44961
45879
  unitExists(unit) {
44962
45880
  try {
44963
- const r = (0, import_node_child_process10.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
45881
+ const r = (0, import_node_child_process11.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
44964
45882
  encoding: "utf-8",
44965
45883
  stdio: ["ignore", "pipe", "ignore"],
44966
45884
  timeout: 3e3
@@ -44972,9 +45890,9 @@ var DnsMonitor = class {
44972
45890
  }
44973
45891
  start() {
44974
45892
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
44975
- if (!(0, import_node_fs39.existsSync)(p)) return false;
45893
+ if (!(0, import_node_fs41.existsSync)(p)) return false;
44976
45894
  try {
44977
- (0, import_node_fs39.accessSync)(p, import_node_fs39.constants.R_OK);
45895
+ (0, import_node_fs41.accessSync)(p, import_node_fs41.constants.R_OK);
44978
45896
  return true;
44979
45897
  } catch {
44980
45898
  return false;
@@ -45033,7 +45951,7 @@ var DnsMonitor = class {
45033
45951
  /** Follow one systemd unit's journal, feeding its lines to the same parser. */
45034
45952
  tailJournalUnit(unit) {
45035
45953
  try {
45036
- const child = (0, import_node_child_process10.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
45954
+ const child = (0, import_node_child_process11.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
45037
45955
  stdio: ["ignore", "pipe", "ignore"]
45038
45956
  });
45039
45957
  if (!child.stdout) return;
@@ -45334,15 +46252,15 @@ var ModuleHost = class {
45334
46252
  }
45335
46253
  }
45336
46254
  async discoverAndStartInstalled() {
45337
- if (!(0, import_node_fs40.existsSync)(PATHS.moduleDir)) return;
46255
+ if (!(0, import_node_fs42.existsSync)(PATHS.moduleDir)) return;
45338
46256
  const configs = loadModuleConfigs(PATHS.confD);
45339
- const entries = (0, import_node_fs40.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
46257
+ const entries = (0, import_node_fs42.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
45340
46258
  for (const entry of entries) {
45341
46259
  if (!entry.isDirectory()) continue;
45342
46260
  const manifestPath = (0, import_node_path31.join)(PATHS.moduleDir, entry.name, "mod.toml");
45343
- if (!(0, import_node_fs40.existsSync)(manifestPath)) continue;
46261
+ if (!(0, import_node_fs42.existsSync)(manifestPath)) continue;
45344
46262
  try {
45345
- const manifest = import_toml5.default.parse((0, import_node_fs40.readFileSync)(manifestPath, "utf-8"));
46263
+ const manifest = import_toml5.default.parse((0, import_node_fs42.readFileSync)(manifestPath, "utf-8"));
45346
46264
  const name = manifest.module?.name || entry.name;
45347
46265
  const defaults = manifest.module?.config?.defaults || {};
45348
46266
  const config = {
@@ -45412,15 +46330,15 @@ var ModuleHost = class {
45412
46330
  installedEntrypoint(modulePath) {
45413
46331
  const packageJson = (0, import_node_path31.join)(modulePath, "package.json");
45414
46332
  const candidates = [];
45415
- if ((0, import_node_fs40.existsSync)(packageJson)) {
46333
+ if ((0, import_node_fs42.existsSync)(packageJson)) {
45416
46334
  try {
45417
- const pkg = JSON.parse((0, import_node_fs40.readFileSync)(packageJson, "utf-8"));
46335
+ const pkg = JSON.parse((0, import_node_fs42.readFileSync)(packageJson, "utf-8"));
45418
46336
  if (pkg.main) candidates.push((0, import_node_path31.join)(modulePath, pkg.main));
45419
46337
  } catch {
45420
46338
  }
45421
46339
  }
45422
46340
  candidates.push((0, import_node_path31.join)(modulePath, "dist", "index.js"), (0, import_node_path31.join)(modulePath, "index.js"));
45423
- return candidates.find((candidate) => (0, import_node_fs40.existsSync)(candidate)) || null;
46341
+ return candidates.find((candidate) => (0, import_node_fs42.existsSync)(candidate)) || null;
45424
46342
  }
45425
46343
  isThreatCrushModule(value) {
45426
46344
  return Boolean(
@@ -45617,11 +46535,11 @@ function pagerdutyChannel(config) {
45617
46535
  }
45618
46536
 
45619
46537
  // src/daemon/alerts/smshub.ts
45620
- var import_node_os18 = require("os");
46538
+ var import_node_os19 = require("os");
45621
46539
  var SEVERITY_RANK6 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
45622
46540
  var DEDUPE_MS = 10 * 6e4;
45623
46541
  var MAX_PER_HOUR = 6;
45624
- function smshubText(event, host = (0, import_node_os18.hostname)()) {
46542
+ function smshubText(event, host = (0, import_node_os19.hostname)()) {
45625
46543
  const evidence = event.details?.evidence?.message;
45626
46544
  const ip = event.source_ip && ![event.message, evidence ?? ""].some((t) => t.includes(event.source_ip)) ? ` from ${event.source_ip}` : "";
45627
46545
  const text = `ThreatCrush ${event.severity.toUpperCase()} on ${host}: ${event.message}${evidence && !event.message.includes(evidence) ? ` | ${evidence}` : ""}${ip}`;
@@ -45742,13 +46660,13 @@ function slackChannel(webhookUrl) {
45742
46660
 
45743
46661
  // src/daemon/workers/runs-worker.ts
45744
46662
  var import_promises7 = require("dns/promises");
45745
- var import_node_fs41 = require("fs");
46663
+ var import_node_fs43 = require("fs");
45746
46664
  var import_node_net9 = require("net");
45747
46665
  var import_node_path32 = require("path");
45748
46666
  init_cli_config();
45749
46667
 
45750
46668
  // src/core/cloud-events.ts
45751
- var import_node_crypto10 = require("crypto");
46669
+ var import_node_crypto11 = require("crypto");
45752
46670
  var import_node_net8 = require("net");
45753
46671
  init_cli_config();
45754
46672
  function currentLink() {
@@ -45832,7 +46750,7 @@ function remediationEvent(serverId, event) {
45832
46750
  return {
45833
46751
  type: "remediation",
45834
46752
  server_id: serverId,
45835
- event_id: (0, import_node_crypto10.randomUUID)(),
46753
+ event_id: (0, import_node_crypto11.randomUUID)(),
45836
46754
  action_type: d.action,
45837
46755
  target_value: event.source_ip,
45838
46756
  status: d.failed === true ? "failed" : "executed",
@@ -45895,7 +46813,7 @@ async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0,
45895
46813
  const inside = addresses.find((a) => !isPublicTarget(a));
45896
46814
  return inside ? `${host} resolves to ${inside}, which is not a public address; dashboard runs never reach inside this network` : null;
45897
46815
  }
45898
- function scanTargetError(target, roots, real = import_node_fs41.realpathSync) {
46816
+ function scanTargetError(target, roots, real = import_node_fs43.realpathSync) {
45899
46817
  if (roots.length === 0) {
45900
46818
  return "dashboard scans of this machine are off; list the directories they may read in [cloud] run_scan_paths";
45901
46819
  }
@@ -45998,11 +46916,11 @@ var RunsWorker = class {
45998
46916
  return null;
45999
46917
  }
46000
46918
  }
46001
- async execute(run2) {
46002
- const target = run2.property?.target;
46919
+ async execute(run3) {
46920
+ const target = run3.property?.target;
46003
46921
  if (!target) {
46004
46922
  return {
46005
- type: run2.type,
46923
+ type: run3.type,
46006
46924
  target: "",
46007
46925
  findings: [],
46008
46926
  severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },
@@ -46010,11 +46928,11 @@ var RunsWorker = class {
46010
46928
  error: "property target missing"
46011
46929
  };
46012
46930
  }
46013
- const refused = run2.type === "scan" ? scanTargetError(target, this.opts.scanRoots) : await pentestTargetError(target);
46931
+ const refused = run3.type === "scan" ? scanTargetError(target, this.opts.scanRoots) : await pentestTargetError(target);
46014
46932
  if (refused) {
46015
- this.opts.log?.(`[runs] refused ${run2.type} ${target}: ${refused}`);
46933
+ this.opts.log?.(`[runs] refused ${run3.type} ${target}: ${refused}`);
46016
46934
  return {
46017
- type: run2.type,
46935
+ type: run3.type,
46018
46936
  target,
46019
46937
  findings: [],
46020
46938
  severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },
@@ -46022,13 +46940,13 @@ var RunsWorker = class {
46022
46940
  error: refused
46023
46941
  };
46024
46942
  }
46025
- this.bus.announceModule("runs-worker", "running", `${run2.type} ${run2.property?.name || target}`);
46943
+ this.bus.announceModule("runs-worker", "running", `${run3.type} ${run3.property?.name || target}`);
46026
46944
  try {
46027
- if (run2.type === "scan") return await runScan(target);
46945
+ if (run3.type === "scan") return await runScan(target);
46028
46946
  return await runPentest(target);
46029
46947
  } catch (err) {
46030
46948
  return {
46031
- type: run2.type,
46949
+ type: run3.type,
46032
46950
  target,
46033
46951
  findings: [],
46034
46952
  severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },
@@ -46066,7 +46984,7 @@ var RunsWorker = class {
46066
46984
  init_cli_config();
46067
46985
 
46068
46986
  // src/daemon/workers/cloud-spool.ts
46069
- var import_node_fs42 = require("fs");
46987
+ var import_node_fs44 = require("fs");
46070
46988
  var import_promises8 = require("fs/promises");
46071
46989
  var import_node_path33 = require("path");
46072
46990
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
@@ -46075,7 +46993,7 @@ var CloudSpool = class {
46075
46993
  this.path = path2;
46076
46994
  this.limits = limits;
46077
46995
  try {
46078
- (0, import_node_fs42.mkdirSync)((0, import_node_path33.dirname)(path2), { recursive: true });
46996
+ (0, import_node_fs44.mkdirSync)((0, import_node_path33.dirname)(path2), { recursive: true });
46079
46997
  } catch {
46080
46998
  }
46081
46999
  this.load();
@@ -46144,7 +47062,7 @@ var CloudSpool = class {
46144
47062
  load() {
46145
47063
  let raw;
46146
47064
  try {
46147
- raw = (0, import_node_fs42.readFileSync)(this.path, "utf-8");
47065
+ raw = (0, import_node_fs44.readFileSync)(this.path, "utf-8");
46148
47066
  } catch {
46149
47067
  return;
46150
47068
  }
@@ -46389,7 +47307,7 @@ var CloudSync = class {
46389
47307
  };
46390
47308
 
46391
47309
  // src/daemon/workers/abuse-reporter.ts
46392
- var import_node_crypto11 = require("crypto");
47310
+ var import_node_crypto12 = require("crypto");
46393
47311
 
46394
47312
  // src/daemon/workers/abuse-evidence.ts
46395
47313
  var import_node_net10 = require("net");
@@ -46618,7 +47536,7 @@ function resolveConfig(section) {
46618
47536
  }
46619
47537
 
46620
47538
  // src/core/abuse-report-log.ts
46621
- var import_node_fs43 = require("fs");
47539
+ var import_node_fs45 = require("fs");
46622
47540
  var import_node_path34 = require("path");
46623
47541
  init_paths();
46624
47542
  var ABUSE_DIRNAME = "abuse-reports";
@@ -46627,7 +47545,7 @@ function resolveAbuseDir(dir) {
46627
47545
  if (dir) return dir;
46628
47546
  if (process.env.THREATCRUSH_ABUSE_DIR) return process.env.THREATCRUSH_ABUSE_DIR;
46629
47547
  const system = (0, import_node_path34.join)("/var/lib/threatcrush", ABUSE_DIRNAME);
46630
- if ((0, import_node_fs43.existsSync)(system)) return system;
47548
+ if ((0, import_node_fs45.existsSync)(system)) return system;
46631
47549
  return (0, import_node_path34.join)(PATHS.stateDir, ABUSE_DIRNAME);
46632
47550
  }
46633
47551
  function logPath(dir) {
@@ -46635,15 +47553,15 @@ function logPath(dir) {
46635
47553
  }
46636
47554
  function appendReport(record, dir) {
46637
47555
  const path2 = logPath(dir);
46638
- (0, import_node_fs43.mkdirSync)(resolveAbuseDir(dir), { recursive: true, mode: 493 });
46639
- (0, import_node_fs43.appendFileSync)(path2, `${JSON.stringify(record)}
47556
+ (0, import_node_fs45.mkdirSync)(resolveAbuseDir(dir), { recursive: true, mode: 493 });
47557
+ (0, import_node_fs45.appendFileSync)(path2, `${JSON.stringify(record)}
46640
47558
  `, { mode: 420 });
46641
47559
  }
46642
47560
  function readReports(dir) {
46643
47561
  const path2 = logPath(dir);
46644
47562
  let raw;
46645
47563
  try {
46646
- raw = (0, import_node_fs43.readFileSync)(path2, "utf-8");
47564
+ raw = (0, import_node_fs45.readFileSync)(path2, "utf-8");
46647
47565
  } catch {
46648
47566
  return [];
46649
47567
  }
@@ -46782,7 +47700,7 @@ var AbuseReporter = class {
46782
47700
  const payload = buildPayload(ip, evidence);
46783
47701
  const results = this.cfg.dryRun ? [] : await dispatch(payload, this.cfg.destinations, this.cfg.keys);
46784
47702
  const record = {
46785
- id: (0, import_node_crypto11.randomUUID)().slice(0, 8),
47703
+ id: (0, import_node_crypto12.randomUUID)().slice(0, 8),
46786
47704
  ip,
46787
47705
  reported_at: new Date(now).toISOString(),
46788
47706
  mode: this.cfg.dryRun ? "dry_run" : "live",
@@ -47068,8 +47986,8 @@ var RemediationConsumer = class {
47068
47986
  };
47069
47987
 
47070
47988
  // src/daemon/workers/auto-update.ts
47071
- var import_node_child_process11 = require("child_process");
47072
- var import_node_fs44 = require("fs");
47989
+ var import_node_child_process12 = require("child_process");
47990
+ var import_node_fs46 = require("fs");
47073
47991
  var import_node_path35 = require("path");
47074
47992
  init_backoff();
47075
47993
  var PKG_NAME = "@profullstack/threatcrush";
@@ -47151,10 +48069,10 @@ function installPlan(opts) {
47151
48069
  }
47152
48070
  function ownerOf(path2, passwd = "/etc/passwd") {
47153
48071
  try {
47154
- const st = (0, import_node_fs44.statSync)(path2);
48072
+ const st = (0, import_node_fs46.statSync)(path2);
47155
48073
  let home = st.uid === 0 ? "/root" : "";
47156
48074
  try {
47157
- for (const line2 of (0, import_node_fs44.readFileSync)(passwd, "utf8").split("\n")) {
48075
+ for (const line2 of (0, import_node_fs46.readFileSync)(passwd, "utf8").split("\n")) {
47158
48076
  const f = line2.split(":");
47159
48077
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
47160
48078
  }
@@ -47177,7 +48095,7 @@ function updateSettings(section, env3 = process.env) {
47177
48095
  }
47178
48096
  function defaultRun(argv, env3) {
47179
48097
  return new Promise((resolve9) => {
47180
- const child = (0, import_node_child_process11.spawn)(argv[0], argv.slice(1), {
48098
+ const child = (0, import_node_child_process12.spawn)(argv[0], argv.slice(1), {
47181
48099
  env: { ...process.env, ...env3 },
47182
48100
  stdio: ["ignore", "pipe", "pipe"]
47183
48101
  });
@@ -47264,7 +48182,7 @@ var AutoUpdate = class {
47264
48182
  uid: process.getuid?.() ?? -1,
47265
48183
  owner: ownerOf(this.opts.pkgRoot),
47266
48184
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
47267
- npmExists: import_node_fs44.existsSync
48185
+ npmExists: import_node_fs46.existsSync
47268
48186
  });
47269
48187
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
47270
48188
  this.recordAttempt(target);
@@ -47300,7 +48218,7 @@ var AutoUpdate = class {
47300
48218
  }
47301
48219
  lastAttempt() {
47302
48220
  try {
47303
- const v = JSON.parse((0, import_node_fs44.readFileSync)(this.opts.statePath, "utf8"));
48221
+ const v = JSON.parse((0, import_node_fs46.readFileSync)(this.opts.statePath, "utf8"));
47304
48222
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
47305
48223
  } catch {
47306
48224
  return null;
@@ -47308,7 +48226,7 @@ var AutoUpdate = class {
47308
48226
  }
47309
48227
  recordAttempt(version) {
47310
48228
  try {
47311
- (0, import_node_fs44.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
48229
+ (0, import_node_fs46.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
47312
48230
  } catch (err) {
47313
48231
  this.opts.log(`[update] could not record attempt: ${err.message}`);
47314
48232
  }
@@ -47316,8 +48234,8 @@ var AutoUpdate = class {
47316
48234
  };
47317
48235
 
47318
48236
  // src/daemon/workers/threat-feeds.ts
47319
- var import_node_child_process12 = require("child_process");
47320
- var import_node_fs45 = require("fs");
48237
+ var import_node_child_process13 = require("child_process");
48238
+ var import_node_fs47 = require("fs");
47321
48239
  var import_node_path36 = require("path");
47322
48240
  var import_node_net13 = require("net");
47323
48241
  init_backoff();
@@ -47396,7 +48314,7 @@ function parseListeningPorts(text) {
47396
48314
  return ports;
47397
48315
  }
47398
48316
  function defaultRun2(cmd, args, input) {
47399
- const res = (0, import_node_child_process12.spawnSync)(cmd, args, { encoding: "utf-8", input, timeout: 15e3, stdio: ["pipe", "pipe", "pipe"] });
48317
+ const res = (0, import_node_child_process13.spawnSync)(cmd, args, { encoding: "utf-8", input, timeout: 15e3, stdio: ["pipe", "pipe", "pipe"] });
47400
48318
  return res.status === 0 ? res.stdout : null;
47401
48319
  }
47402
48320
  var ThreatFeeds = class {
@@ -47496,8 +48414,8 @@ var ThreatFeeds = class {
47496
48414
  const path2 = (0, import_node_path36.join)(dir, name);
47497
48415
  if (this.resolverWritten.get(name) === content) return false;
47498
48416
  try {
47499
- (0, import_node_fs45.writeFileSync)(`${path2}.tmp`, content);
47500
- (0, import_node_fs45.renameSync)(`${path2}.tmp`, path2);
48417
+ (0, import_node_fs47.writeFileSync)(`${path2}.tmp`, content);
48418
+ (0, import_node_fs47.renameSync)(`${path2}.tmp`, path2);
47501
48419
  this.resolverWritten.set(name, content);
47502
48420
  return true;
47503
48421
  } catch (err) {
@@ -47508,11 +48426,11 @@ var ThreatFeeds = class {
47508
48426
  const hostsChanged = write(RESOLVER_FILES.hosts, hostsBlocklist(domains));
47509
48427
  const unboundChanged = write(RESOLVER_FILES.unbound, unboundBlocklist(domains));
47510
48428
  const via = [];
47511
- if ((0, import_node_fs45.existsSync)(hooks.dnsmasq)) {
48429
+ if ((0, import_node_fs47.existsSync)(hooks.dnsmasq)) {
47512
48430
  via.push("dnsmasq");
47513
48431
  if (hostsChanged) this.run("systemctl", ["kill", "-s", "HUP", "dnsmasq.service"]);
47514
48432
  }
47515
- if ((0, import_node_fs45.existsSync)(hooks.unbound)) {
48433
+ if ((0, import_node_fs47.existsSync)(hooks.unbound)) {
47516
48434
  via.push("unbound");
47517
48435
  if (unboundChanged && this.run("unbound-control", ["reload"]) === null) {
47518
48436
  this.run("systemctl", ["reload", "unbound.service"]);
@@ -47573,12 +48491,12 @@ var ThreatFeeds = class {
47573
48491
  };
47574
48492
 
47575
48493
  // src/daemon/workers/privilege-watch.ts
47576
- var import_node_fs46 = require("fs");
48494
+ var import_node_fs48 = require("fs");
47577
48495
  var import_node_path37 = require("path");
47578
- var import_node_child_process13 = require("child_process");
48496
+ var import_node_child_process14 = require("child_process");
47579
48497
 
47580
48498
  // src/core/privileges/index.ts
47581
- var import_node_crypto12 = require("crypto");
48499
+ var import_node_crypto13 = require("crypto");
47582
48500
  var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
47583
48501
  function parseUsers(text) {
47584
48502
  const out = [];
@@ -47617,35 +48535,35 @@ function sudoersRules(text) {
47617
48535
  function sudoReadsIncluded(name) {
47618
48536
  return !name.endsWith("~") && !name.includes(".");
47619
48537
  }
47620
- function keyFingerprint(blobBase64) {
48538
+ function keyFingerprint2(blobBase64) {
47621
48539
  if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
47622
- const digest = (0, import_node_crypto12.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
48540
+ const digest = (0, import_node_crypto13.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
47623
48541
  return `SHA256:${digest.replace(/=+$/, "")}`;
47624
48542
  }
47625
- function parseAuthorizedKeys(text) {
48543
+ function parseAuthorizedKeys2(text) {
47626
48544
  const out = [];
47627
48545
  for (const raw of text.split("\n")) {
47628
48546
  const line2 = raw.trim();
47629
48547
  if (!line2 || line2.startsWith("#")) continue;
47630
48548
  const m = /(?:^|\s)((?:ssh|ecdsa|sk)-[\w@.-]+)\s+([A-Za-z0-9+/]+=*)(?:\s+(.*))?$/.exec(line2);
47631
48549
  if (!m) continue;
47632
- const fingerprint = keyFingerprint(m[2]);
48550
+ const fingerprint = keyFingerprint2(m[2]);
47633
48551
  if (fingerprint) out.push({ fingerprint, type: m[1], comment: (m[3] ?? "").trim() });
47634
48552
  }
47635
48553
  return out;
47636
48554
  }
47637
48555
  function takeSnapshot(io, now = /* @__PURE__ */ new Date()) {
47638
48556
  const unreadable = [];
47639
- const read = (path2) => {
48557
+ const read2 = (path2) => {
47640
48558
  const text = io.readFile(path2);
47641
48559
  if (text === null && io.exists(path2)) unreadable.push(path2);
47642
48560
  return text;
47643
48561
  };
47644
- const users = parseUsers(read("/etc/passwd") ?? "");
48562
+ const users = parseUsers(read2("/etc/passwd") ?? "");
47645
48563
  const snapshot = {
47646
48564
  taken_at: now.toISOString(),
47647
48565
  uid0: users.filter((a) => a.uid === 0).map((a) => a.name).sort(),
47648
- admin_groups: parseAdminGroups(read("/etc/group") ?? ""),
48566
+ admin_groups: parseAdminGroups(read2("/etc/group") ?? ""),
47649
48567
  sudoers: {},
47650
48568
  keys: {},
47651
48569
  unreadable
@@ -47655,15 +48573,15 @@ function takeSnapshot(io, now = /* @__PURE__ */ new Date()) {
47655
48573
  if (sudoReadsIncluded(name)) sudoersFiles.push(`/etc/sudoers.d/${name}`);
47656
48574
  }
47657
48575
  for (const path2 of sudoersFiles) {
47658
- const text = read(path2);
48576
+ const text = read2(path2);
47659
48577
  if (text !== null) snapshot.sudoers[path2] = sudoersRules(text);
47660
48578
  }
47661
48579
  for (const user of users) {
47662
48580
  if (user.uid !== 0 && (!canLogIn(user) || !user.home || user.home === "/")) continue;
47663
48581
  const keys = {};
47664
48582
  for (const file of ["authorized_keys", "authorized_keys2"]) {
47665
- const text = read(`${user.home.replace(/\/$/, "")}/.ssh/${file}`);
47666
- for (const k of parseAuthorizedKeys(text ?? "")) keys[k.fingerprint] = { type: k.type, comment: k.comment };
48583
+ const text = read2(`${user.home.replace(/\/$/, "")}/.ssh/${file}`);
48584
+ for (const k of parseAuthorizedKeys2(text ?? "")) keys[k.fingerprint] = { type: k.type, comment: k.comment };
47667
48585
  }
47668
48586
  if (Object.keys(keys).length > 0) snapshot.keys[user.name] = keys;
47669
48587
  }
@@ -47800,34 +48718,34 @@ function countryName(code) {
47800
48718
  var fsIO = {
47801
48719
  readFile: (p) => {
47802
48720
  try {
47803
- return (0, import_node_fs46.readFileSync)(p, "utf-8");
48721
+ return (0, import_node_fs48.readFileSync)(p, "utf-8");
47804
48722
  } catch {
47805
48723
  return null;
47806
48724
  }
47807
48725
  },
47808
48726
  readDir: (p) => {
47809
48727
  try {
47810
- return (0, import_node_fs46.readdirSync)(p);
48728
+ return (0, import_node_fs48.readdirSync)(p);
47811
48729
  } catch {
47812
48730
  return null;
47813
48731
  }
47814
48732
  },
47815
- exists: (p) => (0, import_node_fs46.existsSync)(p)
48733
+ exists: (p) => (0, import_node_fs48.existsSync)(p)
47816
48734
  };
47817
48735
  function readJson(path2) {
47818
48736
  try {
47819
- return JSON.parse((0, import_node_fs46.readFileSync)(path2, "utf-8"));
48737
+ return JSON.parse((0, import_node_fs48.readFileSync)(path2, "utf-8"));
47820
48738
  } catch {
47821
48739
  return null;
47822
48740
  }
47823
48741
  }
47824
48742
  function writeJson(path2, value) {
47825
- (0, import_node_fs46.mkdirSync)((0, import_node_path37.dirname)(path2), { recursive: true });
47826
- (0, import_node_fs46.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
47827
- (0, import_node_fs46.renameSync)(`${path2}.tmp`, path2);
48743
+ (0, import_node_fs48.mkdirSync)((0, import_node_path37.dirname)(path2), { recursive: true });
48744
+ (0, import_node_fs48.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
48745
+ (0, import_node_fs48.renameSync)(`${path2}.tmp`, path2);
47828
48746
  }
47829
48747
  function defaultRun3(cmd, args) {
47830
- const res = (0, import_node_child_process13.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
48748
+ const res = (0, import_node_child_process14.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
47831
48749
  return res.status === 0 ? res.stdout : null;
47832
48750
  }
47833
48751
  async function geolocateViaThreatcrush(ip, fetchImpl = fetch) {
@@ -47941,7 +48859,7 @@ var PrivilegeWatch = class {
47941
48859
  for (const dir of dirs) {
47942
48860
  if (this.watchers.has(dir) || !this.io.exists(dir)) continue;
47943
48861
  try {
47944
- const w = (0, import_node_fs46.watch)(dir, { persistent: false }, (_type2, name) => {
48862
+ const w = (0, import_node_fs48.watch)(dir, { persistent: false }, (_type2, name) => {
47945
48863
  if (name && !String(name).startsWith("authorized_keys")) return;
47946
48864
  if (this.debounce) clearTimeout(this.debounce);
47947
48865
  this.debounce = setTimeout(() => {
@@ -48040,7 +48958,7 @@ var PrivilegeWatch = class {
48040
48958
  * raised a "new country" alert on its first run; on dev2 it did, at once.
48041
48959
  */
48042
48960
  async backfillLogins() {
48043
- if ((0, import_node_fs46.existsSync)(this.opts.loginsPath)) return;
48961
+ if ((0, import_node_fs48.existsSync)(this.opts.loginsPath)) return;
48044
48962
  const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "cat", "--no-pager"]);
48045
48963
  const byUser = parseAcceptedLogins(out ?? "");
48046
48964
  const ips = [...new Set([...byUser.values()].flatMap((s) => [...s]))];
@@ -48053,7 +48971,7 @@ var PrivilegeWatch = class {
48053
48971
  return;
48054
48972
  }
48055
48973
  }
48056
- if ((0, import_node_fs46.existsSync)(this.opts.loginsPath)) return;
48974
+ if ((0, import_node_fs48.existsSync)(this.opts.loginsPath)) return;
48057
48975
  const at = this.now().toISOString();
48058
48976
  const history = {};
48059
48977
  for (const [user, userIps] of byUser) {
@@ -48105,11 +49023,11 @@ var PrivilegeWatch = class {
48105
49023
  };
48106
49024
 
48107
49025
  // src/daemon/workers/command-history.ts
48108
- var import_node_fs47 = require("fs");
48109
- var import_node_child_process14 = require("child_process");
49026
+ var import_node_fs49 = require("fs");
49027
+ var import_node_child_process15 = require("child_process");
48110
49028
  var import_node_path38 = require("path");
48111
49029
  var import_node_zlib2 = require("zlib");
48112
- var import_node_crypto13 = require("crypto");
49030
+ var import_node_crypto14 = require("crypto");
48113
49031
  var POLL_MS3 = 6e4;
48114
49032
  var MAX_HISTORY_BYTES = 4 * 1024 * 1024;
48115
49033
  var MAX_COMPRESSED_HISTORY_BYTES = MAX_HISTORY_BYTES + 65536;
@@ -48127,10 +49045,10 @@ function commandHistorySettings(section) {
48127
49045
  function historyAccounts() {
48128
49046
  let passwd;
48129
49047
  try {
48130
- passwd = (0, import_node_child_process14.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
49048
+ passwd = (0, import_node_child_process15.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
48131
49049
  } catch {
48132
49050
  try {
48133
- passwd = (0, import_node_fs47.readFileSync)("/etc/passwd", "utf8");
49051
+ passwd = (0, import_node_fs49.readFileSync)("/etc/passwd", "utf8");
48134
49052
  } catch {
48135
49053
  return [];
48136
49054
  }
@@ -48157,17 +49075,17 @@ function descriptorPath(directoryFd, name) {
48157
49075
  }
48158
49076
  function openDirectoryChain(path2) {
48159
49077
  if (!(0, import_node_path38.isAbsolute)(path2) || path2.split(import_node_path38.sep).includes("..")) throw new Error("directory path is not a safe absolute path");
48160
- const flags = import_node_fs47.constants.O_RDONLY | import_node_fs47.constants.O_DIRECTORY | (import_node_fs47.constants.O_NOFOLLOW ?? 0);
48161
- let fd = (0, import_node_fs47.openSync)("/", flags);
49078
+ const flags = import_node_fs49.constants.O_RDONLY | import_node_fs49.constants.O_DIRECTORY | (import_node_fs49.constants.O_NOFOLLOW ?? 0);
49079
+ let fd = (0, import_node_fs49.openSync)("/", flags);
48162
49080
  try {
48163
49081
  for (const part of path2.split(import_node_path38.sep).filter((item) => item && item !== ".")) {
48164
- const next = (0, import_node_fs47.openSync)(descriptorPath(fd, part), flags);
48165
- (0, import_node_fs47.closeSync)(fd);
49082
+ const next = (0, import_node_fs49.openSync)(descriptorPath(fd, part), flags);
49083
+ (0, import_node_fs49.closeSync)(fd);
48166
49084
  fd = next;
48167
49085
  }
48168
49086
  return fd;
48169
49087
  } catch (error2) {
48170
- (0, import_node_fs47.closeSync)(fd);
49088
+ (0, import_node_fs49.closeSync)(fd);
48171
49089
  throw error2;
48172
49090
  }
48173
49091
  }
@@ -48175,68 +49093,68 @@ function readExact(fd, size) {
48175
49093
  const data = Buffer.alloc(size);
48176
49094
  let offset = 0;
48177
49095
  while (offset < data.length) {
48178
- const read = (0, import_node_fs47.readSync)(fd, data, offset, data.length - offset, offset);
48179
- if (read === 0) break;
48180
- offset += read;
49096
+ const read2 = (0, import_node_fs49.readSync)(fd, data, offset, data.length - offset, offset);
49097
+ if (read2 === 0) break;
49098
+ offset += read2;
48181
49099
  }
48182
49100
  return offset === data.length ? data : null;
48183
49101
  }
48184
49102
  function privateDirectory(path2) {
48185
- (0, import_node_fs47.mkdirSync)(path2, { recursive: true, mode: 448 });
48186
- const stat = (0, import_node_fs47.lstatSync)(path2);
49103
+ (0, import_node_fs49.mkdirSync)(path2, { recursive: true, mode: 448 });
49104
+ const stat = (0, import_node_fs49.lstatSync)(path2);
48187
49105
  if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("history storage path is not a directory");
48188
- (0, import_node_fs47.chmodSync)(path2, 448);
49106
+ (0, import_node_fs49.chmodSync)(path2, 448);
48189
49107
  }
48190
49108
  function safeReadHistory(directoryFd, name, uid) {
48191
- const noFollow = import_node_fs47.constants.O_NOFOLLOW ?? 0;
48192
- const fd = (0, import_node_fs47.openSync)(descriptorPath(directoryFd, name), import_node_fs47.constants.O_RDONLY | noFollow);
49109
+ const noFollow = import_node_fs49.constants.O_NOFOLLOW ?? 0;
49110
+ const fd = (0, import_node_fs49.openSync)(descriptorPath(directoryFd, name), import_node_fs49.constants.O_RDONLY | noFollow);
48193
49111
  try {
48194
- const opened = (0, import_node_fs47.fstatSync)(fd);
49112
+ const opened = (0, import_node_fs49.fstatSync)(fd);
48195
49113
  if (!opened.isFile() || opened.nlink !== 1 || opened.uid !== uid) return null;
48196
49114
  if (opened.size > MAX_HISTORY_BYTES) throw new Error(`history file exceeds ${MAX_HISTORY_BYTES} bytes`);
48197
49115
  const data = readExact(fd, opened.size);
48198
49116
  if (data === null) return null;
48199
- const after = (0, import_node_fs47.fstatSync)(fd);
49117
+ const after = (0, import_node_fs49.fstatSync)(fd);
48200
49118
  if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs) return null;
48201
49119
  return data;
48202
49120
  } finally {
48203
- (0, import_node_fs47.closeSync)(fd);
49121
+ (0, import_node_fs49.closeSync)(fd);
48204
49122
  }
48205
49123
  }
48206
49124
  function atomicWrite(path2, data, mode = 384, owner, parentFd) {
48207
49125
  const dirFd = parentFd ?? openDirectoryChain((0, import_node_path38.dirname)(path2));
48208
49126
  const ownsDirFd = parentFd === void 0;
48209
49127
  const name = (0, import_node_path38.basename)(path2);
48210
- const temp = descriptorPath(dirFd, `${name}.${(0, import_node_crypto13.randomUUID)()}.tmp`);
49128
+ const temp = descriptorPath(dirFd, `${name}.${(0, import_node_crypto14.randomUUID)()}.tmp`);
48211
49129
  const destination = descriptorPath(dirFd, name);
48212
- const noFollow = import_node_fs47.constants.O_NOFOLLOW ?? 0;
49130
+ const noFollow = import_node_fs49.constants.O_NOFOLLOW ?? 0;
48213
49131
  let fd;
48214
49132
  try {
48215
- fd = (0, import_node_fs47.openSync)(temp, import_node_fs47.constants.O_WRONLY | import_node_fs47.constants.O_CREAT | import_node_fs47.constants.O_EXCL | noFollow, mode);
49133
+ fd = (0, import_node_fs49.openSync)(temp, import_node_fs49.constants.O_WRONLY | import_node_fs49.constants.O_CREAT | import_node_fs49.constants.O_EXCL | noFollow, mode);
48216
49134
  let offset = 0;
48217
- while (offset < data.length) offset += (0, import_node_fs47.writeSync)(fd, data, offset, data.length - offset);
48218
- (0, import_node_fs47.fchmodSync)(fd, mode);
49135
+ while (offset < data.length) offset += (0, import_node_fs49.writeSync)(fd, data, offset, data.length - offset);
49136
+ (0, import_node_fs49.fchmodSync)(fd, mode);
48219
49137
  if (owner && typeof process.getuid === "function" && process.getuid() === 0) {
48220
- (0, import_node_fs47.fchownSync)(fd, owner.uid, owner.gid);
49138
+ (0, import_node_fs49.fchownSync)(fd, owner.uid, owner.gid);
48221
49139
  }
48222
- (0, import_node_fs47.fsyncSync)(fd);
48223
- (0, import_node_fs47.closeSync)(fd);
49140
+ (0, import_node_fs49.fsyncSync)(fd);
49141
+ (0, import_node_fs49.closeSync)(fd);
48224
49142
  fd = void 0;
48225
- (0, import_node_fs47.renameSync)(temp, destination);
49143
+ (0, import_node_fs49.renameSync)(temp, destination);
48226
49144
  } catch (error2) {
48227
49145
  if (fd !== void 0) {
48228
49146
  try {
48229
- (0, import_node_fs47.closeSync)(fd);
49147
+ (0, import_node_fs49.closeSync)(fd);
48230
49148
  } catch {
48231
49149
  }
48232
49150
  }
48233
49151
  try {
48234
- (0, import_node_fs47.unlinkSync)(temp);
49152
+ (0, import_node_fs49.unlinkSync)(temp);
48235
49153
  } catch {
48236
49154
  }
48237
49155
  throw error2;
48238
49156
  } finally {
48239
- if (ownsDirFd) (0, import_node_fs47.closeSync)(dirFd);
49157
+ if (ownsDirFd) (0, import_node_fs49.closeSync)(dirFd);
48240
49158
  }
48241
49159
  }
48242
49160
  function readCurrentBackup(path2) {
@@ -48244,20 +49162,20 @@ function readCurrentBackup(path2) {
48244
49162
  try {
48245
49163
  const parentFd = openDirectoryChain((0, import_node_path38.dirname)(path2));
48246
49164
  try {
48247
- fd = (0, import_node_fs47.openSync)(descriptorPath(parentFd, (0, import_node_path38.basename)(path2)), import_node_fs47.constants.O_RDONLY | (import_node_fs47.constants.O_NOFOLLOW ?? 0));
49165
+ fd = (0, import_node_fs49.openSync)(descriptorPath(parentFd, (0, import_node_path38.basename)(path2)), import_node_fs49.constants.O_RDONLY | (import_node_fs49.constants.O_NOFOLLOW ?? 0));
48248
49166
  } finally {
48249
- (0, import_node_fs47.closeSync)(parentFd);
49167
+ (0, import_node_fs49.closeSync)(parentFd);
48250
49168
  }
48251
- const stat = (0, import_node_fs47.fstatSync)(fd);
49169
+ const stat = (0, import_node_fs49.fstatSync)(fd);
48252
49170
  if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_COMPRESSED_HISTORY_BYTES) return null;
48253
49171
  const compressed = readExact(fd, stat.size);
48254
- const after = (0, import_node_fs47.fstatSync)(fd);
49172
+ const after = (0, import_node_fs49.fstatSync)(fd);
48255
49173
  if (!compressed || after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) return null;
48256
49174
  return (0, import_node_zlib2.gunzipSync)(compressed, { maxOutputLength: MAX_HISTORY_BYTES });
48257
49175
  } catch {
48258
49176
  return null;
48259
49177
  } finally {
48260
- if (fd !== void 0) (0, import_node_fs47.closeSync)(fd);
49178
+ if (fd !== void 0) (0, import_node_fs49.closeSync)(fd);
48261
49179
  }
48262
49180
  }
48263
49181
  function compactTime(date) {
@@ -48326,7 +49244,7 @@ var CommandHistoryWatcher = class {
48326
49244
  if (targets.has(relative4)) continue;
48327
49245
  const path2 = (0, import_node_path38.join)(account.home, relative4);
48328
49246
  try {
48329
- (0, import_node_fs47.lstatSync)(path2);
49247
+ (0, import_node_fs49.lstatSync)(path2);
48330
49248
  targets.add(relative4);
48331
49249
  continue;
48332
49250
  } catch (error2) {
@@ -48353,7 +49271,7 @@ var CommandHistoryWatcher = class {
48353
49271
  const userPath = descriptorPath(userParentFd, (0, import_node_path38.basename)(path2));
48354
49272
  let status;
48355
49273
  try {
48356
- status = (0, import_node_fs47.lstatSync)(userPath);
49274
+ status = (0, import_node_fs49.lstatSync)(userPath);
48357
49275
  } catch (error2) {
48358
49276
  if (error2.code !== "ENOENT") throw error2;
48359
49277
  }
@@ -48377,13 +49295,13 @@ var CommandHistoryWatcher = class {
48377
49295
  }
48378
49296
  const compressed = (0, import_node_zlib2.gzipSync)(data, { level: 6 });
48379
49297
  const stamp = compactTime(this.now());
48380
- atomicWrite(`${store}.${stamp}-${(0, import_node_crypto13.randomUUID)().slice(0, 8)}.gz`, compressed);
49298
+ atomicWrite(`${store}.${stamp}-${(0, import_node_crypto14.randomUUID)().slice(0, 8)}.gz`, compressed);
48381
49299
  atomicWrite(current, compressed);
48382
49300
  this.pruneSnapshots(store);
48383
49301
  } catch (error2) {
48384
49302
  this.opts.log(`[command-history] could not snapshot uid=${account.uid} ${(0, import_node_path38.basename)(relative4)}: ${error2.message}`);
48385
49303
  } finally {
48386
- (0, import_node_fs47.closeSync)(userParentFd);
49304
+ (0, import_node_fs49.closeSync)(userParentFd);
48387
49305
  }
48388
49306
  }
48389
49307
  restore(path2, content, account, parentFd) {
@@ -48405,13 +49323,13 @@ var CommandHistoryWatcher = class {
48405
49323
  pruneSnapshots(current) {
48406
49324
  const dir = (0, import_node_path38.dirname)(current);
48407
49325
  const prefix = `${(0, import_node_path38.basename)(current).replace(/\.current\.gz$/, "")}.`;
48408
- const snapshots = (0, import_node_fs47.readdirSync)(dir).filter((name) => name !== (0, import_node_path38.basename)(current) && name.startsWith(prefix) && name.endsWith(".gz")).map((name) => ({ path: (0, import_node_path38.join)(dir, name), name, time: (0, import_node_fs47.lstatSync)((0, import_node_path38.join)(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time);
49326
+ const snapshots = (0, import_node_fs49.readdirSync)(dir).filter((name) => name !== (0, import_node_path38.basename)(current) && name.startsWith(prefix) && name.endsWith(".gz")).map((name) => ({ path: (0, import_node_path38.join)(dir, name), name, time: (0, import_node_fs49.lstatSync)((0, import_node_path38.join)(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time);
48409
49327
  const cutoff = this.now().getTime() - SNAPSHOT_RETENTION_MS;
48410
49328
  const removeCount = Math.max(0, snapshots.length - MAX_SNAPSHOTS);
48411
49329
  snapshots.forEach((snapshot, index) => {
48412
49330
  if (snapshot.time < cutoff || index < removeCount) {
48413
49331
  try {
48414
- (0, import_node_fs47.unlinkSync)(snapshot.path);
49332
+ (0, import_node_fs49.unlinkSync)(snapshot.path);
48415
49333
  } catch {
48416
49334
  }
48417
49335
  }
@@ -48420,9 +49338,9 @@ var CommandHistoryWatcher = class {
48420
49338
  };
48421
49339
 
48422
49340
  // src/daemon/workers/file-integrity.ts
48423
- var import_node_fs48 = require("fs");
49341
+ var import_node_fs50 = require("fs");
48424
49342
  var import_promises9 = require("fs/promises");
48425
- var import_node_crypto14 = require("crypto");
49343
+ var import_node_crypto15 = require("crypto");
48426
49344
  var import_node_path39 = require("path");
48427
49345
  var DEFAULT_POLL_MS = 15 * 6e4;
48428
49346
  var MAX_FILES = 5e4;
@@ -48469,12 +49387,12 @@ async function readState(path2) {
48469
49387
  }
48470
49388
  async function writeState(path2, state) {
48471
49389
  await (0, import_promises9.mkdir)((0, import_node_path39.dirname)(path2), { recursive: true, mode: 448 });
48472
- const temp = `${path2}.${process.pid}.${(0, import_node_crypto14.randomUUID)()}.tmp`;
49390
+ const temp = `${path2}.${process.pid}.${(0, import_node_crypto15.randomUUID)()}.tmp`;
48473
49391
  await (0, import_promises9.writeFile)(temp, JSON.stringify(state), { mode: 384 });
48474
49392
  await (0, import_promises9.rename)(temp, path2);
48475
49393
  }
48476
49394
  async function hashFile(path2, handle, size) {
48477
- const hash = (0, import_node_crypto14.createHash)("sha256");
49395
+ const hash = (0, import_node_crypto15.createHash)("sha256");
48478
49396
  const buffer = Buffer.alloc(READ_CHUNK_BYTES);
48479
49397
  const counts = new Uint32Array(256);
48480
49398
  let position = 0;
@@ -48568,7 +49486,7 @@ async function scanTargets(targets, canaries) {
48568
49486
  let complete = true;
48569
49487
  let skipped = 0;
48570
49488
  let bytes = 0;
48571
- const walk = async (path2, parent) => {
49489
+ const walk2 = async (path2, parent) => {
48572
49490
  if (visited.has(path2) || !complete) return;
48573
49491
  visited.add(path2);
48574
49492
  if (visited.size > MAX_FILES) {
@@ -48596,7 +49514,7 @@ async function scanTargets(targets, canaries) {
48596
49514
  return;
48597
49515
  }
48598
49516
  for (const entry of entries) {
48599
- await walk((0, import_node_path39.join)(path2, entry.name), handle);
49517
+ await walk2((0, import_node_path39.join)(path2, entry.name), handle);
48600
49518
  if (!complete) return;
48601
49519
  }
48602
49520
  return;
@@ -48640,7 +49558,7 @@ async function scanTargets(targets, canaries) {
48640
49558
  }
48641
49559
  };
48642
49560
  for (const target of targets) {
48643
- await walk(target);
49561
+ await walk2(target);
48644
49562
  if (!complete) break;
48645
49563
  }
48646
49564
  return { files, directories, complete, skipped, bytes, errorPaths: [...errors].slice(0, 20) };
@@ -48734,7 +49652,7 @@ var FileIntegrityWatch = class {
48734
49652
  for (const path2 of wanted) {
48735
49653
  if (this.watchers.has(path2)) continue;
48736
49654
  try {
48737
- const watcher = (0, import_node_fs48.watch)(path2, { persistent: false }, () => {
49655
+ const watcher = (0, import_node_fs50.watch)(path2, { persistent: false }, () => {
48738
49656
  this.scheduleEventScan();
48739
49657
  });
48740
49658
  watcher.on("error", (error2) => {
@@ -48915,9 +49833,9 @@ var FileIntegrityWatch = class {
48915
49833
  };
48916
49834
 
48917
49835
  // src/daemon/workers/edr.ts
48918
- var import_node_fs49 = require("fs");
49836
+ var import_node_fs51 = require("fs");
48919
49837
  var import_node_path40 = require("path");
48920
- var import_node_child_process15 = require("child_process");
49838
+ var import_node_child_process16 = require("child_process");
48921
49839
  var DEFAULT_AUDIT_LOG = "/var/log/audit/audit.log";
48922
49840
  var DEFAULT_WEB_USERS = ["www-data", "nginx", "apache", "httpd", "caddy", "node"];
48923
49841
  var DEFAULT_TEMP_PATHS = ["/tmp", "/var/tmp", "/dev/shm"];
@@ -48990,10 +49908,10 @@ function parseAuditRecord(line2) {
48990
49908
  function accountNames2() {
48991
49909
  let raw = "";
48992
49910
  try {
48993
- raw = (0, import_node_child_process15.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
49911
+ raw = (0, import_node_child_process16.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
48994
49912
  } catch {
48995
49913
  try {
48996
- raw = (0, import_node_fs49.readFileSync)("/etc/passwd", "utf8");
49914
+ raw = (0, import_node_fs51.readFileSync)("/etc/passwd", "utf8");
48997
49915
  } catch {
48998
49916
  return /* @__PURE__ */ new Map();
48999
49917
  }
@@ -49011,7 +49929,7 @@ function pathWithin(path2, root) {
49011
49929
  }
49012
49930
  function executableInWorldWritableDirectory(executable) {
49013
49931
  try {
49014
- return ((0, import_node_fs49.statSync)((0, import_node_path40.dirname)(executable)).mode & 2) !== 0;
49932
+ return ((0, import_node_fs51.statSync)((0, import_node_path40.dirname)(executable)).mode & 2) !== 0;
49015
49933
  } catch {
49016
49934
  return false;
49017
49935
  }
@@ -49045,11 +49963,11 @@ var EdrWatch = class {
49045
49963
  this.opts.log("[edr] disabled; set [edr] enabled = true after installing the generated audit rules");
49046
49964
  return;
49047
49965
  }
49048
- if (!(0, import_node_fs49.existsSync)(this.opts.settings.auditLogPath)) {
49966
+ if (!(0, import_node_fs51.existsSync)(this.opts.settings.auditLogPath)) {
49049
49967
  this.opts.log(`[edr] audit log not found at ${this.opts.settings.auditLogPath}; auditd detections are unavailable`);
49050
49968
  } else {
49051
49969
  try {
49052
- (0, import_node_fs49.accessSync)(this.opts.settings.auditLogPath, import_node_fs49.constants.R_OK);
49970
+ (0, import_node_fs51.accessSync)(this.opts.settings.auditLogPath, import_node_fs51.constants.R_OK);
49053
49971
  this.tail = new LogTail(this.opts.settings.auditLogPath);
49054
49972
  this.timer = setInterval(() => this.poll(), this.opts.settings.pollMs);
49055
49973
  this.timer.unref?.();
@@ -49160,7 +50078,7 @@ var EdrWatch = class {
49160
50078
  const path2 = this.opts.networkBaselinePath;
49161
50079
  if (!path2) return;
49162
50080
  try {
49163
- const parsed = JSON.parse((0, import_node_fs49.readFileSync)(path2, "utf8"));
50081
+ const parsed = JSON.parse((0, import_node_fs51.readFileSync)(path2, "utf8"));
49164
50082
  if (Array.isArray(parsed)) {
49165
50083
  for (const value of parsed.slice(0, 1e4)) {
49166
50084
  if (typeof value === "string" && value.startsWith("/")) this.outboundExecutables.add(value);
@@ -49177,9 +50095,9 @@ var EdrWatch = class {
49177
50095
  if (!path2) return;
49178
50096
  try {
49179
50097
  const temp = `${path2}.${process.pid}.tmp`;
49180
- (0, import_node_fs49.writeFileSync)(temp, `${JSON.stringify([...this.outboundExecutables])}
50098
+ (0, import_node_fs51.writeFileSync)(temp, `${JSON.stringify([...this.outboundExecutables])}
49181
50099
  `, { mode: 384 });
49182
- (0, import_node_fs49.renameSync)(temp, path2);
50100
+ (0, import_node_fs51.renameSync)(temp, path2);
49183
50101
  this.baselineWriteFailed = false;
49184
50102
  } catch (error2) {
49185
50103
  if (!this.baselineWriteFailed) this.opts.log(`[edr] could not persist outbound executable baseline: ${error2.message.split("\n")[0]}`);
@@ -49188,7 +50106,7 @@ var EdrWatch = class {
49188
50106
  }
49189
50107
  readTicksPerSecond() {
49190
50108
  try {
49191
- const value = Number((0, import_node_child_process15.execFileSync)("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }).trim());
50109
+ const value = Number((0, import_node_child_process16.execFileSync)("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }).trim());
49192
50110
  if (Number.isFinite(value) && value > 0) return value;
49193
50111
  } catch {
49194
50112
  }
@@ -49200,7 +50118,7 @@ var EdrWatch = class {
49200
50118
  const current = /* @__PURE__ */ new Map();
49201
50119
  let pids;
49202
50120
  try {
49203
- pids = (0, import_node_fs49.readdirSync)("/proc");
50121
+ pids = (0, import_node_fs51.readdirSync)("/proc");
49204
50122
  } catch {
49205
50123
  return;
49206
50124
  }
@@ -49208,7 +50126,7 @@ var EdrWatch = class {
49208
50126
  if (!/^\d+$/.test(pid)) continue;
49209
50127
  const proc = `/proc/${pid}`;
49210
50128
  try {
49211
- const raw = (0, import_node_fs49.readFileSync)(`${proc}/stat`, "utf8");
50129
+ const raw = (0, import_node_fs51.readFileSync)(`${proc}/stat`, "utf8");
49212
50130
  const end = raw.lastIndexOf(")");
49213
50131
  if (end < 0) continue;
49214
50132
  const fields = raw.slice(end + 1).trim().split(/\s+/);
@@ -49216,7 +50134,7 @@ var EdrWatch = class {
49216
50134
  const systemTicks = Number(fields[12]);
49217
50135
  const startTicks = fields[19];
49218
50136
  if (!Number.isFinite(userTicks) || !Number.isFinite(systemTicks) || !startTicks) continue;
49219
- let executable = (0, import_node_fs49.readlinkSync)(`${proc}/exe`);
50137
+ let executable = (0, import_node_fs51.readlinkSync)(`${proc}/exe`);
49220
50138
  executable = executable.replace(/ \(deleted\)$/, "");
49221
50139
  if (!this.opts.settings.tempExecPaths.some((path2) => pathWithin(executable, path2))) continue;
49222
50140
  const name = (0, import_node_path40.basename)(executable).toLowerCase();
@@ -49255,9 +50173,9 @@ var EdrWatch = class {
49255
50173
  };
49256
50174
 
49257
50175
  // src/daemon/workers/ssh-intrusion.ts
49258
- var import_node_fs50 = require("fs");
50176
+ var import_node_fs52 = require("fs");
49259
50177
  var import_node_path41 = require("path");
49260
- var import_node_child_process16 = require("child_process");
50178
+ var import_node_child_process17 = require("child_process");
49261
50179
 
49262
50180
  // src/core/asn.ts
49263
50181
  var import_node_dns = require("dns");
@@ -49450,35 +50368,35 @@ function parseKeyLoginsByFingerprint(text) {
49450
50368
  }
49451
50369
  function readJson2(path2) {
49452
50370
  try {
49453
- return JSON.parse((0, import_node_fs50.readFileSync)(path2, "utf-8"));
50371
+ return JSON.parse((0, import_node_fs52.readFileSync)(path2, "utf-8"));
49454
50372
  } catch {
49455
50373
  return null;
49456
50374
  }
49457
50375
  }
49458
50376
  function writeJson2(path2, value) {
49459
- (0, import_node_fs50.mkdirSync)((0, import_node_path41.dirname)(path2), { recursive: true });
49460
- (0, import_node_fs50.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
49461
- (0, import_node_fs50.renameSync)(`${path2}.tmp`, path2);
50377
+ (0, import_node_fs52.mkdirSync)((0, import_node_path41.dirname)(path2), { recursive: true });
50378
+ (0, import_node_fs52.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
50379
+ (0, import_node_fs52.renameSync)(`${path2}.tmp`, path2);
49462
50380
  }
49463
50381
  var fsIO2 = {
49464
50382
  readFile: (p) => {
49465
50383
  try {
49466
- return (0, import_node_fs50.readFileSync)(p, "utf-8");
50384
+ return (0, import_node_fs52.readFileSync)(p, "utf-8");
49467
50385
  } catch {
49468
50386
  return null;
49469
50387
  }
49470
50388
  },
49471
50389
  readDir: (p) => {
49472
50390
  try {
49473
- return (0, import_node_fs50.readdirSync)(p);
50391
+ return (0, import_node_fs52.readdirSync)(p);
49474
50392
  } catch {
49475
50393
  return null;
49476
50394
  }
49477
50395
  },
49478
- exists: (p) => (0, import_node_fs50.existsSync)(p)
50396
+ exists: (p) => (0, import_node_fs52.existsSync)(p)
49479
50397
  };
49480
50398
  function defaultRun4(cmd, args) {
49481
- const res = (0, import_node_child_process16.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
50399
+ const res = (0, import_node_child_process17.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
49482
50400
  return res.status === 0 ? res.stdout : null;
49483
50401
  }
49484
50402
  var SshIntrusionWatch = class {
@@ -49676,23 +50594,23 @@ var SshIntrusionWatch = class {
49676
50594
  };
49677
50595
 
49678
50596
  // src/daemon/key-directory.ts
49679
- var import_node_fs51 = require("fs");
50597
+ var import_node_fs53 = require("fs");
49680
50598
  var fsIO3 = {
49681
50599
  readFile: (p) => {
49682
50600
  try {
49683
- return (0, import_node_fs51.readFileSync)(p, "utf-8");
50601
+ return (0, import_node_fs53.readFileSync)(p, "utf-8");
49684
50602
  } catch {
49685
50603
  return null;
49686
50604
  }
49687
50605
  },
49688
50606
  readDir: (p) => {
49689
50607
  try {
49690
- return (0, import_node_fs51.readdirSync)(p);
50608
+ return (0, import_node_fs53.readdirSync)(p);
49691
50609
  } catch {
49692
50610
  return null;
49693
50611
  }
49694
50612
  },
49695
- exists: (p) => (0, import_node_fs51.existsSync)(p)
50613
+ exists: (p) => (0, import_node_fs53.existsSync)(p)
49696
50614
  };
49697
50615
  var KeyDirectory = class {
49698
50616
  constructor(io = fsIO3, now = Date.now, ttlMs = 3e5) {
@@ -49736,7 +50654,7 @@ function enrichLoginEvent(event, keys) {
49736
50654
  }
49737
50655
 
49738
50656
  // src/daemon/workers/lightning-watch.ts
49739
- var import_node_fs52 = require("fs");
50657
+ var import_node_fs54 = require("fs");
49740
50658
  var DEFAULT_CLN_LOGS = [
49741
50659
  "/home/lightning/.lightning/cln.log",
49742
50660
  "/root/.lightning/cln.log",
@@ -49792,9 +50710,9 @@ var LightningWatch = class {
49792
50710
  if (this.opts.enabled === false) return [];
49793
50711
  const found = [];
49794
50712
  for (const path2 of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
49795
- if (!(0, import_node_fs52.existsSync)(path2)) continue;
50713
+ if (!(0, import_node_fs54.existsSync)(path2)) continue;
49796
50714
  try {
49797
- (0, import_node_fs52.accessSync)(path2, import_node_fs52.constants.R_OK);
50715
+ (0, import_node_fs54.accessSync)(path2, import_node_fs54.constants.R_OK);
49798
50716
  } catch {
49799
50717
  continue;
49800
50718
  }
@@ -49829,7 +50747,7 @@ var LightningWatch = class {
49829
50747
  };
49830
50748
 
49831
50749
  // src/daemon/workers/docker-logs.ts
49832
- var import_node_fs53 = require("fs");
50750
+ var import_node_fs55 = require("fs");
49833
50751
  var import_node_http = require("http");
49834
50752
  var import_node_net15 = require("net");
49835
50753
  var DEFAULT_DOCKER_SOCKET = "/var/run/docker.sock";
@@ -50020,7 +50938,7 @@ var DockerLogsWatch = class {
50020
50938
  start() {
50021
50939
  const { settings } = this.opts;
50022
50940
  if (!settings.enabled) return false;
50023
- if (!this.opts.deps && !(0, import_node_fs53.existsSync)(settings.socket)) return false;
50941
+ if (!this.opts.deps && !(0, import_node_fs55.existsSync)(settings.socket)) return false;
50024
50942
  this.opts.log(`[docker-logs] following containers named /${settings.namePattern.source}/ or with image /${settings.imagePattern.source}/ for Postgres auth failures`);
50025
50943
  void this.poll();
50026
50944
  this.timer = setInterval(() => {
@@ -50054,9 +50972,9 @@ var DockerLogsWatch = class {
50054
50972
  if (this.stopped) return;
50055
50973
  const now = Date.now();
50056
50974
  const previous = this.lastPoll;
50057
- let list;
50975
+ let list2;
50058
50976
  try {
50059
- list = await this.deps.getJson("/containers/json");
50977
+ list2 = await this.deps.getJson("/containers/json");
50060
50978
  this.warned = false;
50061
50979
  } catch (err) {
50062
50980
  if (!this.warned) this.opts.log(`[docker-logs] cannot list containers: ${err.message}`);
@@ -50065,7 +50983,7 @@ var DockerLogsWatch = class {
50065
50983
  }
50066
50984
  this.lastPoll = now;
50067
50985
  const running = /* @__PURE__ */ new Set();
50068
- for (const c of Array.isArray(list) ? list : []) {
50986
+ for (const c of Array.isArray(list2) ? list2 : []) {
50069
50987
  if (!c?.Id || !this.matches(c)) continue;
50070
50988
  running.add(c.Id);
50071
50989
  if (this.follows.has(c.Id)) continue;
@@ -50126,7 +51044,7 @@ var DockerLogsWatch = class {
50126
51044
  };
50127
51045
 
50128
51046
  // src/core/tor-exits.ts
50129
- var import_node_fs54 = require("fs");
51047
+ var import_node_fs56 = require("fs");
50130
51048
  var import_node_path42 = require("path");
50131
51049
  var import_node_net16 = require("net");
50132
51050
  var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
@@ -50199,10 +51117,10 @@ var TorExitList = class _TorExitList {
50199
51117
  }
50200
51118
  loadCache() {
50201
51119
  try {
50202
- if (!(0, import_node_fs54.existsSync)(this.opts.cachePath)) return false;
50203
- const parsed = parseTorExitList((0, import_node_fs54.readFileSync)(this.opts.cachePath, "utf-8"));
51120
+ if (!(0, import_node_fs56.existsSync)(this.opts.cachePath)) return false;
51121
+ const parsed = parseTorExitList((0, import_node_fs56.readFileSync)(this.opts.cachePath, "utf-8"));
50204
51122
  if (parsed.size === 0) return false;
50205
- this.load(parsed, (0, import_node_fs54.statSync)(this.opts.cachePath).mtimeMs);
51123
+ this.load(parsed, (0, import_node_fs56.statSync)(this.opts.cachePath).mtimeMs);
50206
51124
  this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
50207
51125
  return true;
50208
51126
  } catch (err) {
@@ -50234,9 +51152,9 @@ var TorExitList = class _TorExitList {
50234
51152
  const before2 = this.exits.size;
50235
51153
  this.load(parsed);
50236
51154
  try {
50237
- (0, import_node_fs54.mkdirSync)((0, import_node_path42.dirname)(this.opts.cachePath), { recursive: true });
50238
- (0, import_node_fs54.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
50239
- (0, import_node_fs54.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
51155
+ (0, import_node_fs56.mkdirSync)((0, import_node_path42.dirname)(this.opts.cachePath), { recursive: true });
51156
+ (0, import_node_fs56.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
51157
+ (0, import_node_fs56.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
50240
51158
  } catch (err) {
50241
51159
  this.log(`[tor] could not save the exit list cache: ${err.message}`);
50242
51160
  }
@@ -50246,12 +51164,12 @@ var TorExitList = class _TorExitList {
50246
51164
  };
50247
51165
 
50248
51166
  // src/daemon/firewall/tor-block.ts
50249
- var import_node_child_process17 = require("child_process");
51167
+ var import_node_child_process18 = require("child_process");
50250
51168
  var import_node_net17 = require("net");
50251
51169
  var TOR_NFT_TABLE = "threatcrush-tor";
50252
51170
  function defaultNftRunner() {
50253
51171
  return (args, stdin) => new Promise((resolve9, reject) => {
50254
- const child = (0, import_node_child_process17.execFile)(
51172
+ const child = (0, import_node_child_process18.execFile)(
50255
51173
  "nft",
50256
51174
  args,
50257
51175
  { maxBuffer: 16 * 1024 * 1024 },
@@ -50547,7 +51465,7 @@ var RuleEngine = class {
50547
51465
  };
50548
51466
 
50549
51467
  // src/daemon/rules/loader.ts
50550
- var import_node_fs55 = require("fs");
51468
+ var import_node_fs57 = require("fs");
50551
51469
  var import_node_path43 = require("path");
50552
51470
 
50553
51471
  // src/daemon/rules/default-rules.ts
@@ -51220,16 +52138,16 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
51220
52138
  function loadAllRules(customDir) {
51221
52139
  const rules = [...DEFAULT_RULES];
51222
52140
  const dir = customDir || RULES_DIR;
51223
- if ((0, import_node_fs55.existsSync)(dir)) {
52141
+ if ((0, import_node_fs57.existsSync)(dir)) {
51224
52142
  let files = [];
51225
52143
  try {
51226
- files = (0, import_node_fs55.readdirSync)(dir).filter((f) => f.endsWith(".json"));
52144
+ files = (0, import_node_fs57.readdirSync)(dir).filter((f) => f.endsWith(".json"));
51227
52145
  } catch (err) {
51228
52146
  console.warn(`[rules] cannot read ${dir}: ${err.message}; custom rules not loaded`);
51229
52147
  }
51230
52148
  for (const file of files) {
51231
52149
  try {
51232
- const raw = (0, import_node_fs55.readFileSync)((0, import_node_path43.join)(dir, file), "utf-8");
52150
+ const raw = (0, import_node_fs57.readFileSync)((0, import_node_path43.join)(dir, file), "utf-8");
51233
52151
  const parsed = JSON.parse(raw);
51234
52152
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
51235
52153
  for (const rule of customRules) {
@@ -51260,8 +52178,8 @@ function loadAllRules(customDir) {
51260
52178
  }
51261
52179
 
51262
52180
  // src/daemon/firewall/adapters.ts
51263
- var import_node_child_process18 = require("child_process");
51264
- var import_node_fs56 = require("fs");
52181
+ var import_node_child_process19 = require("child_process");
52182
+ var import_node_fs58 = require("fs");
51265
52183
  var import_node_path44 = require("path");
51266
52184
  var import_node_net18 = require("net");
51267
52185
  function assertValidFirewallIp(ip) {
@@ -51275,9 +52193,9 @@ function assertBannableIp(ip) {
51275
52193
  }
51276
52194
  }
51277
52195
  function writeIfAbsent(path2, contents) {
51278
- (0, import_node_fs56.mkdirSync)((0, import_node_path44.dirname)(path2), { recursive: true });
52196
+ (0, import_node_fs58.mkdirSync)((0, import_node_path44.dirname)(path2), { recursive: true });
51279
52197
  try {
51280
- (0, import_node_fs56.writeFileSync)(path2, contents, { flag: "wx" });
52198
+ (0, import_node_fs58.writeFileSync)(path2, contents, { flag: "wx" });
51281
52199
  } catch (err) {
51282
52200
  if (err.code !== "EEXIST") throw err;
51283
52201
  }
@@ -51296,11 +52214,11 @@ var Fail2banAdapter = class {
51296
52214
  enforces = true;
51297
52215
  jailReady = false;
51298
52216
  isAvailable() {
51299
- const result = (0, import_node_child_process18.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
52217
+ const result = (0, import_node_child_process19.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
51300
52218
  return result.status === 0;
51301
52219
  }
51302
52220
  client(args) {
51303
- return (0, import_node_child_process18.execFileSync)("fail2ban-client", args, {
52221
+ return (0, import_node_child_process19.execFileSync)("fail2ban-client", args, {
51304
52222
  encoding: "utf-8",
51305
52223
  stdio: ["ignore", "pipe", "pipe"]
51306
52224
  });
@@ -51396,35 +52314,35 @@ var NftablesAdapter = class {
51396
52314
  table = "threatcrush";
51397
52315
  set = "blocklist";
51398
52316
  isAvailable() {
51399
- const result = (0, import_node_child_process18.spawnSync)("nft", ["--version"], { stdio: "pipe" });
52317
+ const result = (0, import_node_child_process19.spawnSync)("nft", ["--version"], { stdio: "pipe" });
51400
52318
  return result.status === 0;
51401
52319
  }
51402
52320
  ensureSetup() {
51403
52321
  try {
51404
- (0, import_node_child_process18.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
52322
+ (0, import_node_child_process19.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
51405
52323
  } catch {
51406
- (0, import_node_child_process18.execSync)(`nft add table inet ${this.table}`);
51407
- (0, import_node_child_process18.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
51408
- (0, import_node_child_process18.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
51409
- (0, import_node_child_process18.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
52324
+ (0, import_node_child_process19.execSync)(`nft add table inet ${this.table}`);
52325
+ (0, import_node_child_process19.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
52326
+ (0, import_node_child_process19.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
52327
+ (0, import_node_child_process19.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
51410
52328
  }
51411
52329
  }
51412
52330
  async block(ip) {
51413
52331
  assertValidFirewallIp(ip);
51414
52332
  this.ensureSetup();
51415
- (0, import_node_child_process18.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
52333
+ (0, import_node_child_process19.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
51416
52334
  }
51417
52335
  async unblock(ip) {
51418
52336
  assertValidFirewallIp(ip);
51419
52337
  try {
51420
- (0, import_node_child_process18.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
52338
+ (0, import_node_child_process19.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
51421
52339
  } catch {
51422
52340
  }
51423
52341
  }
51424
52342
  async isBlocked(ip) {
51425
52343
  assertValidFirewallIp(ip);
51426
52344
  try {
51427
- const output = (0, import_node_child_process18.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
52345
+ const output = (0, import_node_child_process19.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
51428
52346
  return output.includes(ip);
51429
52347
  } catch {
51430
52348
  return false;
@@ -51432,7 +52350,7 @@ var NftablesAdapter = class {
51432
52350
  }
51433
52351
  async listBlocked() {
51434
52352
  try {
51435
- const output = (0, import_node_child_process18.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
52353
+ const output = (0, import_node_child_process19.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
51436
52354
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
51437
52355
  if (!match) return [];
51438
52356
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -51445,34 +52363,34 @@ var IptablesAdapter = class {
51445
52363
  name = "iptables";
51446
52364
  chain = "THREATCRUSH";
51447
52365
  isAvailable() {
51448
- const result = (0, import_node_child_process18.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
52366
+ const result = (0, import_node_child_process19.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
51449
52367
  return result.status === 0;
51450
52368
  }
51451
52369
  ensureChain() {
51452
52370
  try {
51453
- (0, import_node_child_process18.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
52371
+ (0, import_node_child_process19.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
51454
52372
  } catch {
51455
- (0, import_node_child_process18.execSync)(`iptables -N ${this.chain}`);
51456
- (0, import_node_child_process18.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
52373
+ (0, import_node_child_process19.execSync)(`iptables -N ${this.chain}`);
52374
+ (0, import_node_child_process19.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
51457
52375
  }
51458
52376
  }
51459
52377
  async block(ip) {
51460
52378
  assertValidFirewallIp(ip);
51461
52379
  this.ensureChain();
51462
52380
  if (await this.isBlocked(ip)) return;
51463
- (0, import_node_child_process18.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
52381
+ (0, import_node_child_process19.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
51464
52382
  }
51465
52383
  async unblock(ip) {
51466
52384
  assertValidFirewallIp(ip);
51467
52385
  try {
51468
- (0, import_node_child_process18.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
52386
+ (0, import_node_child_process19.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
51469
52387
  } catch {
51470
52388
  }
51471
52389
  }
51472
52390
  async isBlocked(ip) {
51473
52391
  assertValidFirewallIp(ip);
51474
52392
  try {
51475
- const output = (0, import_node_child_process18.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
52393
+ const output = (0, import_node_child_process19.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
51476
52394
  return output.includes(ip);
51477
52395
  } catch {
51478
52396
  return false;
@@ -51480,7 +52398,7 @@ var IptablesAdapter = class {
51480
52398
  }
51481
52399
  async listBlocked() {
51482
52400
  try {
51483
- const output = (0, import_node_child_process18.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
52401
+ const output = (0, import_node_child_process19.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
51484
52402
  const ips = [];
51485
52403
  for (const line2 of output.split("\n")) {
51486
52404
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -51536,8 +52454,8 @@ function detectFirewallAdapter(backend = "auto") {
51536
52454
  }
51537
52455
 
51538
52456
  // src/daemon/firewall/remediation.ts
51539
- var import_node_fs57 = require("fs");
51540
- var import_node_child_process19 = require("child_process");
52457
+ var import_node_fs59 = require("fs");
52458
+ var import_node_child_process20 = require("child_process");
51541
52459
  var import_node_net19 = require("net");
51542
52460
  init_paths();
51543
52461
  init_backoff();
@@ -51608,19 +52526,19 @@ var defaultDiscovery = {
51608
52526
  const snapshot = takeSnapshot({
51609
52527
  readFile: (p) => {
51610
52528
  try {
51611
- return (0, import_node_fs57.readFileSync)(p, "utf-8");
52529
+ return (0, import_node_fs59.readFileSync)(p, "utf-8");
51612
52530
  } catch {
51613
52531
  return null;
51614
52532
  }
51615
52533
  },
51616
52534
  readDir: (p) => {
51617
52535
  try {
51618
- return (0, import_node_fs57.readdirSync)(p);
52536
+ return (0, import_node_fs59.readdirSync)(p);
51619
52537
  } catch {
51620
52538
  return null;
51621
52539
  }
51622
52540
  },
51623
- exists: (p) => (0, import_node_fs57.existsSync)(p)
52541
+ exists: (p) => (0, import_node_fs59.existsSync)(p)
51624
52542
  });
51625
52543
  const out = /* @__PURE__ */ new Set();
51626
52544
  for (const keys of Object.values(snapshot.keys)) {
@@ -51629,7 +52547,7 @@ var defaultDiscovery = {
51629
52547
  return out;
51630
52548
  },
51631
52549
  keyLoginJournal: (sinceSeconds) => new Promise((resolve9) => {
51632
- (0, import_node_child_process19.execFile)(
52550
+ (0, import_node_child_process20.execFile)(
51633
52551
  "journalctl",
51634
52552
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
51635
52553
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
@@ -52133,7 +53051,7 @@ var RemediationManager = class {
52133
53051
  }
52134
53052
  logLine(line2) {
52135
53053
  try {
52136
- (0, import_node_fs57.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
53054
+ (0, import_node_fs59.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
52137
53055
  `);
52138
53056
  } catch {
52139
53057
  }
@@ -52177,13 +53095,13 @@ function remediationSettings(section) {
52177
53095
  init_backoff();
52178
53096
 
52179
53097
  // src/daemon/watchdog-service.ts
52180
- var import_node_fs58 = require("fs");
53098
+ var import_node_fs60 = require("fs");
52181
53099
  var import_node_path45 = require("path");
52182
53100
  function defaultShareGid() {
52183
53101
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
52184
53102
  if (!isRoot4) return void 0;
52185
53103
  try {
52186
- return (0, import_node_fs58.statSync)("/var/log/auth.log").gid;
53104
+ return (0, import_node_fs60.statSync)("/var/log/auth.log").gid;
52187
53105
  } catch {
52188
53106
  return void 0;
52189
53107
  }
@@ -52283,7 +53201,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
52283
53201
  }
52284
53202
 
52285
53203
  // src/core/node-runtime.ts
52286
- var import_node_child_process20 = require("child_process");
53204
+ var import_node_child_process21 = require("child_process");
52287
53205
  var MIN_DAEMON_NODE_MAJOR = 22;
52288
53206
  function nodeMajor(version) {
52289
53207
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -52297,21 +53215,21 @@ function daemonNodeProblem(version) {
52297
53215
  }
52298
53216
  function versionOfNode(path2) {
52299
53217
  if (path2 === process.execPath) return process.versions.node;
52300
- const res = (0, import_node_child_process20.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
53218
+ const res = (0, import_node_child_process21.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
52301
53219
  return res.status === 0 ? res.stdout.trim() : null;
52302
53220
  }
52303
53221
 
52304
53222
  // src/daemon/index.ts
52305
53223
  function readVersion2() {
52306
53224
  try {
52307
- const pkg = JSON.parse((0, import_node_fs59.readFileSync)((0, import_node_path46.join)(__dirname, "..", "package.json"), "utf-8"));
53225
+ const pkg = JSON.parse((0, import_node_fs61.readFileSync)((0, import_node_path46.join)(__dirname, "..", "package.json"), "utf-8"));
52308
53226
  return pkg.version || "0.0.0";
52309
53227
  } catch {
52310
53228
  return "0.0.0";
52311
53229
  }
52312
53230
  }
52313
53231
  async function runHardeningChecks() {
52314
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process21.execFile)(
53232
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process22.execFile)(
52315
53233
  process.execPath,
52316
53234
  [(0, import_node_path46.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
52317
53235
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
@@ -52325,7 +53243,7 @@ async function runHardeningChecks() {
52325
53243
  return patches ? [...findings2, patches] : findings2;
52326
53244
  }
52327
53245
  async function runPatchCheck() {
52328
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process21.execFile)(
53246
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process22.execFile)(
52329
53247
  process.execPath,
52330
53248
  [(0, import_node_path46.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
52331
53249
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
@@ -52335,7 +53253,7 @@ async function runPatchCheck() {
52335
53253
  }
52336
53254
  function logLine(line2) {
52337
53255
  try {
52338
- (0, import_node_fs59.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
53256
+ (0, import_node_fs61.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
52339
53257
  `);
52340
53258
  } catch {
52341
53259
  }
@@ -52360,9 +53278,9 @@ async function runDaemon() {
52360
53278
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
52361
53279
  const restartDaemon = () => {
52362
53280
  if (PATHS.mode === "system") {
52363
- (0, import_node_child_process21.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
53281
+ (0, import_node_child_process22.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
52364
53282
  } else {
52365
- (0, import_node_child_process21.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
53283
+ (0, import_node_child_process22.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
52366
53284
  setTimeout(() => process.exit(0), 500).unref();
52367
53285
  }
52368
53286
  };
@@ -52551,7 +53469,7 @@ async function runDaemon() {
52551
53469
  cloudSync = new CloudSync({
52552
53470
  bus,
52553
53471
  version,
52554
- hostname: (0, import_node_os19.hostname)(),
53472
+ hostname: (0, import_node_os20.hostname)(),
52555
53473
  minSeverity,
52556
53474
  spoolPath: (0, import_node_path46.join)(PATHS.stateDir, "cloud-spool.jsonl"),
52557
53475
  log: logLine,
@@ -52723,7 +53641,7 @@ async function daemonStart() {
52723
53641
  return;
52724
53642
  }
52725
53643
  ensureRuntimeDirs();
52726
- if (!(0, import_node_fs60.existsSync)(DAEMON_ENTRY)) {
53644
+ if (!(0, import_node_fs62.existsSync)(DAEMON_ENTRY)) {
52727
53645
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
52728
53646
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
52729
53647
  return;
@@ -52731,8 +53649,8 @@ async function daemonStart() {
52731
53649
  let out;
52732
53650
  let err;
52733
53651
  try {
52734
- out = (0, import_node_fs61.openSync)(PATHS.logFile, "a");
52735
- err = (0, import_node_fs61.openSync)(PATHS.logFile, "a");
53652
+ out = (0, import_node_fs63.openSync)(PATHS.logFile, "a");
53653
+ err = (0, import_node_fs63.openSync)(PATHS.logFile, "a");
52736
53654
  } catch (e) {
52737
53655
  const code = e.code;
52738
53656
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -52745,7 +53663,7 @@ async function daemonStart() {
52745
53663
  }
52746
53664
  return;
52747
53665
  }
52748
- const child = (0, import_node_child_process22.spawn)(process.execPath, [DAEMON_ENTRY], {
53666
+ const child = (0, import_node_child_process23.spawn)(process.execPath, [DAEMON_ENTRY], {
52749
53667
  detached: true,
52750
53668
  stdio: ["ignore", out, err],
52751
53669
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -52820,41 +53738,41 @@ async function waitForExit(pid, timeoutMs) {
52820
53738
  }
52821
53739
  async function releaseStaleSocket() {
52822
53740
  const deadline = Date.now() + 2e3;
52823
- while ((0, import_node_fs60.existsSync)(PATHS.socket) && Date.now() < deadline) {
53741
+ while ((0, import_node_fs62.existsSync)(PATHS.socket) && Date.now() < deadline) {
52824
53742
  await new Promise((r) => setTimeout(r, 50));
52825
53743
  }
52826
- if ((0, import_node_fs60.existsSync)(PATHS.socket)) {
53744
+ if ((0, import_node_fs62.existsSync)(PATHS.socket)) {
52827
53745
  try {
52828
- (0, import_node_fs60.unlinkSync)(PATHS.socket);
53746
+ (0, import_node_fs62.unlinkSync)(PATHS.socket);
52829
53747
  } catch {
52830
53748
  }
52831
53749
  }
52832
53750
  }
52833
53751
 
52834
53752
  // src/commands/service.ts
52835
- var import_node_child_process23 = require("child_process");
52836
- var import_node_fs62 = require("fs");
53753
+ var import_node_child_process24 = require("child_process");
53754
+ var import_node_fs64 = require("fs");
52837
53755
  var import_node_path48 = require("path");
52838
- var import_node_os20 = require("os");
53756
+ var import_node_os21 = require("os");
52839
53757
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
52840
53758
  var DAEMON_UNIT_NAME = "threatcrushd.service";
52841
53759
  function resolveTemplate() {
52842
53760
  const templatePath = (0, import_node_path48.join)(__dirname, "systemd", "threatcrushd.service");
52843
- if (!(0, import_node_fs62.existsSync)(templatePath)) {
53761
+ if (!(0, import_node_fs64.existsSync)(templatePath)) {
52844
53762
  throw new Error(`systemd unit template not found at ${templatePath}`);
52845
53763
  }
52846
- return (0, import_node_fs62.readFileSync)(templatePath, "utf-8");
53764
+ return (0, import_node_fs64.readFileSync)(templatePath, "utf-8");
52847
53765
  }
52848
53766
  function stableBinPath(binPath) {
52849
53767
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
52850
53768
  if (stable === binPath) return binPath;
52851
- return (0, import_node_fs62.existsSync)(stable) ? stable : binPath;
53769
+ return (0, import_node_fs64.existsSync)(stable) ? stable : binPath;
52852
53770
  }
52853
53771
  function resolveBinPath() {
52854
53772
  const arg = process.argv[1];
52855
- if (arg && (0, import_node_fs62.existsSync)(arg)) return stableBinPath(arg);
53773
+ if (arg && (0, import_node_fs64.existsSync)(arg)) return stableBinPath(arg);
52856
53774
  try {
52857
- return (0, import_node_child_process23.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
53775
+ return (0, import_node_child_process24.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
52858
53776
  } catch {
52859
53777
  return "threatcrush";
52860
53778
  }
@@ -52862,11 +53780,11 @@ function resolveBinPath() {
52862
53780
  function stableNodePath(execPath) {
52863
53781
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
52864
53782
  if (stable === execPath) return execPath;
52865
- return (0, import_node_fs62.existsSync)(stable) ? stable : execPath;
53783
+ return (0, import_node_fs64.existsSync)(stable) ? stable : execPath;
52866
53784
  }
52867
53785
  function looksLikeNodeScript(path2) {
52868
53786
  try {
52869
- const head2 = (0, import_node_fs62.readFileSync)(path2, "utf-8").slice(0, 120);
53787
+ const head2 = (0, import_node_fs64.readFileSync)(path2, "utf-8").slice(0, 120);
52870
53788
  return /^#!.*\bnode\b/.test(head2);
52871
53789
  } catch {
52872
53790
  return false;
@@ -52893,20 +53811,20 @@ function isRoot3() {
52893
53811
  return typeof process.getuid === "function" && process.getuid() === 0;
52894
53812
  }
52895
53813
  function reexecWithSudo(args) {
52896
- if ((0, import_node_child_process23.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
53814
+ if ((0, import_node_child_process24.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
52897
53815
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
52898
53816
  const bin = resolveBinPath();
52899
53817
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
52900
- const result = (0, import_node_child_process23.spawnSync)("sudo", argv, { stdio: "inherit" });
53818
+ const result = (0, import_node_child_process24.spawnSync)("sudo", argv, { stdio: "inherit" });
52901
53819
  return result.status === 0;
52902
53820
  }
52903
53821
  function callerHome() {
52904
53822
  const user = process.env.SUDO_USER;
52905
53823
  if (!user) return null;
52906
53824
  try {
52907
- const line2 = (0, import_node_child_process23.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
53825
+ const line2 = (0, import_node_child_process24.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
52908
53826
  const home = line2.split(":")[5];
52909
- return home && (0, import_node_fs62.existsSync)(home) ? home : null;
53827
+ return home && (0, import_node_fs64.existsSync)(home) ? home : null;
52910
53828
  } catch {
52911
53829
  return null;
52912
53830
  }
@@ -52917,10 +53835,10 @@ function stopUserModeDaemon() {
52917
53835
  const runDir = (0, import_node_path48.join)(home, ".threatcrush", "run");
52918
53836
  const pidFile = (0, import_node_path48.join)(runDir, "threatcrushd.pid");
52919
53837
  const socket = (0, import_node_path48.join)(runDir, "threatcrushd.sock");
52920
- if (!(0, import_node_fs62.existsSync)(pidFile) && !(0, import_node_fs62.existsSync)(socket)) return;
53838
+ if (!(0, import_node_fs64.existsSync)(pidFile) && !(0, import_node_fs64.existsSync)(socket)) return;
52921
53839
  let pid = null;
52922
53840
  try {
52923
- pid = Number.parseInt((0, import_node_fs62.readFileSync)(pidFile, "utf-8").trim(), 10);
53841
+ pid = Number.parseInt((0, import_node_fs64.readFileSync)(pidFile, "utf-8").trim(), 10);
52924
53842
  } catch {
52925
53843
  pid = null;
52926
53844
  }
@@ -52933,13 +53851,13 @@ function stopUserModeDaemon() {
52933
53851
  }
52934
53852
  for (const path2 of [socket, pidFile]) {
52935
53853
  try {
52936
- if ((0, import_node_fs62.existsSync)(path2)) (0, import_node_fs62.rmSync)(path2);
53854
+ if ((0, import_node_fs64.existsSync)(path2)) (0, import_node_fs64.rmSync)(path2);
52937
53855
  } catch {
52938
53856
  }
52939
53857
  }
52940
53858
  }
52941
53859
  function unitIsActive() {
52942
- const result = (0, import_node_child_process23.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
53860
+ const result = (0, import_node_child_process24.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
52943
53861
  return result.status === 0;
52944
53862
  }
52945
53863
  async function installServiceCommand() {
@@ -52950,8 +53868,8 @@ async function installServiceCommand() {
52950
53868
  return;
52951
53869
  }
52952
53870
  const noSystemd = systemdUnavailableReason({
52953
- hasSystemctl: (0, import_node_child_process23.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
52954
- booted: (0, import_node_fs62.existsSync)("/run/systemd/system")
53871
+ hasSystemctl: (0, import_node_child_process24.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
53872
+ booted: (0, import_node_fs64.existsSync)("/run/systemd/system")
52955
53873
  });
52956
53874
  if (noSystemd) {
52957
53875
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -52973,7 +53891,7 @@ async function installServiceCommand() {
52973
53891
  const isNodeScript = looksLikeNodeScript(binPath);
52974
53892
  let nodePath = stableNodePath(process.execPath);
52975
53893
  if (isNodeScript && nodeVersionDir(binPath)) {
52976
- binPath = (0, import_node_fs62.realpathSync)(binPath);
53894
+ binPath = (0, import_node_fs64.realpathSync)(binPath);
52977
53895
  nodePath = process.execPath;
52978
53896
  }
52979
53897
  if (isNodeScript) {
@@ -52986,11 +53904,11 @@ async function installServiceCommand() {
52986
53904
  }
52987
53905
  }
52988
53906
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
52989
- const configDir = (0, import_node_path48.join)((0, import_node_os20.homedir)(), ".threatcrush");
53907
+ const configDir = (0, import_node_path48.join)((0, import_node_os21.homedir)(), ".threatcrush");
52990
53908
  const commandHistoryEnabled = commandHistorySettings(loadConfig().command_history).enabled;
52991
53909
  const historyPaths = commandHistoryEnabled ? historyWritableHomes() : [];
52992
53910
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir, historyPaths });
52993
- (0, import_node_fs62.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
53911
+ (0, import_node_fs64.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
52994
53912
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
52995
53913
  console.log(source_default.dim(` ExecStart=${exec}`));
52996
53914
  const nodeDir = nodeVersionDir(nodePath);
@@ -53005,8 +53923,8 @@ async function installServiceCommand() {
53005
53923
  installLogrotate();
53006
53924
  stopUserModeDaemon();
53007
53925
  try {
53008
- (0, import_node_child_process23.execSync)("systemctl daemon-reload", { stdio: "inherit" });
53009
- (0, import_node_child_process23.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
53926
+ (0, import_node_child_process24.execSync)("systemctl daemon-reload", { stdio: "inherit" });
53927
+ (0, import_node_child_process24.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
53010
53928
  } catch (err) {
53011
53929
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
53012
53930
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -53043,9 +53961,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
53043
53961
  ].join("\n");
53044
53962
  }
53045
53963
  function installLogrotate() {
53046
- if (!(0, import_node_fs62.existsSync)((0, import_node_path48.dirname)(LOGROTATE_PATH))) return;
53964
+ if (!(0, import_node_fs64.existsSync)((0, import_node_path48.dirname)(LOGROTATE_PATH))) return;
53047
53965
  try {
53048
- (0, import_node_fs62.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
53966
+ (0, import_node_fs64.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
53049
53967
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
53050
53968
  } catch (err) {
53051
53969
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -53067,20 +53985,20 @@ function ensureSystemDirs(configDir) {
53067
53985
  ];
53068
53986
  let admGid2 = null;
53069
53987
  try {
53070
- admGid2 = (0, import_node_fs62.statSync)("/var/log/auth.log").gid;
53988
+ admGid2 = (0, import_node_fs64.statSync)("/var/log/auth.log").gid;
53071
53989
  } catch {
53072
53990
  }
53073
53991
  for (const { path: path2, groupWritable, sticky } of dirs) {
53074
53992
  try {
53075
- (0, import_node_fs62.mkdirSync)(path2, { recursive: true });
53993
+ (0, import_node_fs64.mkdirSync)(path2, { recursive: true });
53076
53994
  } catch {
53077
53995
  }
53078
53996
  try {
53079
53997
  if (groupWritable && admGid2 !== null) {
53080
- (0, import_node_fs62.chmodSync)(path2, sticky ? 1533 : 509);
53081
- (0, import_node_child_process23.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
53998
+ (0, import_node_fs64.chmodSync)(path2, sticky ? 1533 : 509);
53999
+ (0, import_node_child_process24.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
53082
54000
  } else {
53083
- (0, import_node_fs62.chmodSync)(path2, 493);
54001
+ (0, import_node_fs64.chmodSync)(path2, 493);
53084
54002
  }
53085
54003
  } catch {
53086
54004
  }
@@ -53100,29 +54018,29 @@ async function uninstallServiceCommand() {
53100
54018
  return;
53101
54019
  }
53102
54020
  try {
53103
- (0, import_node_child_process23.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
54021
+ (0, import_node_child_process24.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
53104
54022
  } catch {
53105
54023
  }
53106
54024
  try {
53107
- (0, import_node_child_process23.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
54025
+ (0, import_node_child_process24.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
53108
54026
  } catch {
53109
54027
  }
53110
54028
  try {
53111
- if ((0, import_node_fs62.existsSync)(UNIT_PATH)) {
53112
- (0, import_node_child_process23.execSync)(`rm -f ${UNIT_PATH}`);
54029
+ if ((0, import_node_fs64.existsSync)(UNIT_PATH)) {
54030
+ (0, import_node_child_process24.execSync)(`rm -f ${UNIT_PATH}`);
53113
54031
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
53114
54032
  }
53115
54033
  } catch {
53116
54034
  }
53117
54035
  try {
53118
- (0, import_node_child_process23.execSync)("systemctl daemon-reload", { stdio: "inherit" });
54036
+ (0, import_node_child_process24.execSync)("systemctl daemon-reload", { stdio: "inherit" });
53119
54037
  } catch {
53120
54038
  }
53121
54039
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
53122
54040
  }
53123
54041
 
53124
54042
  // src/commands/save.ts
53125
- var import_node_fs63 = require("fs");
54043
+ var import_node_fs65 = require("fs");
53126
54044
  var import_toml6 = __toESM(require_toml());
53127
54045
  init_cli_config();
53128
54046
  init_paths();
@@ -53161,9 +54079,9 @@ async function saveCommand(opts = {}) {
53161
54079
  }
53162
54080
  const path2 = opts.config ?? PATHS.configFile;
53163
54081
  let config = {};
53164
- if ((0, import_node_fs63.existsSync)(path2)) {
54082
+ if ((0, import_node_fs65.existsSync)(path2)) {
53165
54083
  try {
53166
- config = import_toml6.default.parse((0, import_node_fs63.readFileSync)(path2, "utf-8"));
54084
+ config = import_toml6.default.parse((0, import_node_fs65.readFileSync)(path2, "utf-8"));
53167
54085
  } catch (err) {
53168
54086
  console.log(source_default.red(` \u2717 ${path2} is not valid TOML: ${err.message}
53169
54087
  `));
@@ -53276,7 +54194,7 @@ function welcomeCommand() {
53276
54194
  }
53277
54195
 
53278
54196
  // src/commands/properties.ts
53279
- var import_node_fs64 = require("fs");
54197
+ var import_node_fs66 = require("fs");
53280
54198
  var import_node_path49 = require("path");
53281
54199
  var import_node_readline4 = __toESM(require("readline"));
53282
54200
  init_cli_config();
@@ -53590,12 +54508,12 @@ async function propertiesRunsCommand(opts) {
53590
54508
  const runs = data.runs || [];
53591
54509
  if (runs.length === 0) continue;
53592
54510
  console.log(` ${source_default.white.bold(prop.name)} ${KIND_COLOR[prop.kind](`[${prop.kind}]`)}`);
53593
- for (const run2 of runs) {
53594
- const statusColor = run2.status === "succeeded" ? source_default.green : run2.status === "failed" ? source_default.red : run2.status === "running" ? source_default.yellow : run2.status === "cancelled" ? source_default.gray : source_default.cyan;
53595
- const when = (run2.completed_at || run2.started_at || run2.queued_at).slice(0, 19).replace("T", " ");
53596
- const sev = run2.severity_summary;
54511
+ for (const run3 of runs) {
54512
+ const statusColor = run3.status === "succeeded" ? source_default.green : run3.status === "failed" ? source_default.red : run3.status === "running" ? source_default.yellow : run3.status === "cancelled" ? source_default.gray : source_default.cyan;
54513
+ const when = (run3.completed_at || run3.started_at || run3.queued_at).slice(0, 19).replace("T", " ");
54514
+ const sev = run3.severity_summary;
53597
54515
  const sevStr = sev ? source_default.dim(`[${sev.critical || 0}C/${sev.high || 0}H/${sev.medium || 0}M/${sev.low || 0}L]`) : source_default.dim("[\u2013]");
53598
- console.log(` ${source_default.gray(when)} ${statusColor(run2.status.padEnd(10))} ${source_default.dim(run2.type.padEnd(8))} ${sevStr} ${source_default.gray(run2.summary || "")}`);
54516
+ console.log(` ${source_default.gray(when)} ${statusColor(run3.status.padEnd(10))} ${source_default.dim(run3.type.padEnd(8))} ${sevStr} ${source_default.gray(run3.summary || "")}`);
53599
54517
  total++;
53600
54518
  }
53601
54519
  console.log();
@@ -53608,7 +54526,7 @@ async function propertiesRunsCommand(opts) {
53608
54526
  }
53609
54527
  function parseImportFile(path2) {
53610
54528
  const ext = (0, import_node_path49.extname)(path2).toLowerCase();
53611
- const raw = (0, import_node_fs64.readFileSync)(path2, "utf-8");
54529
+ const raw = (0, import_node_fs66.readFileSync)(path2, "utf-8");
53612
54530
  if (ext === ".json") {
53613
54531
  const parsed = JSON.parse(raw);
53614
54532
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -53850,13 +54768,13 @@ async function rulesCommand(opts) {
53850
54768
  }
53851
54769
 
53852
54770
  // src/commands/harden.ts
53853
- var import_node_fs66 = require("fs");
53854
- var import_node_child_process24 = require("child_process");
54771
+ var import_node_fs68 = require("fs");
54772
+ var import_node_child_process25 = require("child_process");
53855
54773
  init_cli_config();
53856
54774
 
53857
54775
  // src/commands/cis-report.ts
53858
- var import_node_os21 = require("os");
53859
- var import_node_fs65 = require("fs");
54776
+ var import_node_os22 = require("os");
54777
+ var import_node_fs67 = require("fs");
53860
54778
  var CIS_UBUNTU_URL = "https://www.cisecurity.org/benchmark/ubuntu_linux";
53861
54779
  var CIS_DEBIAN_URL = "https://www.cisecurity.org/benchmark/debian_linux";
53862
54780
  var UBUNTU_2404_CIS_CONTROL_SOURCE = "https://github.com/ComplianceAsCode/content/blob/v0.1.78/controls/cis_ubuntu2404.yml";
@@ -53876,7 +54794,7 @@ var EDITIONS = {
53876
54794
  function osRelease() {
53877
54795
  let raw = "";
53878
54796
  try {
53879
- raw = (0, import_node_fs65.readFileSync)("/etc/os-release", "utf8");
54797
+ raw = (0, import_node_fs67.readFileSync)("/etc/os-release", "utf8");
53880
54798
  } catch {
53881
54799
  return {};
53882
54800
  }
@@ -53903,9 +54821,9 @@ var VERIFIED_CHECK_MAPPINGS = {
53903
54821
  }
53904
54822
  }
53905
54823
  };
53906
- function tagCisMappings(findings2, os4 = osRelease()) {
53907
- const distro = os4.ID?.toLowerCase() ?? "";
53908
- const version = os4.VERSION_ID ?? "";
54824
+ function tagCisMappings(findings2, os5 = osRelease()) {
54825
+ const distro = os5.ID?.toLowerCase() ?? "";
54826
+ const version = os5.VERSION_ID ?? "";
53909
54827
  const checkMappings = VERIFIED_CHECK_MAPPINGS[distro]?.[version] ?? {};
53910
54828
  return findings2.map((finding) => {
53911
54829
  const mapping = checkMappings[finding.key];
@@ -53933,11 +54851,11 @@ function tagCisMappings(findings2, os4 = osRelease()) {
53933
54851
  });
53934
54852
  }
53935
54853
  function buildCisEvidenceReport(findings2, score, now = /* @__PURE__ */ new Date()) {
53936
- const os4 = osRelease();
53937
- const id = os4.ID?.toLowerCase() ?? null;
53938
- const version = os4.VERSION_ID ?? null;
54854
+ const os5 = osRelease();
54855
+ const id = os5.ID?.toLowerCase() ?? null;
54856
+ const version = os5.VERSION_ID ?? null;
53939
54857
  const edition = id && version ? EDITIONS[id]?.[version] : void 0;
53940
- const checks = tagCisMappings(findings2, os4).map((finding) => ({
54858
+ const checks = tagCisMappings(findings2, os5).map((finding) => ({
53941
54859
  ...finding,
53942
54860
  cis_control_ids: finding.cis_control_ids ?? [],
53943
54861
  mapping_status: finding.cis_mapping_status ?? "unverified",
@@ -53949,7 +54867,7 @@ function buildCisEvidenceReport(findings2, score, now = /* @__PURE__ */ new Date
53949
54867
  schema_version: 1,
53950
54868
  generated_at: now.toISOString(),
53951
54869
  benchmark_catalog_checked_at: "2026-11-01",
53952
- host: { hostname: (0, import_node_os21.hostname)(), os_id: id, os_version: version, pretty_name: os4.PRETTY_NAME ?? null },
54870
+ host: { hostname: (0, import_node_os22.hostname)(), os_id: id, os_version: version, pretty_name: os5.PRETTY_NAME ?? null },
53953
54871
  benchmark: edition ? { name: edition.name, version: edition.version, source: edition.source } : null,
53954
54872
  assessment: "partial",
53955
54873
  mapped_controls: mappedControls.size,
@@ -54056,20 +54974,20 @@ function writeCisReport(path2, format2, report) {
54056
54974
  const markdown = renderCisMarkdown(report);
54057
54975
  const content = format2 === "json" ? `${JSON.stringify(report, null, 2)}
54058
54976
  ` : format2 === "pdf" ? renderCisPdf(markdown) : markdown;
54059
- (0, import_node_fs65.writeFileSync)(path2, content);
54977
+ (0, import_node_fs67.writeFileSync)(path2, content);
54060
54978
  }
54061
54979
 
54062
54980
  // src/commands/harden.ts
54063
54981
  function tryExec(cmd) {
54064
54982
  try {
54065
- return (0, import_node_child_process24.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
54983
+ return (0, import_node_child_process25.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
54066
54984
  } catch {
54067
54985
  return null;
54068
54986
  }
54069
54987
  }
54070
54988
  function tryRead(path2) {
54071
54989
  try {
54072
- return (0, import_node_fs66.readFileSync)(path2, "utf-8");
54990
+ return (0, import_node_fs68.readFileSync)(path2, "utf-8");
54073
54991
  } catch {
54074
54992
  return null;
54075
54993
  }
@@ -54183,8 +55101,8 @@ function checkSshWeakConfig() {
54183
55101
  };
54184
55102
  }
54185
55103
  function checkAutoUpdates() {
54186
- const unattended = (0, import_node_fs66.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs66.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
54187
- const dnfAuto = (0, import_node_fs66.existsSync)("/etc/dnf/automatic.conf");
55104
+ const unattended = (0, import_node_fs68.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs68.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
55105
+ const dnfAuto = (0, import_node_fs68.existsSync)("/etc/dnf/automatic.conf");
54188
55106
  if (unattended || dnfAuto) {
54189
55107
  return {
54190
55108
  key: "auto-updates",
@@ -54310,7 +55228,7 @@ function checkFail2ban() {
54310
55228
  explanation: "fail2ban is installed and running."
54311
55229
  };
54312
55230
  }
54313
- if ((0, import_node_fs66.existsSync)("/etc/fail2ban/fail2ban.conf")) {
55231
+ if ((0, import_node_fs68.existsSync)("/etc/fail2ban/fail2ban.conf")) {
54314
55232
  return {
54315
55233
  key: checkKey,
54316
55234
  status: "warn",
@@ -54530,9 +55448,9 @@ async function hardenCommand(opts) {
54530
55448
  }
54531
55449
 
54532
55450
  // src/core/patches/index.ts
54533
- var import_node_fs67 = require("fs");
55451
+ var import_node_fs69 = require("fs");
54534
55452
  var import_node_path50 = require("path");
54535
- var import_node_child_process25 = require("child_process");
55453
+ var import_node_child_process26 = require("child_process");
54536
55454
  var import_node_util5 = require("util");
54537
55455
 
54538
55456
  // src/core/patches/dpkg-version.ts
@@ -54592,7 +55510,7 @@ var STALE_AFTER_MS = 2 * 864e5;
54592
55510
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
54593
55511
  var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
54594
55512
  var defaultExec = async (file, args) => {
54595
- const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process25.execFile)(file, args, {
55513
+ const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process26.execFile)(file, args, {
54596
55514
  timeout: 12e4,
54597
55515
  maxBuffer: 32 * 1024 * 1024,
54598
55516
  env: { ...process.env, LC_ALL: "C" }
@@ -54607,11 +55525,11 @@ function parseOsRelease(text) {
54607
55525
  }
54608
55526
  return out;
54609
55527
  }
54610
- function osvEcosystem(os4) {
54611
- if (os4.ID === "ubuntu" && os4.VERSION_ID) {
54612
- return /LTS/.test(os4.VERSION ?? "") ? `Ubuntu:${os4.VERSION_ID}:LTS` : `Ubuntu:${os4.VERSION_ID}`;
55528
+ function osvEcosystem(os5) {
55529
+ if (os5.ID === "ubuntu" && os5.VERSION_ID) {
55530
+ return /LTS/.test(os5.VERSION ?? "") ? `Ubuntu:${os5.VERSION_ID}:LTS` : `Ubuntu:${os5.VERSION_ID}`;
54613
55531
  }
54614
- if (os4.ID === "debian" && os4.VERSION_ID) return `Debian:${os4.VERSION_ID.split(".")[0]}`;
55532
+ if (os5.ID === "debian" && os5.VERSION_ID) return `Debian:${os5.VERSION_ID.split(".")[0]}`;
54615
55533
  return null;
54616
55534
  }
54617
55535
  function parseAptSimulation(text) {
@@ -54691,9 +55609,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
54691
55609
  function newestReleaseMtime(dir) {
54692
55610
  try {
54693
55611
  let newest = 0;
54694
- for (const name of (0, import_node_fs67.readdirSync)(dir)) {
55612
+ for (const name of (0, import_node_fs69.readdirSync)(dir)) {
54695
55613
  if (!/Release$/.test(name)) continue;
54696
- newest = Math.max(newest, (0, import_node_fs67.statSync)((0, import_node_path50.join)(dir, name)).mtimeMs);
55614
+ newest = Math.max(newest, (0, import_node_fs69.statSync)((0, import_node_path50.join)(dir, name)).mtimeMs);
54697
55615
  }
54698
55616
  return newest > 0 ? new Date(newest) : null;
54699
55617
  } catch {
@@ -54710,16 +55628,16 @@ async function checkPatches(opts = {}) {
54710
55628
  let osText = opts.osRelease;
54711
55629
  if (osText === void 0) {
54712
55630
  try {
54713
- osText = (0, import_node_fs67.readFileSync)("/etc/os-release", "utf-8");
55631
+ osText = (0, import_node_fs69.readFileSync)("/etc/os-release", "utf-8");
54714
55632
  } catch {
54715
55633
  osText = "";
54716
55634
  }
54717
55635
  }
54718
- const os4 = parseOsRelease(osText);
54719
- const ecosystem = osvEcosystem(os4);
55636
+ const os5 = parseOsRelease(osText);
55637
+ const ecosystem = osvEcosystem(os5);
54720
55638
  const base = {
54721
55639
  supported: false,
54722
- os: os4.PRETTY_NAME ?? os4.ID ?? "unknown",
55640
+ os: os5.PRETTY_NAME ?? os5.ID ?? "unknown",
54723
55641
  ecosystem,
54724
55642
  checked_at: now.toISOString(),
54725
55643
  lists_updated_at: null,
@@ -54941,22 +55859,22 @@ var import_node_path52 = require("path");
54941
55859
  init_paths();
54942
55860
 
54943
55861
  // src/commands/feeds-resolver.ts
54944
- var import_node_child_process26 = require("child_process");
54945
- var import_node_fs68 = require("fs");
55862
+ var import_node_child_process27 = require("child_process");
55863
+ var import_node_fs70 = require("fs");
54946
55864
  var import_node_path51 = require("path");
54947
55865
  var realIO = {
54948
- exists: (p) => (0, import_node_fs68.existsSync)(p),
55866
+ exists: (p) => (0, import_node_fs70.existsSync)(p),
54949
55867
  read: (p) => {
54950
55868
  try {
54951
- return (0, import_node_fs68.readFileSync)(p, "utf-8");
55869
+ return (0, import_node_fs70.readFileSync)(p, "utf-8");
54952
55870
  } catch {
54953
55871
  return null;
54954
55872
  }
54955
55873
  },
54956
- write: (p, c) => (0, import_node_fs68.writeFileSync)(p, c),
54957
- remove: (p) => (0, import_node_fs68.rmSync)(p, { force: true }),
55874
+ write: (p, c) => (0, import_node_fs70.writeFileSync)(p, c),
55875
+ remove: (p) => (0, import_node_fs70.rmSync)(p, { force: true }),
54958
55876
  run: (cmd, args) => {
54959
- const r = (0, import_node_child_process26.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
55877
+ const r = (0, import_node_child_process27.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
54960
55878
  return { code: r.status ?? 1, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
54961
55879
  }
54962
55880
  };
@@ -55109,7 +56027,7 @@ async function feedsCommand(action, value, opts) {
55109
56027
  }
55110
56028
 
55111
56029
  // src/commands/tor.ts
55112
- var import_node_fs69 = require("fs");
56030
+ var import_node_fs71 = require("fs");
55113
56031
  var import_node_net21 = require("net");
55114
56032
  var import_node_path53 = require("path");
55115
56033
  init_paths();
@@ -55120,10 +56038,10 @@ async function torCommand(action, value, opts) {
55120
56038
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
55121
56039
  const path2 = (0, import_node_path53.join)(dir, "tor-exits.txt");
55122
56040
  try {
55123
- if (!(0, import_node_fs69.existsSync)(path2)) continue;
55124
- exits = parseTorExitList((0, import_node_fs69.readFileSync)(path2, "utf-8"));
56041
+ if (!(0, import_node_fs71.existsSync)(path2)) continue;
56042
+ exits = parseTorExitList((0, import_node_fs71.readFileSync)(path2, "utf-8"));
55125
56043
  from = path2;
55126
- updated = (0, import_node_fs69.statSync)(path2).mtime;
56044
+ updated = (0, import_node_fs71.statSync)(path2).mtime;
55127
56045
  break;
55128
56046
  } catch {
55129
56047
  }
@@ -55170,14 +56088,14 @@ async function torCommand(action, value, opts) {
55170
56088
  }
55171
56089
 
55172
56090
  // src/commands/reputation.ts
55173
- var import_node_os22 = require("os");
55174
- var import_node_fs70 = require("fs");
56091
+ var import_node_os23 = require("os");
56092
+ var import_node_fs72 = require("fs");
55175
56093
  var import_node_path54 = require("path");
55176
56094
  var API_URL7 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
55177
- var CONFIG_PATH4 = (0, import_node_path54.join)((0, import_node_os22.homedir)(), ".threatcrush", "config.json");
56095
+ var CONFIG_PATH4 = (0, import_node_path54.join)((0, import_node_os23.homedir)(), ".threatcrush", "config.json");
55178
56096
  function readConfig3() {
55179
56097
  try {
55180
- return JSON.parse((0, import_node_fs70.readFileSync)(CONFIG_PATH4, "utf-8"));
56098
+ return JSON.parse((0, import_node_fs72.readFileSync)(CONFIG_PATH4, "utf-8"));
55181
56099
  } catch {
55182
56100
  return {};
55183
56101
  }
@@ -55365,7 +56283,7 @@ async function reputationSubscribeCommand(opts) {
55365
56283
  }
55366
56284
 
55367
56285
  // src/commands/privileged.ts
55368
- var import_node_fs71 = require("fs");
56286
+ var import_node_fs73 = require("fs");
55369
56287
  init_paths();
55370
56288
  var SEV2 = {
55371
56289
  critical: source_default.red.bold,
@@ -55378,19 +56296,19 @@ async function privilegedCommand(opts) {
55378
56296
  const snapshot = takeSnapshot({
55379
56297
  readFile: (p) => {
55380
56298
  try {
55381
- return (0, import_node_fs71.readFileSync)(p, "utf-8");
56299
+ return (0, import_node_fs73.readFileSync)(p, "utf-8");
55382
56300
  } catch {
55383
56301
  return null;
55384
56302
  }
55385
56303
  },
55386
56304
  readDir: (p) => {
55387
56305
  try {
55388
- return (0, import_node_fs71.readdirSync)(p);
56306
+ return (0, import_node_fs73.readdirSync)(p);
55389
56307
  } catch {
55390
56308
  return null;
55391
56309
  }
55392
56310
  },
55393
- exists: (p) => (0, import_node_fs71.existsSync)(p)
56311
+ exists: (p) => (0, import_node_fs73.existsSync)(p)
55394
56312
  });
55395
56313
  let events = [];
55396
56314
  let ledgerNote = "";
@@ -55432,12 +56350,12 @@ async function privilegedCommand(opts) {
55432
56350
  }
55433
56351
 
55434
56352
  // src/commands/integrity.ts
55435
- var import_node_fs72 = require("fs");
56353
+ var import_node_fs74 = require("fs");
55436
56354
  var import_node_path55 = require("path");
55437
56355
  init_paths();
55438
56356
  function readState2(path2) {
55439
56357
  try {
55440
- return JSON.parse((0, import_node_fs72.readFileSync)(path2, "utf8"));
56358
+ return JSON.parse((0, import_node_fs74.readFileSync)(path2, "utf8"));
55441
56359
  } catch {
55442
56360
  return null;
55443
56361
  }
@@ -55458,7 +56376,7 @@ async function integrityCommand(action = "status", opts = {}) {
55458
56376
  const config = loadConfig();
55459
56377
  const settings = fileIntegritySettings(config.file_integrity);
55460
56378
  const systemBaseline = (0, import_node_path55.join)(SYSTEM_PATHS.stateDir, "file-integrity-baseline.json");
55461
- const useSystemState = PATHS.mode === "system" || systemDaemonPresent() || (0, import_node_fs72.existsSync)(systemBaseline);
56379
+ const useSystemState = PATHS.mode === "system" || systemDaemonPresent() || (0, import_node_fs74.existsSync)(systemBaseline);
55462
56380
  const stateDir = useSystemState ? SYSTEM_PATHS.stateDir : PATHS.stateDir;
55463
56381
  const baselinePath = (0, import_node_path55.join)(stateDir, "file-integrity-baseline.json");
55464
56382
  const observedPath = (0, import_node_path55.join)(stateDir, "file-integrity-observed.json");
@@ -55529,12 +56447,12 @@ async function integrityCommand(action = "status", opts = {}) {
55529
56447
  }
55530
56448
 
55531
56449
  // src/commands/edr.ts
55532
- var import_node_fs74 = require("fs");
56450
+ var import_node_fs76 = require("fs");
55533
56451
  init_paths();
55534
56452
 
55535
56453
  // src/daemon/auditd/rules.ts
55536
- var import_node_fs73 = require("fs");
55537
- var import_node_child_process27 = require("child_process");
56454
+ var import_node_fs75 = require("fs");
56455
+ var import_node_child_process28 = require("child_process");
55538
56456
  var import_node_path56 = require("path");
55539
56457
  var WEB_TOOLS = ["sh", "bash", "dash", "zsh", "curl", "wget"];
55540
56458
  var MINER_NAMES = ["xmrig", "minerd", "cpuminer", "cpuminer-multi", "kdevtmpfsi", "kinsing", "cryptonight"];
@@ -55543,10 +56461,10 @@ var LISTEN_KEY2 = "threatcrush_edr_listen";
55543
56461
  function passwdByName() {
55544
56462
  let raw = "";
55545
56463
  try {
55546
- raw = (0, import_node_child_process27.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
56464
+ raw = (0, import_node_child_process28.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
55547
56465
  } catch {
55548
56466
  try {
55549
- raw = (0, import_node_fs73.readFileSync)("/etc/passwd", "utf8");
56467
+ raw = (0, import_node_fs75.readFileSync)("/etc/passwd", "utf8");
55550
56468
  } catch {
55551
56469
  return /* @__PURE__ */ new Map();
55552
56470
  }
@@ -55565,8 +56483,8 @@ function existingExecutables(names) {
55565
56483
  for (const prefix of ["/bin", "/usr/bin", "/usr/local/bin"]) {
55566
56484
  const candidate = `${prefix}/${name}`;
55567
56485
  try {
55568
- if (!(0, import_node_fs73.existsSync)(candidate) || !(0, import_node_fs73.statSync)(candidate).isFile()) continue;
55569
- paths.add((0, import_node_fs73.realpathSync)(candidate));
56486
+ if (!(0, import_node_fs75.existsSync)(candidate) || !(0, import_node_fs75.statSync)(candidate).isFile()) continue;
56487
+ paths.add((0, import_node_fs75.realpathSync)(candidate));
55570
56488
  } catch {
55571
56489
  }
55572
56490
  }
@@ -55577,7 +56495,7 @@ function existingDirectories(paths) {
55577
56495
  return [...new Set(paths)].filter((path2) => {
55578
56496
  if (!(0, import_node_path56.isAbsolute)(path2) || /[\s\r\n]/.test(path2)) return false;
55579
56497
  try {
55580
- return (0, import_node_fs73.statSync)(path2).isDirectory();
56498
+ return (0, import_node_fs75.statSync)(path2).isDirectory();
55581
56499
  } catch {
55582
56500
  return false;
55583
56501
  }
@@ -55638,8 +56556,8 @@ async function edrCommand(action = "status", opts = {}) {
55638
56556
  }
55639
56557
  let readable = false;
55640
56558
  try {
55641
- if ((0, import_node_fs74.existsSync)(settings.auditLogPath)) (0, import_node_fs74.accessSync)(settings.auditLogPath, import_node_fs74.constants.R_OK);
55642
- readable = (0, import_node_fs74.existsSync)(settings.auditLogPath);
56559
+ if ((0, import_node_fs76.existsSync)(settings.auditLogPath)) (0, import_node_fs76.accessSync)(settings.auditLogPath, import_node_fs76.constants.R_OK);
56560
+ readable = (0, import_node_fs76.existsSync)(settings.auditLogPath);
55643
56561
  } catch {
55644
56562
  }
55645
56563
  let events = [];
@@ -55825,7 +56743,7 @@ async function allowlistCommand(opts) {
55825
56743
  }
55826
56744
 
55827
56745
  // src/commands/abuse.ts
55828
- var import_node_fs75 = require("fs");
56746
+ var import_node_fs77 = require("fs");
55829
56747
  init_paths();
55830
56748
  function rows(records) {
55831
56749
  if (records.length === 0) {
@@ -55885,7 +56803,7 @@ function abuseRetractCommand(id, opts = {}) {
55885
56803
  );
55886
56804
  }
55887
56805
  function abuseStatusCommand(opts = {}) {
55888
- const config = loadConfig((0, import_node_fs75.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
56806
+ const config = loadConfig((0, import_node_fs77.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
55889
56807
  const cfg = resolveConfig(config.abuse_reporter);
55890
56808
  const hasKey2 = Boolean(cfg.keys.abuseipdb || cfg.keys.stopforumspam);
55891
56809
  const active2 = cfg.enabled && (cfg.dryRun || hasKey2);
@@ -55908,11 +56826,11 @@ function abuseStatusCommand(opts = {}) {
55908
56826
  init_paths();
55909
56827
 
55910
56828
  // src/upgrade.ts
55911
- var import_node_child_process28 = require("child_process");
56829
+ var import_node_child_process29 = require("child_process");
55912
56830
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
55913
56831
  var defaultRunner = (cmd) => {
55914
56832
  try {
55915
- return (0, import_node_child_process28.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
56833
+ return (0, import_node_child_process29.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
55916
56834
  } catch {
55917
56835
  return null;
55918
56836
  }
@@ -55945,9 +56863,9 @@ function globalListCommand(pm, pkgName) {
55945
56863
  };
55946
56864
  return lists[pm] ?? lists.npm;
55947
56865
  }
55948
- function globalHolders(pkgName, run2 = defaultRunner) {
56866
+ function globalHolders(pkgName, run3 = defaultRunner) {
55949
56867
  return PACKAGE_MANAGERS.filter((pm) => {
55950
- const out = run2(globalListCommand(pm, pkgName));
56868
+ const out = run3(globalListCommand(pm, pkgName));
55951
56869
  return typeof out === "string" && out.includes(pkgName);
55952
56870
  });
55953
56871
  }
@@ -55956,11 +56874,11 @@ function parseVersionOutput(output) {
55956
56874
  const match = output.match(/\d+\.\d+\.\d+[^\s]*/);
55957
56875
  return match ? match[0] : null;
55958
56876
  }
55959
- function activeCliVersion(bin = "threatcrush", run2 = defaultRunner) {
55960
- return parseVersionOutput(run2(`${bin} --version`));
56877
+ function activeCliVersion(bin = "threatcrush", run3 = defaultRunner) {
56878
+ return parseVersionOutput(run3(`${bin} --version`));
55961
56879
  }
55962
- function activeCliPath(bin = "threatcrush", run2 = defaultRunner) {
55963
- const out = run2(`command -v ${bin}`);
56880
+ function activeCliPath(bin = "threatcrush", run3 = defaultRunner) {
56881
+ const out = run3(`command -v ${bin}`);
55964
56882
  return out ? out.trim().split("\n")[0] || null : null;
55965
56883
  }
55966
56884
  async function latestPublishedVersion(pkgName, timeoutMs = 8e3) {
@@ -56053,8 +56971,8 @@ function installUserAgent(target = globalThis) {
56053
56971
  }
56054
56972
 
56055
56973
  // src/core/cloud-upload.ts
56056
- var import_node_child_process29 = require("child_process");
56057
- var import_node_os23 = require("os");
56974
+ var import_node_child_process30 = require("child_process");
56975
+ var import_node_os24 = require("os");
56058
56976
  var import_node_path57 = require("path");
56059
56977
  init_cli_config();
56060
56978
  function uploadDisabled(upload, env3 = process.env) {
@@ -56074,23 +56992,23 @@ function cleanUrl(raw) {
56074
56992
  return raw.split(/[?#]/)[0];
56075
56993
  }
56076
56994
  }
56077
- function repoTarget(path2, run2 = (args) => (0, import_node_child_process29.execFileSync)("git", args, { cwd: (0, import_node_path57.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
56995
+ function repoTarget(path2, run3 = (args) => (0, import_node_child_process30.execFileSync)("git", args, { cwd: (0, import_node_path57.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
56078
56996
  const abs = (0, import_node_path57.resolve)(path2);
56079
56997
  try {
56080
- const root = run2(["rev-parse", "--show-toplevel"]);
56998
+ const root = run3(["rev-parse", "--show-toplevel"]);
56081
56999
  const sub = abs === root ? "." : abs.slice(root.length + 1);
56082
57000
  let remote = "";
56083
57001
  try {
56084
- remote = run2(["remote", "get-url", "origin"]);
57002
+ remote = run3(["remote", "get-url", "origin"]);
56085
57003
  } catch {
56086
57004
  }
56087
57005
  if (remote) {
56088
57006
  const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)[:/](.+?)(?:\.git)?\/?$/i.exec(remote);
56089
57007
  if (m) return { target: `${m[1]}/${m[2]}`, root, sub };
56090
57008
  }
56091
- return { target: `${(0, import_node_os23.hostname)()}:${root}`, root, sub };
57009
+ return { target: `${(0, import_node_os24.hostname)()}:${root}`, root, sub };
56092
57010
  } catch {
56093
- return { target: `${(0, import_node_os23.hostname)()}:${abs}`, root: abs, sub: "." };
57011
+ return { target: `${(0, import_node_os24.hostname)()}:${abs}`, root: abs, sub: "." };
56094
57012
  }
56095
57013
  }
56096
57014
  async function uploadResult(result, opts) {
@@ -56447,25 +57365,25 @@ ${source_default.dim(" C R U S H")}
56447
57365
  var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
56448
57366
  var PKG_NAME2 = "@profullstack/threatcrush";
56449
57367
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
56450
- var INSTALL_CONFIG_PATH = (0, import_node_path58.join)((0, import_node_os24.homedir)(), ".threatcrush", "install.json");
56451
- function detectPackageManager() {
57368
+ var INSTALL_CONFIG_PATH = (0, import_node_path58.join)((0, import_node_os25.homedir)(), ".threatcrush", "install.json");
57369
+ function detectPackageManager2() {
56452
57370
  try {
56453
- const npmGlobal = (0, import_node_child_process30.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
57371
+ const npmGlobal = (0, import_node_child_process31.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
56454
57372
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
56455
57373
  } catch {
56456
57374
  }
56457
57375
  try {
56458
- (0, import_node_child_process30.execSync)("pnpm --version", { stdio: "pipe" });
57376
+ (0, import_node_child_process31.execSync)("pnpm --version", { stdio: "pipe" });
56459
57377
  return "pnpm";
56460
57378
  } catch {
56461
57379
  }
56462
57380
  try {
56463
- (0, import_node_child_process30.execSync)("yarn --version", { stdio: "pipe" });
57381
+ (0, import_node_child_process31.execSync)("yarn --version", { stdio: "pipe" });
56464
57382
  return "yarn";
56465
57383
  } catch {
56466
57384
  }
56467
57385
  try {
56468
- (0, import_node_child_process30.execSync)("bun --version", { stdio: "pipe" });
57386
+ (0, import_node_child_process31.execSync)("bun --version", { stdio: "pipe" });
56469
57387
  return "bun";
56470
57388
  } catch {
56471
57389
  }
@@ -56473,14 +57391,14 @@ function detectPackageManager() {
56473
57391
  }
56474
57392
  function readInstallConfig() {
56475
57393
  try {
56476
- return JSON.parse((0, import_node_fs76.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
57394
+ return JSON.parse((0, import_node_fs78.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
56477
57395
  } catch {
56478
57396
  return {};
56479
57397
  }
56480
57398
  }
56481
57399
  function packageLooksInstalled(pm, pkgName) {
56482
57400
  try {
56483
- const output = (0, import_node_child_process30.execSync)(globalListCommand(pm, pkgName), {
57401
+ const output = (0, import_node_child_process31.execSync)(globalListCommand(pm, pkgName), {
56484
57402
  encoding: "utf-8",
56485
57403
  stdio: ["pipe", "pipe", "pipe"]
56486
57404
  });
@@ -56491,7 +57409,7 @@ function packageLooksInstalled(pm, pkgName) {
56491
57409
  }
56492
57410
  function upgradeCommands(pkgName) {
56493
57411
  const holders = globalHolders(pkgName);
56494
- const targets = holders.length > 0 ? holders : [detectPackageManager()];
57412
+ const targets = holders.length > 0 ? holders : [detectPackageManager2()];
56495
57413
  return targets.map((pm) => globalInstallCommand(pm, pkgName, "update"));
56496
57414
  }
56497
57415
  async function reportIfStillStale() {
@@ -56583,14 +57501,14 @@ async function promoteUnprivilegedDaemon() {
56583
57501
  function restartSystemdDaemon() {
56584
57502
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
56585
57503
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
56586
- if (!asRoot && (0, import_node_child_process30.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
57504
+ if (!asRoot && (0, import_node_child_process31.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
56587
57505
  const [cmd, ...args] = argv;
56588
- if ((0, import_node_child_process30.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
56589
- return (0, import_node_child_process30.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
57506
+ if ((0, import_node_child_process31.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
57507
+ return (0, import_node_child_process31.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
56590
57508
  }
56591
57509
  function execQuiet(cmd) {
56592
57510
  try {
56593
- return (0, import_node_child_process30.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
57511
+ return (0, import_node_child_process31.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
56594
57512
  } catch {
56595
57513
  return null;
56596
57514
  }
@@ -56613,6 +57531,7 @@ ${source_default.dim("Examples:")}
56613
57531
  ${source_default.green("$")} threatcrush map ${source_default.dim("# Live map of where attacks come from")}
56614
57532
  ${source_default.green("$")} threatcrush watchdog ${source_default.dim("# Triage logged attacks: hole or not?")}
56615
57533
  ${source_default.green("$")} threatcrush scan ./src ${source_default.dim("# Scan code for vulns")}
57534
+ ${source_default.green("$")} sudo threatcrush scan --host ${source_default.dim("# Rootkit / host integrity scan of this machine")}
56616
57535
  ${source_default.green("$")} threatcrush pentest URL ${source_default.dim("# Quick web checks on a URL")}
56617
57536
  ${source_default.green("$")} threatcrush ai-scan URL ${source_default.dim("# Red-team your AI/LLM endpoint (OWASP LLM Top 10)")}
56618
57537
  ${source_default.green("$")} threatcrush modules install ${source_default.dim("# Install a module")}
@@ -56703,7 +57622,7 @@ program2.command("logout").description("Clear stored threatcrush.com credentials
56703
57622
  program2.command("whoami").description("Show the currently logged-in threatcrush.com account").action(async () => {
56704
57623
  await whoamiCommand();
56705
57624
  });
56706
- program2.command("scan").description("Scan codebase for vulnerabilities and secrets").argument("[path]", "Path to scan", ".").option("-f, --format <format>", "output format: text, json, or sarif", "text").option("-o, --output <file>", "write json/sarif output to a file instead of stdout").option(
57625
+ program2.command("scan").description("Scan codebase for vulnerabilities and secrets; --host scans this machine for rootkits and tampering instead").argument("[path]", "Path to scan", ".").option("--host", "scan this machine instead of code: package integrity, rkhunter/chkrootkit, hidden processes and modules, ld.so.preload, SSH keys, Docker, persistence, SUID (same as `threatcrush host-scan`)").option("--localhost", "alias for --host").option("--json", "(--host) machine-readable JSON").option("--since <duration>", "(--host) window for recently changed persistence files", "7d").option("--deny-keys <file>", "(--host) SSH keys that must not be authorized anywhere (public key lines, base64 blobs or SHA256: fingerprints)").option("--checks <ids>", "(--host) run only these checks (comma-separated)").option("--skip-checks <ids>", "(--host) skip these checks (comma-separated)").option("-f, --format <format>", "output format: text, json, or sarif", "text").option("-o, --output <file>", "write json/sarif output to a file instead of stdout").option(
56707
57626
  "--fail-on <severities>",
56708
57627
  "exit 1 when a finding at or above any of these exists (comma-separated: critical,high,medium,low,info)"
56709
57628
  ).option(
@@ -56718,6 +57637,17 @@ program2.command("scan").description("Scan codebase for vulnerabilities and secr
56718
57637
  "--missing-controls",
56719
57638
  "also report security controls the tree shows no evidence of (headers, CSRF, rate limiting, body size limits)"
56720
57639
  ).option("-v, --verbose", "list the paths that could not be read").option("--no-upload", "do not save the results to your threatcrush.com org (also THREATCRUSH_UPLOAD=0)").action(async (targetPath, opts) => {
57640
+ if (opts.host || opts.localhost) {
57641
+ await hostScanCommand({
57642
+ json: opts.json || (opts.format ?? "").toLowerCase() === "json",
57643
+ since: opts.since,
57644
+ denyKeys: opts.denyKeys,
57645
+ checks: opts.checks,
57646
+ skipChecks: opts.skipChecks,
57647
+ output: opts.output
57648
+ });
57649
+ return;
57650
+ }
56721
57651
  const format2 = (opts.format ?? "text").toLowerCase();
56722
57652
  if (!["text", "json", "sarif"].includes(format2)) {
56723
57653
  console.error(source_default.red(`Unknown --format "${opts.format}" (expected text, json, or sarif)`));
@@ -56751,6 +57681,9 @@ program2.command("scan").description("Scan codebase for vulnerabilities and secr
56751
57681
  await uploadResult(result, { source: "scan", target: repo.target, kind: "repo", scope, upload: opts.upload, machineReadable: format2 !== "text" });
56752
57682
  }
56753
57683
  });
57684
+ program2.command("host-scan").description("Host integrity / rootkit scan of this machine (exit 1 on any fail); run as root for every check").option("--json", "machine-readable JSON").option("--since <duration>", "window for recently changed persistence files (e.g. 7d, 12h)", "7d").option("--deny-keys <file>", "SSH keys that must not be authorized anywhere (public key lines, base64 blobs or SHA256: fingerprints)").option("--checks <ids>", "run only these checks (comma-separated)").option("--skip-checks <ids>", "skip these checks (comma-separated)").option("-o, --output <file>", "also write the report to a file").action(async (opts) => {
57685
+ await hostScanCommand(opts);
57686
+ });
56754
57687
  var av = program2.command("av").alias("antivirus").description("CrushAV: free open-source antivirus (heuristics + ClamAV + hash reputation), Windows/macOS/Linux");
56755
57688
  av.command("scan").description("Scan files or folders for malware; no paths = quick scan of downloads, desktop, temp and startup items").argument("[paths...]", "files or folders to scan").option("--full", "scan the whole home folder plus system startup and temp locations").option("--no-clamav", "do not use ClamAV even when it is installed").option("--require-clamav", "fail if ClamAV is not installed").option("--offline", "do not send file hashes to threatcrush.com for reputation lookups").option("--quarantine", "move malware into quarantine (reversible with `av quarantine restore`)").option("--max-size <mb>", "skip files larger than this many MB (default 1024)").option("-j, --jobs <n>", "files scanned in parallel worker threads (default: one per CPU core)").option("--json", "emit JSON").action(async (paths, opts) => {
56756
57689
  await avScanCommand(paths, opts);
@@ -56904,7 +57837,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
56904
57837
  program2.command("logs").description("Tail daemon logs").action(async () => {
56905
57838
  console.log(LOGO2);
56906
57839
  const logPath2 = PATHS.logFile;
56907
- if (!(0, import_node_fs76.existsSync)(logPath2)) {
57840
+ if (!(0, import_node_fs78.existsSync)(logPath2)) {
56908
57841
  console.log(source_default.yellow(` No log file found at ${logPath2}`));
56909
57842
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
56910
57843
  return;
@@ -56912,7 +57845,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
56912
57845
  console.log(source_default.green(` Tailing ${logPath2}...
56913
57846
  `));
56914
57847
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
56915
- (0, import_node_child_process30.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
57848
+ (0, import_node_child_process31.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
56916
57849
  });
56917
57850
  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) => {
56918
57851
  console.log(LOGO2);
@@ -56924,7 +57857,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
56924
57857
  for (const cmd of commands2) {
56925
57858
  console.log(source_default.green(` \u2192 ${cmd}
56926
57859
  `));
56927
- (0, import_node_child_process30.execSync)(cmd, { stdio: "inherit" });
57860
+ (0, import_node_child_process31.execSync)(cmd, { stdio: "inherit" });
56928
57861
  }
56929
57862
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
56930
57863
  await reportIfStillStale();
@@ -56940,7 +57873,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
56940
57873
  const holders = globalHolders(PKG_NAME2);
56941
57874
  const installConfig = readInstallConfig();
56942
57875
  const installMode = opts.cli ? "server" : opts.desktop ? "desktop" : installConfig.installMode || "server";
56943
- console.log(source_default.dim(` Detected package manager: ${holders.join(", ") || detectPackageManager()}`));
57876
+ console.log(source_default.dim(` Detected package manager: ${holders.join(", ") || detectPackageManager2()}`));
56944
57877
  console.log(source_default.dim(` Install mode: ${installMode}`));
56945
57878
  console.log(source_default.dim(` Current version: ${PKG_VERSION}
56946
57879
  `));
@@ -56949,7 +57882,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
56949
57882
  for (const cmd of commands) {
56950
57883
  console.log(source_default.green(` \u2192 ${cmd}
56951
57884
  `));
56952
- (0, import_node_child_process30.execSync)(cmd, { stdio: "inherit" });
57885
+ (0, import_node_child_process31.execSync)(cmd, { stdio: "inherit" });
56953
57886
  }
56954
57887
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
56955
57888
  if (installMode === "desktop") {
@@ -56985,7 +57918,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
56985
57918
  const installConfig = readInstallConfig();
56986
57919
  const installMode = installConfig.installMode || "server";
56987
57920
  const holders = globalHolders(PKG_NAME2);
56988
- const pms = holders.length > 0 ? holders : [detectPackageManager()];
57921
+ const pms = holders.length > 0 ? holders : [detectPackageManager2()];
56989
57922
  const commands = pms.map((pm) => globalInstallCommand(pm, PKG_NAME2, "remove"));
56990
57923
  for (const pm of pms) {
56991
57924
  if (installMode === "desktop" && packageLooksInstalled(pm, DESKTOP_PKG_NAME)) {
@@ -57000,7 +57933,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
57000
57933
  for (const cmd of commands) {
57001
57934
  console.log(source_default.green(` \u2192 ${cmd}
57002
57935
  `));
57003
- (0, import_node_child_process30.execSync)(cmd, { stdio: "inherit" });
57936
+ (0, import_node_child_process31.execSync)(cmd, { stdio: "inherit" });
57004
57937
  }
57005
57938
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
57006
57939
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -57077,10 +58010,10 @@ storeCmd.command("search <query>").description("Search for modules in the store"
57077
58010
  });
57078
58011
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
57079
58012
  console.log(LOGO2);
57080
- const configPath = (0, import_node_path58.join)((0, import_node_os24.homedir)(), ".threatcrush", "config.json");
58013
+ const configPath = (0, import_node_path58.join)((0, import_node_os25.homedir)(), ".threatcrush", "config.json");
57081
58014
  let email = "";
57082
58015
  try {
57083
- const config = JSON.parse((0, import_node_fs76.readFileSync)(configPath, "utf-8"));
58016
+ const config = JSON.parse((0, import_node_fs78.readFileSync)(configPath, "utf-8"));
57084
58017
  email = config.email || "";
57085
58018
  } catch {
57086
58019
  }
@@ -57097,9 +58030,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
57097
58030
  return;
57098
58031
  }
57099
58032
  try {
57100
- const dir = (0, import_node_path58.join)((0, import_node_os24.homedir)(), ".threatcrush");
57101
- if (!(0, import_node_fs76.existsSync)(dir)) (0, import_node_fs76.mkdirSync)(dir, { recursive: true });
57102
- (0, import_node_fs76.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
58033
+ const dir = (0, import_node_path58.join)((0, import_node_os25.homedir)(), ".threatcrush");
58034
+ if (!(0, import_node_fs78.existsSync)(dir)) (0, import_node_fs78.mkdirSync)(dir, { recursive: true });
58035
+ (0, import_node_fs78.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
57103
58036
  console.log(source_default.dim(` Saved email to ${configPath}`));
57104
58037
  } catch {
57105
58038
  }