@profullstack/threatcrush 0.13.69 → 0.13.71

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
@@ -1655,20 +1655,20 @@ var require_parse_async = __commonJS({
1655
1655
  const index = 0;
1656
1656
  const blocksize = opts.blocksize || 40960;
1657
1657
  const parser = new TOMLParser();
1658
- return new Promise((resolve8, reject) => {
1659
- setImmediate(parseAsyncNext, index, blocksize, resolve8, reject);
1658
+ return new Promise((resolve9, reject) => {
1659
+ setImmediate(parseAsyncNext, index, blocksize, resolve9, reject);
1660
1660
  });
1661
- function parseAsyncNext(index2, blocksize2, resolve8, reject) {
1661
+ function parseAsyncNext(index2, blocksize2, resolve9, reject) {
1662
1662
  if (index2 >= str3.length) {
1663
1663
  try {
1664
- return resolve8(parser.finish());
1664
+ return resolve9(parser.finish());
1665
1665
  } catch (err) {
1666
1666
  return reject(prettyError(err, str3));
1667
1667
  }
1668
1668
  }
1669
1669
  try {
1670
1670
  parser.parse(str3.slice(index2, index2 + blocksize2));
1671
- setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve8, reject);
1671
+ setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve9, reject);
1672
1672
  } catch (err) {
1673
1673
  reject(prettyError(err, str3));
1674
1674
  }
@@ -1694,7 +1694,7 @@ var require_parse_stream = __commonJS({
1694
1694
  function parseReadable(stm) {
1695
1695
  const parser = new TOMLParser();
1696
1696
  stm.setEncoding("utf8");
1697
- return new Promise((resolve8, reject) => {
1697
+ return new Promise((resolve9, reject) => {
1698
1698
  let readable;
1699
1699
  let ended = false;
1700
1700
  let errored = false;
@@ -1702,7 +1702,7 @@ var require_parse_stream = __commonJS({
1702
1702
  ended = true;
1703
1703
  if (readable) return;
1704
1704
  try {
1705
- resolve8(parser.finish());
1705
+ resolve9(parser.finish());
1706
1706
  } catch (err) {
1707
1707
  reject(err);
1708
1708
  }
@@ -16764,8 +16764,8 @@ var init_app = __esm({
16764
16764
  this.frame();
16765
16765
  }, interval);
16766
16766
  this.timer.unref?.();
16767
- await new Promise((resolve8) => {
16768
- this.exitResolve = resolve8;
16767
+ await new Promise((resolve9) => {
16768
+ this.exitResolve = resolve9;
16769
16769
  });
16770
16770
  }
16771
16771
  targetFps() {
@@ -17238,7 +17238,7 @@ var init_ipc_client = __esm({
17238
17238
  if (!(0, import_node_fs8.existsSync)(this.socketPath)) {
17239
17239
  throw new Error(`threatcrushd socket not found at ${this.socketPath}`);
17240
17240
  }
17241
- return new Promise((resolve8, reject) => {
17241
+ return new Promise((resolve9, reject) => {
17242
17242
  const sock = (0, import_node_net2.createConnection)(this.socketPath);
17243
17243
  const timer = setTimeout(() => {
17244
17244
  sock.destroy();
@@ -17251,7 +17251,7 @@ var init_ipc_client = __esm({
17251
17251
  sock.on("data", (chunk2) => this.onData(chunk2.toString()));
17252
17252
  sock.on("close", () => this.onClose());
17253
17253
  sock.on("error", () => this.onClose());
17254
- resolve8();
17254
+ resolve9();
17255
17255
  });
17256
17256
  sock.once("error", (err) => {
17257
17257
  clearTimeout(timer);
@@ -17267,14 +17267,14 @@ var init_ipc_client = __esm({
17267
17267
  if (!this.socket) throw new Error("not connected");
17268
17268
  const id = this.nextId++;
17269
17269
  const frame = params ? { id, method, params } : { id, method };
17270
- return new Promise((resolve8, reject) => {
17270
+ return new Promise((resolve9, reject) => {
17271
17271
  const timer = setTimeout(() => {
17272
17272
  this.pending.delete(id);
17273
17273
  reject(new Error(
17274
17274
  `threatcrushd did not answer "${method}" within ${REQUEST_TIMEOUT_MS / 1e3}s; if it is older than this CLI, update it`
17275
17275
  ));
17276
17276
  }, REQUEST_TIMEOUT_MS);
17277
- this.pending.set(id, { resolve: resolve8, reject, timer });
17277
+ this.pending.set(id, { resolve: resolve9, reject, timer });
17278
17278
  this.socket.write(JSON.stringify(frame) + "\n", (err) => {
17279
17279
  if (err && this.pending.delete(id)) {
17280
17280
  clearTimeout(timer);
@@ -21992,10 +21992,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
21992
21992
  _executeSubCommand(subcommand, args) {
21993
21993
  args = args.slice();
21994
21994
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
21995
- function findFile(baseDir, baseName) {
21996
- const localBin = import_node_path.default.resolve(baseDir, baseName);
21995
+ function findFile(baseDir, baseName2) {
21996
+ const localBin = import_node_path.default.resolve(baseDir, baseName2);
21997
21997
  if (import_node_fs.default.existsSync(localBin)) return localBin;
21998
- if (sourceExt.includes(import_node_path.default.extname(baseName))) return void 0;
21998
+ if (sourceExt.includes(import_node_path.default.extname(baseName2))) return void 0;
21999
21999
  const foundExt = sourceExt.find(
22000
22000
  (ext) => import_node_fs.default.existsSync(`${localBin}${ext}`)
22001
22001
  );
@@ -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_process28 = require("child_process");
23790
- var import_node_fs68 = require("fs");
23791
- var import_node_path51 = require("path");
23792
- var import_node_os19 = require("os");
23789
+ var import_node_child_process29 = require("child_process");
23790
+ var import_node_fs74 = require("fs");
23791
+ var import_node_path57 = require("path");
23792
+ var import_node_os23 = require("os");
23793
23793
 
23794
23794
  // src/commands/monitor.ts
23795
23795
  var import_node_fs11 = require("fs");
@@ -36811,18 +36811,18 @@ function isComment(line2) {
36811
36811
  }
36812
36812
  function proseLines(lines) {
36813
36813
  const inside = /* @__PURE__ */ new Set();
36814
- let delimiter = null;
36814
+ let delimiter2 = null;
36815
36815
  lines.forEach((line2, index) => {
36816
- if (delimiter) {
36816
+ if (delimiter2) {
36817
36817
  inside.add(index);
36818
- if (line2.includes(delimiter)) delimiter = null;
36818
+ if (line2.includes(delimiter2)) delimiter2 = null;
36819
36819
  return;
36820
36820
  }
36821
36821
  for (const candidate of ['"""', "'''"]) {
36822
36822
  const start = line2.indexOf(candidate);
36823
36823
  if (start === -1) continue;
36824
36824
  if (line2.indexOf(candidate, start + candidate.length) !== -1) return;
36825
- delimiter = candidate;
36825
+ delimiter2 = candidate;
36826
36826
  inside.add(index);
36827
36827
  return;
36828
36828
  }
@@ -39145,8 +39145,8 @@ function askPiped(question, mask) {
39145
39145
  if (reader.lines.length > 0) return Promise.resolve(settle2(reader.lines.shift()));
39146
39146
  if (reader.ended) return Promise.resolve(settle2(null));
39147
39147
  reader.rl.resume();
39148
- return new Promise((resolve8) => {
39149
- reader.waiting = (line2) => resolve8(settle2(line2));
39148
+ return new Promise((resolve9) => {
39149
+ reader.waiting = (line2) => resolve9(settle2(line2));
39150
39150
  });
39151
39151
  }
39152
39152
  function askTerminal(question, mask) {
@@ -39154,20 +39154,20 @@ function askTerminal(question, mask) {
39154
39154
  cb();
39155
39155
  } }) : process.stdout;
39156
39156
  const rl = import_node_readline.default.createInterface({ input: process.stdin, output, terminal: true });
39157
- return new Promise((resolve8) => {
39157
+ return new Promise((resolve9) => {
39158
39158
  let settled = false;
39159
39159
  rl.on("close", () => {
39160
39160
  if (settled) return;
39161
39161
  settled = true;
39162
39162
  process.stdout.write("\n");
39163
- resolve8(null);
39163
+ resolve9(null);
39164
39164
  });
39165
39165
  if (mask) process.stdout.write(question);
39166
39166
  rl.question(mask ? "" : question, (answer) => {
39167
39167
  settled = true;
39168
39168
  rl.close();
39169
39169
  if (mask) process.stdout.write("\n");
39170
- resolve8(answer);
39170
+ resolve9(answer);
39171
39171
  });
39172
39172
  });
39173
39173
  }
@@ -39205,7 +39205,7 @@ async function startLinkLogin(pkce, deviceName = (0, import_node_os8.hostname)()
39205
39205
  }
39206
39206
  return data;
39207
39207
  }
39208
- var sleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
39208
+ var sleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
39209
39209
  async function waitForApproval(request, pkce, opts = {}) {
39210
39210
  const wait = opts.sleepMs ?? sleep;
39211
39211
  const now = opts.now ?? Date.now;
@@ -40794,8 +40794,1391 @@ async function pentestCommand(targetUrl) {
40794
40794
  };
40795
40795
  }
40796
40796
 
40797
- // src/commands/ai-scan.ts
40797
+ // src/commands/av.ts
40798
+ var import_node_fs27 = require("fs");
40799
+ var import_node_os12 = require("os");
40800
+ var import_node_path24 = require("path");
40801
+
40802
+ // ../../packages/av/src/sha256.ts
40803
+ var K = new Uint32Array([
40804
+ 1116352408,
40805
+ 1899447441,
40806
+ 3049323471,
40807
+ 3921009573,
40808
+ 961987163,
40809
+ 1508970993,
40810
+ 2453635748,
40811
+ 2870763221,
40812
+ 3624381080,
40813
+ 310598401,
40814
+ 607225278,
40815
+ 1426881987,
40816
+ 1925078388,
40817
+ 2162078206,
40818
+ 2614888103,
40819
+ 3248222580,
40820
+ 3835390401,
40821
+ 4022224774,
40822
+ 264347078,
40823
+ 604807628,
40824
+ 770255983,
40825
+ 1249150122,
40826
+ 1555081692,
40827
+ 1996064986,
40828
+ 2554220882,
40829
+ 2821834349,
40830
+ 2952996808,
40831
+ 3210313671,
40832
+ 3336571891,
40833
+ 3584528711,
40834
+ 113926993,
40835
+ 338241895,
40836
+ 666307205,
40837
+ 773529912,
40838
+ 1294757372,
40839
+ 1396182291,
40840
+ 1695183700,
40841
+ 1986661051,
40842
+ 2177026350,
40843
+ 2456956037,
40844
+ 2730485921,
40845
+ 2820302411,
40846
+ 3259730800,
40847
+ 3345764771,
40848
+ 3516065817,
40849
+ 3600352804,
40850
+ 4094571909,
40851
+ 275423344,
40852
+ 430227734,
40853
+ 506948616,
40854
+ 659060556,
40855
+ 883997877,
40856
+ 958139571,
40857
+ 1322822218,
40858
+ 1537002063,
40859
+ 1747873779,
40860
+ 1955562222,
40861
+ 2024104815,
40862
+ 2227730452,
40863
+ 2361852424,
40864
+ 2428436474,
40865
+ 2756734187,
40866
+ 3204031479,
40867
+ 3329325298
40868
+ ]);
40869
+ var Sha256 = class {
40870
+ h = new Uint32Array([
40871
+ 1779033703,
40872
+ 3144134277,
40873
+ 1013904242,
40874
+ 2773480762,
40875
+ 1359893119,
40876
+ 2600822924,
40877
+ 528734635,
40878
+ 1541459225
40879
+ ]);
40880
+ block = new Uint8Array(64);
40881
+ blockLen = 0;
40882
+ total = 0;
40883
+ w = new Uint32Array(64);
40884
+ update(data) {
40885
+ let i = 0;
40886
+ this.total += data.length;
40887
+ if (this.blockLen > 0) {
40888
+ const take = Math.min(64 - this.blockLen, data.length);
40889
+ this.block.set(data.subarray(0, take), this.blockLen);
40890
+ this.blockLen += take;
40891
+ i = take;
40892
+ if (this.blockLen === 64) {
40893
+ this.compress(this.block, 0);
40894
+ this.blockLen = 0;
40895
+ }
40896
+ }
40897
+ for (; i + 64 <= data.length; i += 64) this.compress(data, i);
40898
+ if (i < data.length) {
40899
+ this.block.set(data.subarray(i), 0);
40900
+ this.blockLen = data.length - i;
40901
+ }
40902
+ return this;
40903
+ }
40904
+ hex() {
40905
+ const bitLen = this.total * 8;
40906
+ const pad = new Uint8Array((this.blockLen < 56 ? 56 : 120) - this.blockLen + 8);
40907
+ pad[0] = 128;
40908
+ const hi = Math.floor(bitLen / 4294967296);
40909
+ const lo = bitLen >>> 0;
40910
+ const n = pad.length;
40911
+ pad[n - 8] = hi >>> 24;
40912
+ pad[n - 7] = hi >>> 16;
40913
+ pad[n - 6] = hi >>> 8;
40914
+ pad[n - 5] = hi;
40915
+ pad[n - 4] = lo >>> 24;
40916
+ pad[n - 3] = lo >>> 16;
40917
+ pad[n - 2] = lo >>> 8;
40918
+ pad[n - 1] = lo;
40919
+ this.total -= pad.length;
40920
+ this.update(pad);
40921
+ let out = "";
40922
+ for (const v of this.h) out += v.toString(16).padStart(8, "0");
40923
+ return out;
40924
+ }
40925
+ compress(d, o) {
40926
+ const w = this.w;
40927
+ for (let t = 0; t < 16; t++) {
40928
+ const j = o + t * 4;
40929
+ w[t] = d[j] << 24 | d[j + 1] << 16 | d[j + 2] << 8 | d[j + 3];
40930
+ }
40931
+ for (let t = 16; t < 64; t++) {
40932
+ const a2 = w[t - 15], b2 = w[t - 2];
40933
+ const s0 = (a2 >>> 7 | a2 << 25) ^ (a2 >>> 18 | a2 << 14) ^ a2 >>> 3;
40934
+ const s1 = (b2 >>> 17 | b2 << 15) ^ (b2 >>> 19 | b2 << 13) ^ b2 >>> 10;
40935
+ w[t] = w[t - 16] + s0 + w[t - 7] + s1 | 0;
40936
+ }
40937
+ let [a, b, c, dd, e, f, g, h] = this.h;
40938
+ for (let t = 0; t < 64; t++) {
40939
+ const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
40940
+ const ch = e & f ^ ~e & g;
40941
+ const t1 = h + S1 + ch + K[t] + w[t] | 0;
40942
+ const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
40943
+ const maj = a & b ^ a & c ^ b & c;
40944
+ const t2 = S0 + maj | 0;
40945
+ h = g;
40946
+ g = f;
40947
+ f = e;
40948
+ e = dd + t1 | 0;
40949
+ dd = c;
40950
+ c = b;
40951
+ b = a;
40952
+ a = t1 + t2 | 0;
40953
+ }
40954
+ const H = this.h;
40955
+ H[0] += a;
40956
+ H[1] += b;
40957
+ H[2] += c;
40958
+ H[3] += dd;
40959
+ H[4] += e;
40960
+ H[5] += f;
40961
+ H[6] += g;
40962
+ H[7] += h;
40963
+ }
40964
+ };
40965
+ async function sha256Hex(bytes) {
40966
+ const subtle = globalThis.crypto?.subtle;
40967
+ if (subtle) {
40968
+ try {
40969
+ const buf = await subtle.digest("SHA-256", bytes);
40970
+ return Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
40971
+ } catch {
40972
+ }
40973
+ }
40974
+ return new Sha256().update(bytes).hex();
40975
+ }
40976
+ var SHA256_RE = /^[0-9a-f]{64}$/;
40977
+
40978
+ // ../../packages/av/src/magic.ts
40979
+ var starts = (b, sig, at = 0) => b.length >= at + sig.length && sig.every((v, i) => b[at + i] === v);
40980
+ function sniffKind(b) {
40981
+ if (starts(b, [77, 90])) return "pe";
40982
+ if (starts(b, [127, 69, 76, 70])) return "elf";
40983
+ if (starts(b, [254, 237, 250, 206]) || starts(b, [254, 237, 250, 207]) || starts(b, [206, 250, 237, 254]) || starts(b, [207, 250, 237, 254])) return "macho";
40984
+ if (starts(b, [202, 254, 186, 190]) && b.length >= 8 && b[4] === 0 && b[5] === 0 && b[6] === 0 && b[7] > 0 && b[7] < 20) return "macho";
40985
+ if (starts(b, [80, 75, 3, 4]) || starts(b, [80, 75, 5, 6])) return "zip";
40986
+ if (starts(b, [208, 207, 17, 224, 161, 177, 26, 225])) return "ole";
40987
+ if (starts(b, [37, 80, 68, 70, 45])) return "pdf";
40988
+ if (starts(b, [76, 0, 0, 0, 1, 20, 2, 0])) return "lnk";
40989
+ if (starts(b, [123, 92, 114, 116, 102])) return "rtf";
40990
+ if (starts(b, [100, 101, 120, 10])) return "dex";
40991
+ if (starts(b, [35, 33])) return "script";
40992
+ if (starts(b, [255, 216, 255]) || starts(b, [137, 80, 78, 71]) || starts(b, [71, 73, 70, 56]) || starts(b, [82, 73, 70, 70]) && starts(b, [87, 69, 66, 80], 8) || starts(b, [66, 77])) return "image";
40993
+ if (starts(b, [102, 116, 121, 112], 4) || starts(b, [73, 68, 51]) || starts(b, [26, 69, 223, 163]) || starts(b, [79, 103, 103, 83]) || starts(b, [102, 76, 97, 67])) return "media";
40994
+ if (starts(b, [31, 139]) || starts(b, [82, 97, 114, 33]) || starts(b, [55, 122, 188, 175]) || starts(b, [253, 55, 122, 88, 90]) || starts(b, [40, 181, 47, 253])) return "archive";
40995
+ if (looksLikeText(b)) return "text";
40996
+ return "unknown";
40997
+ }
40998
+ function looksLikeText(b) {
40999
+ const n = Math.min(b.length, 4096);
41000
+ if (n === 0) return true;
41001
+ let odd = 0;
41002
+ for (let i = 0; i < n; i++) {
41003
+ const c = b[i];
41004
+ if (c === 0) return false;
41005
+ if (c < 9 || c > 13 && c < 32) odd++;
41006
+ }
41007
+ return odd / n < 0.05;
41008
+ }
41009
+ var EXECUTABLE_KINDS = /* @__PURE__ */ new Set(["pe", "elf", "macho"]);
41010
+ var DOCUMENT_EXTENSIONS = /* @__PURE__ */ new Set([
41011
+ "pdf",
41012
+ "doc",
41013
+ "docx",
41014
+ "xls",
41015
+ "xlsx",
41016
+ "ppt",
41017
+ "pptx",
41018
+ "odt",
41019
+ "ods",
41020
+ "txt",
41021
+ "rtf",
41022
+ "csv",
41023
+ "jpg",
41024
+ "jpeg",
41025
+ "png",
41026
+ "gif",
41027
+ "bmp",
41028
+ "webp",
41029
+ "heic",
41030
+ "svg",
41031
+ "mp3",
41032
+ "mp4",
41033
+ "mov",
41034
+ "avi",
41035
+ "mkv",
41036
+ "wav",
41037
+ "m4a"
41038
+ ]);
41039
+ function extOf(name) {
41040
+ const base = name.split(/[\\/]/).pop() ?? name;
41041
+ const dot = base.lastIndexOf(".");
41042
+ return dot > 0 ? base.slice(dot + 1).toLowerCase() : "";
41043
+ }
41044
+ function baseName(name) {
41045
+ return name.split(/[\\/]/).pop() ?? name;
41046
+ }
41047
+
41048
+ // ../../packages/av/src/rules.ts
41049
+ var EICAR = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*";
41050
+ var SCRIPT_EXTS = /* @__PURE__ */ new Set(["ps1", "psm1", "bat", "cmd", "vbs", "vbe", "js", "jse", "wsf", "hta", "sh", "bash", "zsh", "py", "pl", "rb", "php", "command", "applescript", "scpt"]);
41051
+ var WIN_SCRIPT_EXTS = /* @__PURE__ */ new Set(["js", "jse", "vbs", "vbe", "wsf", "hta"]);
41052
+ var WEB_EXTS = /* @__PURE__ */ new Set(["html", "htm", "shtml", "xhtml", "svg", "hta"]);
41053
+ var SERVER_SCRIPT_EXTS = /* @__PURE__ */ new Set(["php", "phtml", "php3", "php4", "php5", "php7", "phar", "asp", "aspx", "ashx", "jsp", "jspx"]);
41054
+ var isScript = (c) => c.kind === "script" || SCRIPT_EXTS.has(c.ext);
41055
+ var POWERSHELL_HOST_EXTS = /* @__PURE__ */ new Set(["ps1", "psm1", "bat", "cmd", "vbs", "vbe", "wsf", "hta"]);
41056
+ var isWindowsScriptContext = (c) => POWERSHELL_HOST_EXTS.has(c.ext) || c.kind === "lnk" || ["js", "jse"].includes(c.ext) && /ActiveXObject|WScript\.|GetObject\(\s*["']winmgmts/i.test(c.text);
41057
+ var NON_RUNNABLE_SOURCE_EXTS = /* @__PURE__ */ new Set(["ts", "tsx", "mts", "cts", "md", "markdown", "rst", "go", "rs", "c", "h", "cc", "cpp", "hpp", "java", "kt", "cs", "swift", "scala"]);
41058
+ var NOTE_EXTS = /* @__PURE__ */ new Set(["txt", "html", "htm", "hta", "rtf", ""]);
41059
+ var allText = (c) => c.wide ? `${c.text}
41060
+ ${c.wide}` : c.text;
41061
+ var RANSOM_COMMANDS = [
41062
+ /vssadmin(?:\.exe)?["']?\s+delete\s+shadows/i,
41063
+ /wmic(?:\.exe)?["']?\s+shadowcopy\s+delete/i,
41064
+ /wbadmin(?:\.exe)?["']?\s+delete\s+(?:catalog|backup|systemstatebackup)/i,
41065
+ /bcdedit(?:\.exe)?["']?\s+\/set\s+\{default\}\s+(?:recoveryenabled\s+no|bootstatuspolicy\s+ignoreallfailures)/i,
41066
+ /Get-WmiObject\s+Win32_Shadowcopy\s*\|\s*ForEach-Object\s*\{\s*\$_\.Delete\(\)/i
41067
+ ];
41068
+ var RULES = [
41069
+ {
41070
+ id: "CrushAV.Test.EICAR",
41071
+ name: "EICAR test file",
41072
+ severity: "low",
41073
+ impact: "malicious",
41074
+ description: "The industry-standard harmless antivirus test file. It cannot do anything; it only proves the scanner works.",
41075
+ test: (c) => c.size <= 128 && c.text.trimStart().startsWith(EICAR)
41076
+ },
41077
+ {
41078
+ id: "CrushAV.Disguise.ExecutableAsDocument",
41079
+ name: "Program disguised as a document",
41080
+ severity: "high",
41081
+ impact: "malicious",
41082
+ description: "This file is a program, but its name says it is a document, picture or video. Real documents never do this; it is how malware tricks people into running it. Do not open it.",
41083
+ test: (c) => EXECUTABLE_KINDS.has(c.kind) && DOCUMENT_EXTENSIONS.has(c.ext)
41084
+ },
41085
+ {
41086
+ id: "CrushAV.Disguise.DoubleExtension",
41087
+ name: "Fake file extension",
41088
+ severity: "high",
41089
+ impact: "suspicious",
41090
+ description: 'The name hides a runnable extension behind a harmless-looking one (like "invoice.pdf.exe"). Windows hides the last part by default, so this looks like a document but runs as a program.',
41091
+ test: (c) => /\.(?:pdf|docx?|xlsx?|pptx?|jpe?g|png|gif|txt|rtf|mp3|mp4|mov|zip)[\s_.]*\.(?:exe|scr|com|pif|bat|cmd|js|jse|vbs|vbe|wsf|hta|lnk|ps1|cpl)$/i.test(baseName(c.name)) || /\s{6,}\.(?:exe|scr|com|pif|bat|cmd|js|vbs|hta|lnk)$/i.test(baseName(c.name))
41092
+ },
41093
+ {
41094
+ id: "CrushAV.Disguise.RightToLeftOverride",
41095
+ name: "Reversed file name trick",
41096
+ severity: "high",
41097
+ impact: "malicious",
41098
+ description: 'The file name contains an invisible character that reverses the text after it, so "photo\u202Egpj.exe" displays as "photoexe.jpg". Legitimate files have no reason to do this.',
41099
+ test: (c) => baseName(c.name).includes("\u202E")
41100
+ },
41101
+ {
41102
+ id: "CrushAV.PowerShell.EncodedCommand",
41103
+ name: "Hidden PowerShell command",
41104
+ severity: "high",
41105
+ impact: "suspicious",
41106
+ description: "Runs PowerShell with a long base64-encoded command, which hides what it does. Malware droppers use this constantly; legitimate software rarely needs to.",
41107
+ test: (c) => (isWindowsScriptContext(c) || c.kind === "pe") && /powershell(?:\.exe)?["']?[^\n]{0,120}?\s-(?:e|ec|en|enc|enco|encod|encodedcommand)\s+["']?[A-Za-z0-9+/]{80,}={0,2}/i.test(allText(c))
41108
+ },
41109
+ {
41110
+ id: "CrushAV.PowerShell.DownloadExecute",
41111
+ name: "Downloads and runs code",
41112
+ severity: "medium",
41113
+ impact: "suspicious",
41114
+ description: "Downloads code from the internet and runs it straight away. Some installers do this; if you did not expect this script, delete it.",
41115
+ test: (c) => {
41116
+ if (!isWindowsScriptContext(c)) return false;
41117
+ const t = allText(c);
41118
+ const download = /(?:DownloadString|DownloadData|DownloadFile|Invoke-WebRequest|\biwr\b|Invoke-RestMethod|\birm\b|Net\.WebClient|Start-BitsTransfer)/i.test(t);
41119
+ const execute = /(?:\bIEX\b|Invoke-Expression|\|\s*iex\b|Start-Process|\.Invoke\(\))/i.test(t);
41120
+ if (!download || !execute) return false;
41121
+ const stealthy = /-w(?:indowstyle)?\s+h(?:idden)?\b/i.test(t) && /-ex(?:ecutionpolicy)?\s+bypass/i.test(t);
41122
+ return stealthy ? { impact: "malicious", severity: "high", description: "Downloads code and runs it in a hidden window with security checks bypassed. This is how most Windows malware gets installed." } : true;
41123
+ }
41124
+ },
41125
+ {
41126
+ id: "CrushAV.Script.WindowsDropper",
41127
+ name: "Script that downloads and runs programs",
41128
+ severity: "high",
41129
+ impact: "malicious",
41130
+ description: "A Windows script (JS/VBS/HTA) that fetches something from the internet and launches it. Email attachments like this are malware droppers; nothing legitimate is delivered this way.",
41131
+ test: (c) => {
41132
+ if (!WIN_SCRIPT_EXTS.has(c.ext)) return false;
41133
+ const t = c.text;
41134
+ return /WScript\.Shell|Shell\.Application/i.test(t) && /\.(?:Run|Exec|ShellExecute)\s*\(/i.test(t) && /(?:MSXML2\.(?:Server)?XMLHTTP|WinHttp\.WinHttpRequest|ADODB\.Stream|Microsoft\.XMLHTTP)/i.test(t);
41135
+ }
41136
+ },
41137
+ {
41138
+ id: "CrushAV.Shortcut.LolbinLauncher",
41139
+ name: "Booby-trapped shortcut",
41140
+ severity: "high",
41141
+ impact: "malicious",
41142
+ description: "A Windows shortcut (.lnk) that launches PowerShell, mshta or a similar tool to fetch something from the internet. Shortcuts like this arrive in zip and ISO attachments to install malware.",
41143
+ test: (c) => c.kind === "lnk" && /(?:powershell|mshta|wscript|cscript|rundll32|regsvr32|certutil|bitsadmin|cmd(?:\.exe)?\s*\/c)/i.test(allText(c)) && /(?:https?:\/\/|\\\\[\w.-]+@SSL|-enc(?:odedcommand)?\s)/i.test(allText(c))
41144
+ },
41145
+ {
41146
+ id: "CrushAV.Office.MacroInDocx",
41147
+ name: "Macros hidden in a regular Office file",
41148
+ severity: "high",
41149
+ impact: "suspicious",
41150
+ description: "This document carries macro code even though its type (.docx/.xlsx/.pptx) is not supposed to have any. That mismatch is a common way to sneak malicious macros past filters.",
41151
+ test: (c) => c.kind === "zip" && ["docx", "xlsx", "pptx"].includes(c.ext) && c.text.includes("vbaProject.bin")
41152
+ },
41153
+ {
41154
+ id: "CrushAV.Office.AutoMacro",
41155
+ name: "Office macro that runs on open and starts programs",
41156
+ severity: "high",
41157
+ impact: "malicious",
41158
+ description: 'An Office document whose macro runs automatically when opened and starts other programs or downloads files. Never click "Enable content" on this one.',
41159
+ test: (c) => {
41160
+ if (c.kind !== "ole") return false;
41161
+ const t = allText(c);
41162
+ if (!/_VBA_PROJECT|VBA\b/i.test(t)) return false;
41163
+ const auto = /(?:Auto_?Open|Document_Open|Workbook_Open|AutoExec|Auto_Close|Document_Close)/i.test(t);
41164
+ const act = /(?:\bShell\b|WScript\.Shell|CreateObject|URLDownloadToFile|powershell|MSXML2)/i.test(t);
41165
+ if (auto && act) return true;
41166
+ if (auto) return { impact: "suspicious", severity: "medium", name: "Office macro that runs on open", description: "This document has a macro that runs automatically when opened. Only enable macros for documents you were expecting from someone you trust." };
41167
+ return false;
41168
+ }
41169
+ },
41170
+ {
41171
+ id: "CrushAV.Office.MacroEnabled",
41172
+ name: "Document contains macros",
41173
+ severity: "info",
41174
+ impact: "info",
41175
+ description: "This is a macro-enabled Office document. That is normal for some spreadsheets, but only enable macros if you trust the sender.",
41176
+ test: (c) => c.kind === "zip" && ["docm", "xlsm", "pptm", "dotm", "xltm"].includes(c.ext) && c.text.includes("vbaProject.bin")
41177
+ },
41178
+ {
41179
+ id: "CrushAV.PDF.Launch",
41180
+ name: "PDF that tries to start a program",
41181
+ severity: "high",
41182
+ impact: "suspicious",
41183
+ description: "This PDF contains a /Launch action, which asks your PDF reader to run a program. Normal documents do not need that.",
41184
+ test: (c) => {
41185
+ if (c.kind !== "pdf" || !/\/Launch\b/.test(c.text)) return false;
41186
+ return /(?:cmd\.exe|powershell|mshta|\.exe\b|\.bat\b|\.vbs\b)/i.test(c.text) ? { impact: "malicious", description: "This PDF tries to start a Windows program (cmd, PowerShell or an .exe) when opened. That is an attack; do not open it." } : true;
41187
+ }
41188
+ },
41189
+ {
41190
+ id: "CrushAV.PDF.AutoJavaScript",
41191
+ name: "PDF runs JavaScript on open",
41192
+ severity: "info",
41193
+ impact: "info",
41194
+ description: "This PDF runs JavaScript when opened. Fillable forms do this legitimately, so it is shown for information only.",
41195
+ test: (c) => c.kind === "pdf" && /\/(?:OpenAction|AA)\b/.test(c.text) && /\/(?:JavaScript|JS)\b/.test(c.text)
41196
+ },
41197
+ {
41198
+ id: "CrushAV.Shell.ReverseShell",
41199
+ name: "Remote-control backdoor (reverse shell)",
41200
+ severity: "critical",
41201
+ impact: "malicious",
41202
+ description: "This script connects out to another computer and hands it a command line on this one. That gives a stranger full control of the machine.",
41203
+ test: (c) => {
41204
+ if (!isScript(c)) return false;
41205
+ const t = c.text;
41206
+ return /bash\s+-i\s*>&\s*\/dev\/tcp\//.test(t) || /\/dev\/tcp\/\d{1,3}(?:\.\d{1,3}){3}\/\d{2,5}\s*0>&1/.test(t) || /\bnc(?:at)?\s+(?:-\w+\s+)*-e\s+\/bin\/(?:ba)?sh\b/.test(t) || /socket\.socket\([\s\S]{0,300}?(?:os\.dup2|pty\.spawn)\([\s\S]{0,300}?\/bin\/(?:ba)?sh/.test(t) || /New-Object\s+System\.Net\.Sockets\.TCPClient\([\s\S]{0,600}?(?:\bIEX\b|Invoke-Expression)/i.test(t);
41207
+ }
41208
+ },
41209
+ {
41210
+ id: "CrushAV.Web.Webshell",
41211
+ name: "Website backdoor (webshell)",
41212
+ severity: "critical",
41213
+ impact: "malicious",
41214
+ description: "Server code that runs whatever a visitor sends it. Attackers plant these on hacked websites to keep control. Remove it and change your hosting passwords.",
41215
+ test: (c) => {
41216
+ if (!SERVER_SCRIPT_EXTS.has(c.ext)) return false;
41217
+ const t = c.text;
41218
+ return /\b(?:eval|assert|system|passthru|shell_exec|exec|popen|proc_open|create_function)\s*\(\s*@?(?:(?:base64_decode|gzinflate|str_rot13|gzuncompress|stripslashes)\s{0,4}\(\s{0,4}@?){0,4}\$_(?:POST|GET|REQUEST|COOKIE)\b/i.test(t) || /\beval\s*\(\s*gz(?:inflate|uncompress)\s*\(\s*base64_decode\s*\(/i.test(t) || /Runtime\.getRuntime\(\)\.exec\(\s*request\.getParameter/.test(t) || /Request\.(?:Form|QueryString|Item)\[[^\]]+\][\s\S]{0,120}?(?:Process\.Start|eval\s*\()/i.test(t);
41219
+ }
41220
+ },
41221
+ {
41222
+ id: "CrushAV.PUA.CoinMiner",
41223
+ name: "Cryptocurrency miner",
41224
+ severity: "high",
41225
+ impact: "suspicious",
41226
+ description: "Software that uses your computer to mine cryptocurrency for someone. If you did not install a miner yourself, it is stealing your electricity and slowing you down.",
41227
+ test: (c) => {
41228
+ if (NON_RUNNABLE_SOURCE_EXTS.has(c.ext)) return false;
41229
+ const t = c.text;
41230
+ return /stratum2?\+(?:tcp|ssl|tls):\/\//i.test(t) && /(?:xmrig|donate-level|cryptonight|randomx|nicehash|cpu-max-threads-hint)/i.test(t);
41231
+ }
41232
+ },
41233
+ {
41234
+ id: "CrushAV.Ransomware.ShadowCopyWipe",
41235
+ name: "Deletes backups (ransomware behaviour)",
41236
+ severity: "critical",
41237
+ impact: "malicious",
41238
+ description: "This program deletes Windows backup copies and disables recovery, which is what ransomware does right before encrypting files. Disconnect from the network and do not run it.",
41239
+ test: (c) => {
41240
+ if (!(EXECUTABLE_KINDS.has(c.kind) || isWindowsScriptContext(c))) return false;
41241
+ const t = allText(c);
41242
+ const hits = RANSOM_COMMANDS.filter((r) => r.test(t)).length;
41243
+ if (hits >= 2) return true;
41244
+ if (hits === 1) return { impact: "suspicious", severity: "high", description: "This program deletes Windows backup copies. Ransomware does this before encrypting files; a few admin tools do it on purpose. If you do not know what this is, do not run it." };
41245
+ return false;
41246
+ }
41247
+ },
41248
+ {
41249
+ id: "CrushAV.Ransomware.Note",
41250
+ name: "Ransom note",
41251
+ severity: "critical",
41252
+ impact: "malicious",
41253
+ description: "This looks like a ransom note, which ransomware leaves behind after encrypting files. Disconnect this computer from the network, do not pay, and check nomoreransom.org for a free decryptor.",
41254
+ test: (c) => c.size <= 64 * 1024 && c.kind === "text" && NOTE_EXTS.has(c.ext) && /(?:all\s+)?your\s+(?:important\s+|personal\s+)?(?:files|documents|data)\s+(?:have\s+been|are|were)\s+(?:encrypted|locked)/i.test(c.text) && /(?:bitcoin|\bBTC\b|monero|\.onion\b|tor\s+browser|decrypt(?:or|ion)\s+(?:key|tool|software|program))/i.test(c.text)
41255
+ },
41256
+ {
41257
+ id: "CrushAV.HackTool.CredentialDumper",
41258
+ name: "Password-stealing tool",
41259
+ severity: "high",
41260
+ impact: "malicious",
41261
+ description: "A tool that pulls saved passwords out of Windows memory (Mimikatz or a copy of it). Attackers use it to spread through networks.",
41262
+ test: (c) => (c.kind === "pe" || c.ext === "ps1") && /sekurlsa::(?:logonpasswords|wdigest|msv)|lsadump::(?:sam|dcsync|secrets)/i.test(allText(c))
41263
+ },
41264
+ {
41265
+ id: "CrushAV.macOS.PasswordPhishStealer",
41266
+ name: "Mac password-stealing script",
41267
+ severity: "critical",
41268
+ impact: "malicious",
41269
+ description: "Shows a fake macOS password prompt and then reaches for your keychain, browser data or wallets. This is how Mac stealers like AMOS work. Do not enter your password; delete it.",
41270
+ test: (c) => {
41271
+ if (!(isScript(c) || c.kind === "macho")) return false;
41272
+ const t = c.text;
41273
+ return /display\s+dialog[\s\S]{0,400}?with\s+hidden\s+answer/i.test(t) && /(?:Library\/Keychains|login\.keychain|Cookies|Login Data|wallet|find-generic-password|dscl\s+\.\s+-?authonly|curl\s)/i.test(t);
41274
+ }
41275
+ },
41276
+ {
41277
+ id: "CrushAV.Web.ClickFix",
41278
+ name: 'Fake "verify you are human" trick (ClickFix)',
41279
+ severity: "critical",
41280
+ impact: "malicious",
41281
+ description: 'A web page that secretly copies a command to your clipboard and tells you to paste it into Run or Terminal to "verify" yourself. Pasting it installs malware. Never paste commands a website gives you.',
41282
+ test: (c) => {
41283
+ if (!(WEB_EXTS.has(c.ext) || c.ext === "js")) return false;
41284
+ const t = c.text;
41285
+ return /(?:navigator\.clipboard\.writeText|document\.execCommand\(\s*["']copy)/.test(t) && /(?:powershell|mshta|cmd(?:\.exe)?\s*\/c|curl\s[^\n]{0,200}\|\s*(?:ba|z)?sh|osascript)/i.test(t) && /(?:Win(?:dows)?\s*(?:key\s*)?\+\s*R|Windows\s+key|Ctrl\s*\+\s*V|Cmd\s*\+\s*Space|verify\s+you\s+are\s+(?:a\s+)?human|I(?:'|&#39;)?m\s+not\s+a\s+robot)/i.test(t);
41286
+ }
41287
+ },
41288
+ {
41289
+ id: "CrushAV.Web.HtmlSmuggling",
41290
+ name: "Web page that builds a hidden download",
41291
+ severity: "high",
41292
+ impact: "suspicious",
41293
+ description: "This HTML or SVG file carries a large hidden file inside itself and saves it to your computer when opened. Attackers use this to sneak malware past email filters.",
41294
+ test: (c) => {
41295
+ if (!WEB_EXTS.has(c.ext)) return false;
41296
+ const t = c.text;
41297
+ return /new\s+Blob\s*\(/.test(t) && /(?:\.download\s*=|msSaveOrOpenBlob|msSaveBlob)/.test(t) && /(?:atob\s*\(|base64)/.test(t) && /[A-Za-z0-9+/]{20000}/.test(t);
41298
+ }
41299
+ },
41300
+ {
41301
+ id: "CrushAV.Web.SvgRedirect",
41302
+ name: "Image file that runs code",
41303
+ severity: "medium",
41304
+ impact: "suspicious",
41305
+ description: 'This SVG "image" contains a script that redirects you or decodes hidden content. Phishing emails use SVG attachments like this to send you to fake login pages.',
41306
+ test: (c) => c.ext === "svg" && /<script\b/i.test(c.text) && /(?:location(?:\.href)?\s*=|location\.replace\(|window\.open\(|atob\s*\()/.test(c.text)
41307
+ }
41308
+ ];
41309
+ function buildContext(name, bytes, kind, size) {
41310
+ let text = "";
41311
+ for (let i = 0; i < bytes.length; i += 32768) {
41312
+ text += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));
41313
+ }
41314
+ let wide = "";
41315
+ if (kind === "pe" || kind === "lnk" || kind === "ole") {
41316
+ const parts = [];
41317
+ let run2 = "";
41318
+ for (let i = 0; i + 1 < bytes.length; i += 2) {
41319
+ const lo = bytes[i];
41320
+ if (bytes[i + 1] === 0 && lo >= 32 && lo < 127) run2 += String.fromCharCode(lo);
41321
+ else {
41322
+ if (run2.length >= 4) parts.push(run2);
41323
+ run2 = "";
41324
+ }
41325
+ }
41326
+ if (run2.length >= 4) parts.push(run2);
41327
+ wide = parts.join("\n");
41328
+ }
41329
+ return { name, ext: extOf(name), kind, size, bytes, text, wide };
41330
+ }
41331
+ function runRules(ctx, rules = RULES) {
41332
+ const out = [];
41333
+ for (const r of rules) {
41334
+ let hit;
41335
+ try {
41336
+ hit = r.test(ctx);
41337
+ } catch {
41338
+ continue;
41339
+ }
41340
+ if (!hit) continue;
41341
+ const base = { engine: "heuristic", id: r.id, name: r.name, severity: r.severity, impact: r.impact, description: r.description };
41342
+ out.push(hit === true ? base : { ...base, ...hit });
41343
+ }
41344
+ return out;
41345
+ }
41346
+
41347
+ // ../../packages/av/src/engine.ts
41348
+ var DEFAULT_HEURISTIC_BYTES = 16 * 1024 * 1024;
41349
+ var SignatureSet = class {
41350
+ map = /* @__PURE__ */ new Map();
41351
+ constructor(entries = BUILTIN_SIGNATURES) {
41352
+ for (const [h, n] of entries) this.add(h, n);
41353
+ }
41354
+ add(sha256, name) {
41355
+ const h = sha256.trim().toLowerCase();
41356
+ if (SHA256_RE.test(h)) this.map.set(h, name || "Malware");
41357
+ }
41358
+ /** Load `sha256 [name]` lines; `#` starts a comment. Returns how many were added. */
41359
+ load(text) {
41360
+ let n = 0;
41361
+ for (const raw of text.split(/\r?\n/)) {
41362
+ const line2 = raw.replace(/#.*/, "").trim();
41363
+ if (!line2) continue;
41364
+ const [h, ...rest] = line2.split(/[\s,;]+/);
41365
+ if (SHA256_RE.test(h.toLowerCase())) {
41366
+ this.add(h, rest.join(" "));
41367
+ n++;
41368
+ }
41369
+ }
41370
+ return n;
41371
+ }
41372
+ get(sha256) {
41373
+ return this.map.get(sha256.toLowerCase());
41374
+ }
41375
+ get size() {
41376
+ return this.map.size;
41377
+ }
41378
+ };
41379
+ var BUILTIN_SIGNATURES = [
41380
+ ["275a021bbfb6489e54d471899f7db9d1663fc695ec2fe2a2c4538aabf651fd0f", "EICAR-Test-File"]
41381
+ ];
41382
+ var IMPACT_RANK = { info: 0, suspicious: 1, malicious: 2 };
41383
+ function verdictOf(detections) {
41384
+ let worst = 0;
41385
+ for (const d of detections) worst = Math.max(worst, IMPACT_RANK[d.impact]);
41386
+ return worst === 2 ? "malicious" : worst === 1 ? "suspicious" : "clean";
41387
+ }
41388
+ async function scanBytes(input, opts = {}) {
41389
+ const size = input.size ?? input.bytes.length;
41390
+ const complete = input.bytes.length >= size;
41391
+ const sha256 = input.sha256 ?? (complete ? await sha256Hex(input.bytes) : null);
41392
+ const kind = sniffKind(input.bytes);
41393
+ const detections = [];
41394
+ const sigs = opts.signatures ?? DEFAULT_SIGNATURES;
41395
+ const known = sha256 ? sigs.get(sha256) : void 0;
41396
+ if (known) {
41397
+ detections.push({
41398
+ engine: "signature",
41399
+ id: `CrushAV.Signature.${known.replace(/[^\w.-]+/g, "_")}`,
41400
+ name: known,
41401
+ severity: known.startsWith("EICAR") ? "low" : "critical",
41402
+ impact: "malicious",
41403
+ description: known.startsWith("EICAR") ? "The harmless standard antivirus test file. Seeing this means the scanner works." : `This exact file is known malware (${known}). Quarantine or delete it.`
41404
+ });
41405
+ }
41406
+ const ctx = buildContext(input.name, input.bytes, kind, size);
41407
+ for (const d of runRules(ctx, opts.rules ?? RULES)) {
41408
+ if (known && d.id === "CrushAV.Test.EICAR") continue;
41409
+ detections.push(d);
41410
+ }
41411
+ return {
41412
+ path: input.name,
41413
+ size,
41414
+ sha256,
41415
+ kind,
41416
+ verdict: verdictOf(detections),
41417
+ detections,
41418
+ note: complete ? void 0 : `heuristics read the first ${Math.round(input.bytes.length / 1048576)} MB`
41419
+ };
41420
+ }
41421
+ var DEFAULT_SIGNATURES = new SignatureSet();
41422
+ var TRUSTED_SCORE = 50;
41423
+ function applyReputation(result, rep) {
41424
+ if (!rep) return result;
41425
+ const detections = [...result.detections];
41426
+ if (rep.knownMalicious) {
41427
+ detections.push({
41428
+ engine: "reputation",
41429
+ id: `CrushAV.Reputation.${(rep.malwareName ?? "KnownMalware").replace(/[^\w.-]+/g, "_")}`,
41430
+ name: rep.malwareName ?? "Known malware",
41431
+ severity: "critical",
41432
+ impact: "malicious",
41433
+ description: `This exact file is listed as malware by ${rep.knownMalicious}. Quarantine or delete it.`
41434
+ });
41435
+ } else if ((rep.trust ?? 0) >= TRUSTED_SCORE) {
41436
+ for (let i = 0; i < detections.length; i++) {
41437
+ const d = detections[i];
41438
+ if (d.engine === "heuristic" && d.impact === "suspicious") {
41439
+ detections[i] = { ...d, impact: "info", description: `${d.description} (Downgraded: this exact file is a known, published file from a trusted software source.)` };
41440
+ }
41441
+ }
41442
+ }
41443
+ return { ...result, detections, verdict: verdictOf(detections) };
41444
+ }
41445
+
41446
+ // ../../packages/av/src/reputation.ts
41447
+ var DEFAULT_LOOKUP_ENDPOINT = "https://threatcrush.com/api/av/lookup";
41448
+ var LOOKUP_BATCH = 100;
41449
+ async function lookupHashes(hashes, opts = {}) {
41450
+ const out = /* @__PURE__ */ new Map();
41451
+ const f = opts.fetch ?? globalThis.fetch;
41452
+ const unique = [...new Set(hashes.map((h) => h.toLowerCase()).filter((h) => SHA256_RE.test(h)))];
41453
+ if (!f || unique.length === 0) return out;
41454
+ for (let i = 0; i < unique.length; i += LOOKUP_BATCH) {
41455
+ const batch = unique.slice(i, i + LOOKUP_BATCH);
41456
+ const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
41457
+ const timer = ctrl ? setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 2e4) : null;
41458
+ try {
41459
+ const headers = { "content-type": "application/json" };
41460
+ if (opts.userAgent) headers["user-agent"] = opts.userAgent;
41461
+ const res = await f(opts.endpoint ?? DEFAULT_LOOKUP_ENDPOINT, {
41462
+ method: "POST",
41463
+ headers,
41464
+ body: JSON.stringify({ hashes: batch }),
41465
+ signal: ctrl?.signal
41466
+ });
41467
+ if (!res.ok) continue;
41468
+ const body = await res.json();
41469
+ for (const [h, rep] of Object.entries(body.results ?? {})) {
41470
+ if (SHA256_RE.test(h)) out.set(h, { ...rep, sha256: h });
41471
+ }
41472
+ } catch {
41473
+ } finally {
41474
+ if (timer) clearTimeout(timer);
41475
+ }
41476
+ }
41477
+ return out;
41478
+ }
41479
+
41480
+ // ../../packages/av/src/summary.ts
41481
+ function summarize2(results, engines, startedAt, skipped = 0) {
41482
+ const count = (v) => results.filter((r) => r.verdict === v).length;
41483
+ return {
41484
+ scanned: results.length,
41485
+ malicious: count("malicious"),
41486
+ suspicious: count("suspicious"),
41487
+ clean: count("clean"),
41488
+ errors: count("error"),
41489
+ skipped,
41490
+ engines,
41491
+ startedAt: startedAt.toISOString(),
41492
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString()
41493
+ };
41494
+ }
41495
+
41496
+ // ../../packages/av/src/node/locations.ts
41497
+ var import_node_fs22 = require("fs");
41498
+ var import_node_os9 = require("os");
41499
+ var import_node_path19 = require("path");
41500
+ function quickScanTargets(platform = process.platform, env3 = process.env, home = (0, import_node_os9.homedir)()) {
41501
+ const t = [
41502
+ { path: (0, import_node_path19.join)(home, "Downloads"), depth: 3 },
41503
+ { path: (0, import_node_path19.join)(home, "Desktop"), depth: 2 }
41504
+ ];
41505
+ if (platform === "win32") {
41506
+ const appData = env3.APPDATA ?? (0, import_node_path19.join)(home, "AppData", "Roaming");
41507
+ const local = env3.LOCALAPPDATA ?? (0, import_node_path19.join)(home, "AppData", "Local");
41508
+ const programData = env3.ProgramData ?? env3.PROGRAMDATA ?? "C:\\ProgramData";
41509
+ t.push(
41510
+ { path: env3.TEMP ?? (0, import_node_path19.join)(local, "Temp"), depth: 2 },
41511
+ { path: (0, import_node_path19.join)(appData, "Microsoft", "Windows", "Start Menu", "Programs", "Startup"), depth: 1 },
41512
+ { path: (0, import_node_path19.join)(programData, "Microsoft", "Windows", "Start Menu", "Programs", "StartUp"), depth: 1 },
41513
+ // Droppers love %APPDATA%\<random>\payload.exe; two levels catches that without crawling every app's cache.
41514
+ { path: appData, depth: 2 },
41515
+ { path: local, depth: 1 },
41516
+ { path: (0, import_node_path19.join)(env3.PUBLIC ?? "C:\\Users\\Public"), depth: 2 }
41517
+ );
41518
+ } else if (platform === "darwin") {
41519
+ t.push(
41520
+ { path: (0, import_node_path19.join)(home, "Library", "LaunchAgents"), depth: 1 },
41521
+ { path: "/Library/LaunchAgents", depth: 1 },
41522
+ { path: "/Library/LaunchDaemons", depth: 1 },
41523
+ { path: "/Users/Shared", depth: 2 },
41524
+ { path: "/tmp", depth: 2 },
41525
+ { path: (0, import_node_os9.tmpdir)(), depth: 2 }
41526
+ );
41527
+ } else {
41528
+ t.push(
41529
+ { path: "/tmp", depth: 2 },
41530
+ { path: "/var/tmp", depth: 2 },
41531
+ { path: "/dev/shm", depth: 2 },
41532
+ { path: (0, import_node_path19.join)(home, ".config", "autostart"), depth: 1 },
41533
+ { path: (0, import_node_path19.join)(home, ".config", "systemd", "user"), depth: 1 },
41534
+ { path: (0, import_node_path19.join)(home, ".local", "bin"), depth: 1 },
41535
+ { path: "/etc/cron.d", depth: 1 },
41536
+ { path: "/etc/systemd/system", depth: 1 }
41537
+ );
41538
+ }
41539
+ const seen = /* @__PURE__ */ new Set();
41540
+ return t.filter((x) => !seen.has(x.path) && (seen.add(x.path), (0, import_node_fs22.existsSync)(x.path)));
41541
+ }
41542
+ function fullScanTargets(platform = process.platform, env3 = process.env, home = (0, import_node_os9.homedir)()) {
41543
+ const quick = quickScanTargets(platform, env3, home).filter((x) => !x.path.startsWith(home));
41544
+ const extra = platform === "linux" ? [{ path: "/opt", depth: Infinity }, { path: "/usr/local/bin", depth: 1 }] : [];
41545
+ return [{ path: home, depth: Infinity }, ...quick, ...extra.filter((x) => (0, import_node_fs22.existsSync)(x.path))];
41546
+ }
41547
+
41548
+ // ../../packages/av/src/node/walk.ts
41549
+ var import_promises = require("fs/promises");
41550
+ var import_node_path20 = require("path");
41551
+ var SKIP_DIR_NAMES = /* @__PURE__ */ new Set([
41552
+ ".git",
41553
+ ".hg",
41554
+ ".svn",
41555
+ "node_modules",
41556
+ ".pnpm-store",
41557
+ ".npm",
41558
+ ".yarn",
41559
+ "__pycache__",
41560
+ ".venv",
41561
+ "venv",
41562
+ ".cargo",
41563
+ ".rustup",
41564
+ ".gradle",
41565
+ ".m2",
41566
+ ".cache",
41567
+ ".Trash",
41568
+ "$Recycle.Bin",
41569
+ "System Volume Information",
41570
+ ".threatcrush"
41571
+ ]);
41572
+ var SKIP_ROOTS = ["/proc", "/sys", "/dev/pts", "/run", "/snap"];
41573
+ async function* walkTargets(targets, opts = {}) {
41574
+ const skip = opts.skipDirNames ?? SKIP_DIR_NAMES;
41575
+ const seen = /* @__PURE__ */ new Set();
41576
+ for (const t of targets) {
41577
+ let st;
41578
+ try {
41579
+ st = await (0, import_promises.lstat)(t.path);
41580
+ } catch (e) {
41581
+ opts.onSkip?.(t.path, e.code ?? "unreadable");
41582
+ continue;
41583
+ }
41584
+ if (st.isFile()) {
41585
+ if (!seen.has(t.path)) {
41586
+ seen.add(t.path);
41587
+ yield { path: t.path, size: st.size };
41588
+ }
41589
+ continue;
41590
+ }
41591
+ if (!st.isDirectory()) continue;
41592
+ const stack2 = [[t.path, 0]];
41593
+ while (stack2.length) {
41594
+ if (opts.signal?.aborted) return;
41595
+ const [dir, depth] = stack2.pop();
41596
+ if (SKIP_ROOTS.some((r) => dir === r || dir.startsWith(`${r}/`))) continue;
41597
+ let handle;
41598
+ try {
41599
+ handle = await (0, import_promises.opendir)(dir);
41600
+ } catch (e) {
41601
+ opts.onSkip?.(dir, e.code ?? "unreadable");
41602
+ continue;
41603
+ }
41604
+ for await (const ent of handle) {
41605
+ const p = (0, import_node_path20.join)(dir, ent.name);
41606
+ if (ent.isSymbolicLink()) continue;
41607
+ if (ent.isDirectory()) {
41608
+ if (depth + 1 < t.depth && !skip.has(ent.name)) stack2.push([p, depth + 1]);
41609
+ continue;
41610
+ }
41611
+ if (!ent.isFile() || seen.has(p)) continue;
41612
+ seen.add(p);
41613
+ try {
41614
+ const s = await (0, import_promises.lstat)(p);
41615
+ yield { path: p, size: s.size };
41616
+ } catch (e) {
41617
+ opts.onSkip?.(p, e.code ?? "unreadable");
41618
+ }
41619
+ }
41620
+ }
41621
+ }
41622
+ }
41623
+
41624
+ // ../../packages/av/src/node/clamav.ts
41625
+ var import_node_child_process5 = require("child_process");
40798
41626
  var import_node_fs23 = require("fs");
41627
+ var import_promises2 = require("fs/promises");
41628
+ var import_node_os10 = require("os");
41629
+ var import_node_path21 = require("path");
41630
+ var WINDOWS_DIRS = ["C:\\Program Files\\ClamAV", "C:\\Program Files (x86)\\ClamAV", "C:\\ProgramData\\chocolatey\\bin"];
41631
+ function findBinary(name, env3 = process.env, platform = process.platform) {
41632
+ const exe = platform === "win32" ? `${name}.exe` : name;
41633
+ const dirs = (env3.PATH ?? env3.Path ?? "").split(import_node_path21.delimiter).filter(Boolean);
41634
+ if (platform === "win32") dirs.push(...WINDOWS_DIRS);
41635
+ if (platform === "darwin") dirs.push("/opt/homebrew/bin", "/usr/local/bin");
41636
+ for (const d of dirs) {
41637
+ const p = (0, import_node_path21.join)(d, exe);
41638
+ if ((0, import_node_fs23.existsSync)(p)) return p;
41639
+ }
41640
+ return null;
41641
+ }
41642
+ function run(bin, args, timeoutMs, signal) {
41643
+ return new Promise((resolve9) => {
41644
+ const child = (0, import_node_child_process5.spawn)(bin, args, { windowsHide: true, signal });
41645
+ let stdout = "";
41646
+ let stderr = "";
41647
+ child.stdout.on("data", (d) => stdout += d);
41648
+ child.stderr.on("data", (d) => stderr += d);
41649
+ const timer = setTimeout(() => child.kill(), timeoutMs);
41650
+ child.on("error", (e) => {
41651
+ clearTimeout(timer);
41652
+ resolve9({ code: null, stdout, stderr: stderr || String(e) });
41653
+ });
41654
+ child.on("close", (code) => {
41655
+ clearTimeout(timer);
41656
+ resolve9({ code, stdout, stderr });
41657
+ });
41658
+ });
41659
+ }
41660
+ async function detectClamAV() {
41661
+ const none = { available: false, binary: null, mode: null, version: null, signaturesDate: null };
41662
+ const clamscan = findBinary("clamscan");
41663
+ const clamdscan = findBinary("clamdscan");
41664
+ let mode = null;
41665
+ let binary = null;
41666
+ if (clamdscan) {
41667
+ const ping = await run(clamdscan, ["--ping", "1"], 5e3);
41668
+ if (ping.code === 0) {
41669
+ mode = "clamdscan";
41670
+ binary = clamdscan;
41671
+ }
41672
+ }
41673
+ if (!binary && clamscan) {
41674
+ mode = "clamscan";
41675
+ binary = clamscan;
41676
+ }
41677
+ if (!binary) return none;
41678
+ const v = await run(binary, ["--version"], 15e3);
41679
+ const version = v.stdout.trim().split("\n")[0] || null;
41680
+ const parts = version?.split("/") ?? [];
41681
+ return { available: v.code === 0, binary, mode, version, signaturesDate: parts.length >= 3 ? parts.slice(2).join("/").trim() : null };
41682
+ }
41683
+ function parseClamOutput(stdout) {
41684
+ const out = /* @__PURE__ */ new Map();
41685
+ for (const line2 of stdout.split(/\r?\n/)) {
41686
+ const m = /^(.*): (\S+) FOUND$/.exec(line2.trim());
41687
+ if (!m) continue;
41688
+ const list = out.get(m[1]) ?? [];
41689
+ list.push(m[2]);
41690
+ out.set(m[1], list);
41691
+ }
41692
+ return out;
41693
+ }
41694
+ function clamDetection(sig) {
41695
+ const pua = /^PUA\./i.test(sig);
41696
+ const heuristic = /^Heuristics\./i.test(sig);
41697
+ return {
41698
+ engine: "clamav",
41699
+ id: `ClamAV.${sig}`,
41700
+ name: sig,
41701
+ severity: pua ? "medium" : heuristic ? "medium" : /EICAR/i.test(sig) ? "low" : "critical",
41702
+ impact: pua || heuristic ? "suspicious" : "malicious",
41703
+ description: pua ? "ClamAV flags this as a potentially unwanted program (adware, bundleware or a tool that can be misused)." : heuristic ? "ClamAV heuristics flag this file as likely malicious, without an exact signature match." : /EICAR/i.test(sig) ? "The harmless antivirus test file, recognised by ClamAV too." : `ClamAV recognises this file as malware (${sig}). Quarantine or delete it.`
41704
+ };
41705
+ }
41706
+ async function clamScanFiles(info2, files, opts = {}) {
41707
+ const detections = /* @__PURE__ */ new Map();
41708
+ if (!info2.available || !info2.binary || files.length === 0) return { detections, error: null };
41709
+ const dir = await (0, import_promises2.mkdtemp)((0, import_node_path21.join)((0, import_node_os10.tmpdir)(), "crushav-"));
41710
+ const list = (0, import_node_path21.join)(dir, "files.txt");
41711
+ try {
41712
+ await (0, import_promises2.writeFile)(list, `${files.join("\n")}
41713
+ `);
41714
+ const args = ["--no-summary", "--infected", "--stdout", `--file-list=${list}`];
41715
+ if (info2.mode === "clamdscan") args.push("--fdpass", "--multiscan");
41716
+ const r = await run(info2.binary, args, opts.timeoutMs ?? 60 * 60 * 1e3, opts.signal);
41717
+ for (const [path2, sigs] of parseClamOutput(r.stdout)) detections.set(path2, sigs.map(clamDetection));
41718
+ const error2 = r.code === null || r.code === 2 && detections.size === 0 && !r.stdout.trim() ? r.stderr.trim().split("\n").pop() ?? "clamav failed" : null;
41719
+ return { detections, error: error2 };
41720
+ } finally {
41721
+ await (0, import_promises2.rm)(dir, { recursive: true, force: true });
41722
+ }
41723
+ }
41724
+ function clamInstallHint(platform = process.platform) {
41725
+ switch (platform) {
41726
+ case "win32":
41727
+ return 'winget install Cisco.ClamAV (then run "freshclam" once)';
41728
+ case "darwin":
41729
+ return 'brew install clamav && cp $(brew --prefix)/etc/clamav/freshclam.conf.sample $(brew --prefix)/etc/clamav/freshclam.conf && sed -i "" "/^Example/d" $(brew --prefix)/etc/clamav/freshclam.conf && freshclam';
41730
+ default:
41731
+ return "sudo apt install clamav clamav-daemon (Fedora: sudo dnf install clamav clamd; Arch: sudo pacman -S clamav)";
41732
+ }
41733
+ }
41734
+
41735
+ // ../../packages/av/src/node/quarantine.ts
41736
+ var import_node_crypto6 = require("crypto");
41737
+ var import_node_fs24 = require("fs");
41738
+ var import_promises3 = require("fs/promises");
41739
+ var import_node_os11 = require("os");
41740
+ var import_node_path22 = require("path");
41741
+ var KEY = 165;
41742
+ function quarantineDir(home = (0, import_node_os11.homedir)()) {
41743
+ return process.env.CRUSHAV_QUARANTINE_DIR ?? (0, import_node_path22.join)(home, ".threatcrush", "quarantine");
41744
+ }
41745
+ function xor(buf) {
41746
+ const out = Buffer.allocUnsafe(buf.length);
41747
+ for (let i = 0; i < buf.length; i++) out[i] = buf[i] ^ KEY;
41748
+ return out;
41749
+ }
41750
+ async function quarantineFile(path2, detections = [], dir = quarantineDir()) {
41751
+ const data = await (0, import_promises3.readFile)(path2);
41752
+ const sha256 = (0, import_node_crypto6.createHash)("sha256").update(data).digest("hex");
41753
+ const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g, "").slice(0, 14)}-${(0, import_node_crypto6.randomBytes)(4).toString("hex")}`;
41754
+ await (0, import_promises3.mkdir)(dir, { recursive: true, mode: 448 });
41755
+ const entry = {
41756
+ id,
41757
+ originalPath: path2,
41758
+ sha256,
41759
+ size: data.length,
41760
+ detections: detections.map(({ id: did, name, engine: engine2, impact }) => ({ id: did, name, engine: engine2, impact })),
41761
+ quarantinedAt: (/* @__PURE__ */ new Date()).toISOString()
41762
+ };
41763
+ const bin = (0, import_node_path22.join)(dir, `${id}.bin`);
41764
+ await (0, import_promises3.writeFile)(bin, xor(data), { mode: 384 });
41765
+ const check2 = xor(await (0, import_promises3.readFile)(bin));
41766
+ if ((0, import_node_crypto6.createHash)("sha256").update(check2).digest("hex") !== sha256) {
41767
+ await (0, import_promises3.rm)(bin, { force: true });
41768
+ throw new Error("quarantine copy did not verify; original left in place");
41769
+ }
41770
+ await (0, import_promises3.writeFile)((0, import_node_path22.join)(dir, `${id}.json`), JSON.stringify(entry, null, 2), { mode: 384 });
41771
+ await (0, import_promises3.unlink)(path2);
41772
+ return entry;
41773
+ }
41774
+ async function listQuarantine(dir = quarantineDir()) {
41775
+ if (!(0, import_node_fs24.existsSync)(dir)) return [];
41776
+ const out = [];
41777
+ for (const f of await (0, import_promises3.readdir)(dir)) {
41778
+ if (!f.endsWith(".json")) continue;
41779
+ try {
41780
+ out.push(JSON.parse(await (0, import_promises3.readFile)((0, import_node_path22.join)(dir, f), "utf8")));
41781
+ } catch {
41782
+ }
41783
+ }
41784
+ return out.sort((a, b) => b.quarantinedAt.localeCompare(a.quarantinedAt));
41785
+ }
41786
+ async function entryOf(id, dir) {
41787
+ if (!/^[\w-]+$/.test(id)) throw new Error(`bad quarantine id: ${id}`);
41788
+ const p = (0, import_node_path22.join)(dir, `${id}.json`);
41789
+ if (!(0, import_node_fs24.existsSync)(p)) throw new Error(`no quarantined file with id ${id}`);
41790
+ return JSON.parse(await (0, import_promises3.readFile)(p, "utf8"));
41791
+ }
41792
+ async function restoreQuarantined(id, to, dir = quarantineDir()) {
41793
+ const entry = await entryOf(id, dir);
41794
+ const dest = to ?? entry.originalPath;
41795
+ const data = xor(await (0, import_promises3.readFile)((0, import_node_path22.join)(dir, `${id}.bin`)));
41796
+ await (0, import_promises3.mkdir)((0, import_node_path22.dirname)(dest), { recursive: true });
41797
+ try {
41798
+ await (0, import_promises3.writeFile)(dest, data, { flag: "wx" });
41799
+ } catch (e) {
41800
+ if (e.code === "EEXIST") throw new Error(`${dest} already exists; pass another destination`);
41801
+ throw e;
41802
+ }
41803
+ await (0, import_promises3.rm)((0, import_node_path22.join)(dir, `${id}.bin`), { force: true });
41804
+ await (0, import_promises3.rm)((0, import_node_path22.join)(dir, `${id}.json`), { force: true });
41805
+ return dest;
41806
+ }
41807
+ async function deleteQuarantined(id, dir = quarantineDir()) {
41808
+ await entryOf(id, dir);
41809
+ await (0, import_promises3.rm)((0, import_node_path22.join)(dir, `${id}.bin`), { force: true });
41810
+ await (0, import_promises3.rm)((0, import_node_path22.join)(dir, `${id}.json`), { force: true });
41811
+ }
41812
+
41813
+ // ../../packages/av/src/node/scan.ts
41814
+ var import_node_crypto7 = require("crypto");
41815
+ var import_node_fs25 = require("fs");
41816
+ var LOOKUP_KINDS = /* @__PURE__ */ new Set(["pe", "elf", "macho", "script", "lnk", "ole", "zip", "pdf", "dex", "rtf"]);
41817
+ var MAX_LOOKUPS = 5e3;
41818
+ async function readForScan(path2, size, cap) {
41819
+ const hash = (0, import_node_crypto7.createHash)("sha256");
41820
+ const head = Buffer.allocUnsafe(Math.min(size, cap));
41821
+ let filled = 0;
41822
+ await new Promise((resolve9, reject) => {
41823
+ const s = (0, import_node_fs25.createReadStream)(path2, { highWaterMark: 1 << 20 });
41824
+ s.on("data", (chunk2) => {
41825
+ const c = chunk2;
41826
+ hash.update(c);
41827
+ if (filled < head.length) {
41828
+ const n = Math.min(head.length - filled, c.length);
41829
+ c.copy(head, filled, 0, n);
41830
+ filled += n;
41831
+ }
41832
+ });
41833
+ s.on("error", reject);
41834
+ s.on("end", () => resolve9());
41835
+ });
41836
+ return { head: head.subarray(0, filled), sha256: hash.digest("hex") };
41837
+ }
41838
+ async function scanPaths(targets, opts = {}) {
41839
+ const started = /* @__PURE__ */ new Date();
41840
+ const cap = opts.heuristicBytes ?? DEFAULT_HEURISTIC_BYTES;
41841
+ const maxFile = opts.maxFileBytes ?? 1024 ** 3;
41842
+ const skipped = [];
41843
+ const skip = (path2, reason) => {
41844
+ skipped.push({ path: path2, reason });
41845
+ opts.onProgress?.({ type: "skip", path: path2, reason });
41846
+ };
41847
+ let signatures = opts.signatures;
41848
+ if (opts.signatureFile && (0, import_node_fs25.existsSync)(opts.signatureFile)) {
41849
+ signatures = signatures ?? new SignatureSet();
41850
+ signatures.load((0, import_node_fs25.readFileSync)(opts.signatureFile, "utf8"));
41851
+ }
41852
+ const clamav = opts.clamav === "off" ? null : await detectClamAV();
41853
+ if (opts.clamav === "require" && !clamav?.available) throw new Error("ClamAV is not installed (or clamscan is not on PATH)");
41854
+ opts.onProgress?.({ type: "phase", phase: "walking" });
41855
+ const results = [];
41856
+ const queue = [];
41857
+ const limit = Math.max(1, opts.concurrency ?? 4);
41858
+ const scanOne = async (path2, size) => {
41859
+ try {
41860
+ const { head, sha256 } = await readForScan(path2, size, cap);
41861
+ const r = await scanBytes({ name: path2, bytes: head, size, sha256 }, { signatures });
41862
+ results.push(r);
41863
+ opts.onProgress?.({ type: "file", path: path2, scanned: results.length, result: r });
41864
+ } catch (e) {
41865
+ const code = e.code ?? e.message;
41866
+ const r = { path: path2, size, sha256: null, kind: "unknown", verdict: "error", detections: [], note: code };
41867
+ results.push(r);
41868
+ opts.onProgress?.({ type: "file", path: path2, scanned: results.length, result: r });
41869
+ }
41870
+ };
41871
+ for await (const f of walkTargets(targets, { signal: opts.signal, onSkip: skip })) {
41872
+ if (opts.signal?.aborted) break;
41873
+ if (f.size === 0) continue;
41874
+ if (f.size > maxFile) {
41875
+ skip(f.path, `larger than ${Math.round(maxFile / 1048576)} MB`);
41876
+ continue;
41877
+ }
41878
+ const p = scanOne(f.path, f.size).finally(() => {
41879
+ queue.splice(queue.indexOf(p), 1);
41880
+ });
41881
+ queue.push(p);
41882
+ if (queue.length >= limit) await Promise.race(queue);
41883
+ }
41884
+ await Promise.all(queue);
41885
+ const engines = ["signature", "heuristic"];
41886
+ if (opts.reputation !== false && !opts.signal?.aborted) {
41887
+ const wanted = results.filter((r) => r.sha256 && (LOOKUP_KINDS.has(r.kind) || r.detections.length > 0)).slice(0, MAX_LOOKUPS);
41888
+ if (wanted.length) {
41889
+ opts.onProgress?.({ type: "phase", phase: "reputation", detail: `${wanted.length} hashes` });
41890
+ const reps = await lookupHashes(wanted.map((r) => r.sha256), { endpoint: opts.lookupEndpoint, userAgent: opts.userAgent });
41891
+ if (reps.size || wanted.length) engines.push("reputation");
41892
+ applyAll(results, reps);
41893
+ }
41894
+ }
41895
+ let clamavError = null;
41896
+ if (clamav?.available && !opts.signal?.aborted) {
41897
+ const files = results.filter((r) => r.verdict !== "error").map((r) => r.path);
41898
+ opts.onProgress?.({ type: "phase", phase: "clamav", detail: `${files.length} files via ${clamav.mode}` });
41899
+ const { detections, error: error2 } = await clamScanFiles(clamav, files, { signal: opts.signal });
41900
+ clamavError = error2;
41901
+ if (!error2) engines.push("clamav");
41902
+ for (const r of results) {
41903
+ const extra = detections.get(r.path);
41904
+ if (!extra) continue;
41905
+ r.detections.push(...extra);
41906
+ r.verdict = verdictOf(r.detections);
41907
+ }
41908
+ }
41909
+ opts.onProgress?.({ type: "phase", phase: "done" });
41910
+ return { summary: summarize2(results, engines, started, skipped.length), results, clamav, clamavError, skipped };
41911
+ }
41912
+ function applyAll(results, reps) {
41913
+ for (let i = 0; i < results.length; i++) {
41914
+ const r = results[i];
41915
+ if (r.sha256 && reps.has(r.sha256)) results[i] = applyReputation(r, reps.get(r.sha256));
41916
+ }
41917
+ }
41918
+
41919
+ // ../../packages/av/src/node/watch.ts
41920
+ var import_node_fs26 = require("fs");
41921
+ var import_promises4 = require("fs/promises");
41922
+ var import_node_path23 = require("path");
41923
+ var IN_PROGRESS = /\.(?:crdownload|part|partial|download|tmp)$/i;
41924
+ function watchTargets(targets, opts) {
41925
+ const settle2 = opts.settleMs ?? 1500;
41926
+ const timers = /* @__PURE__ */ new Map();
41927
+ const lastScanned = /* @__PURE__ */ new Map();
41928
+ const watchers = [];
41929
+ const scan = async (path2) => {
41930
+ timers.delete(path2);
41931
+ try {
41932
+ const st = await (0, import_promises4.lstat)(path2);
41933
+ if (!st.isFile() || st.size === 0 || st.size > (opts.maxFileBytes ?? 1024 ** 3)) return;
41934
+ const key = `${st.size}:${st.mtimeMs}`;
41935
+ if (lastScanned.get(path2) === key) return;
41936
+ lastScanned.set(path2, key);
41937
+ if (lastScanned.size > 1e4) lastScanned.delete(lastScanned.keys().next().value);
41938
+ const { head, sha256 } = await readForScan(path2, st.size, opts.heuristicBytes ?? 16 * 1024 * 1024);
41939
+ let r = await scanBytes({ name: path2, bytes: head, size: st.size, sha256 }, { signatures: opts.signatures });
41940
+ if (opts.reputation !== false) {
41941
+ const reps = await lookupHashes([sha256], { endpoint: opts.lookupEndpoint, timeoutMs: 8e3 });
41942
+ r = applyReputation(r, reps.get(sha256));
41943
+ }
41944
+ opts.onResult(r);
41945
+ } catch (e) {
41946
+ const code = e.code;
41947
+ if (code !== "ENOENT") opts.onError?.(path2, e);
41948
+ }
41949
+ };
41950
+ for (const t of targets) {
41951
+ try {
41952
+ const w = (0, import_node_fs26.watch)(t.path, { recursive: t.depth > 1, persistent: true }, (_event, file) => {
41953
+ if (!file) return;
41954
+ const rel = String(file);
41955
+ if (IN_PROGRESS.test(rel)) return;
41956
+ const parts = rel.split(/[\\/]/);
41957
+ if (parts.length > t.depth || parts.some((p) => SKIP_DIR_NAMES.has(p))) return;
41958
+ const full = (0, import_node_path23.join)(t.path, rel);
41959
+ const prev = timers.get(full);
41960
+ if (prev) clearTimeout(prev);
41961
+ timers.set(full, setTimeout(() => void scan(full), settle2));
41962
+ });
41963
+ w.on("error", (e) => opts.onError?.(t.path, e));
41964
+ watchers.push(w);
41965
+ } catch (e) {
41966
+ opts.onError?.(t.path, e);
41967
+ }
41968
+ }
41969
+ return () => {
41970
+ for (const w of watchers) w.close();
41971
+ for (const tm of timers.values()) clearTimeout(tm);
41972
+ timers.clear();
41973
+ };
41974
+ }
41975
+
41976
+ // src/commands/av.ts
41977
+ init_cli_config();
41978
+ var SIGNATURE_FILE = (0, import_node_path24.join)((0, import_node_os12.homedir)(), ".threatcrush", "av", "signatures.txt");
41979
+ 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");
41980
+ async function avScanCommand(paths, opts = {}) {
41981
+ let targets;
41982
+ let label;
41983
+ if (paths.length) {
41984
+ targets = paths.map((p) => ({ path: (0, import_node_path24.resolve)(p), depth: Infinity }));
41985
+ label = paths.join(", ");
41986
+ } else if (opts.full) {
41987
+ targets = fullScanTargets();
41988
+ label = "full scan (home folder + system startup and temp locations)";
41989
+ } else {
41990
+ targets = quickScanTargets();
41991
+ label = "quick scan (downloads, desktop, temp and startup locations)";
41992
+ }
41993
+ const missing = targets.filter((t) => !(0, import_node_fs27.existsSync)(t.path));
41994
+ if (paths.length && missing.length) {
41995
+ console.error(source_default.red(` Not found: ${missing.map((m) => m.path).join(", ")}`));
41996
+ process.exitCode = 2;
41997
+ return;
41998
+ }
41999
+ const spinner = opts.json ? null : ora({ text: `CrushAV ${label}`, discardStdin: false }).start();
42000
+ let lastPaint = 0;
42001
+ const report = await scanPaths(targets, {
42002
+ clamav: opts.requireClamav ? "require" : opts.clamav === false ? "off" : "auto",
42003
+ reputation: !opts.offline,
42004
+ lookupEndpoint: `${apiUrl()}/api/av/lookup`,
42005
+ signatureFile: SIGNATURE_FILE,
42006
+ maxFileBytes: opts.maxSize ? Number(opts.maxSize) * 1048576 : void 0,
42007
+ onProgress: (e) => {
42008
+ if (!spinner) return;
42009
+ if (e.type === "phase") {
42010
+ if (e.phase === "reputation") spinner.text = `Checking ${e.detail} against known malware and known-good files`;
42011
+ if (e.phase === "clamav") spinner.text = `ClamAV scanning ${e.detail}`;
42012
+ } else if (e.type === "file" && Date.now() - lastPaint > 120) {
42013
+ lastPaint = Date.now();
42014
+ const short2 = e.path.length > 70 ? `\u2026${e.path.slice(-69)}` : e.path;
42015
+ spinner.text = `${e.scanned} files ${source_default.gray(short2)}`;
42016
+ }
42017
+ }
42018
+ }).catch((e) => {
42019
+ spinner?.fail(e.message);
42020
+ if (/ClamAV/.test(e.message)) console.error(` Install it: ${source_default.cyan(clamInstallHint())}`);
42021
+ process.exitCode = 2;
42022
+ return null;
42023
+ });
42024
+ if (!report) return;
42025
+ spinner?.stop();
42026
+ const flagged = report.results.filter((r) => r.verdict === "malicious" || r.verdict === "suspicious");
42027
+ const quarantined = [];
42028
+ if (opts.quarantine) {
42029
+ for (const r of flagged.filter((x) => x.verdict === "malicious")) {
42030
+ try {
42031
+ const q = await quarantineFile(r.path, r.detections);
42032
+ quarantined.push({ path: r.path, id: q.id });
42033
+ } catch (e) {
42034
+ quarantined.push({ path: r.path, error: e.message });
42035
+ }
42036
+ }
42037
+ }
42038
+ if (opts.json) {
42039
+ console.log(JSON.stringify({ ...report, results: flagged, quarantined }, null, 2));
42040
+ } else {
42041
+ const s = report.summary;
42042
+ console.log();
42043
+ console.log(` ${source_default.bold("CrushAV")} ${source_default.gray(label)}`);
42044
+ console.log(` Engines: ${s.engines.join(", ")}${report.clamav?.available ? source_default.gray(` (${report.clamav.version})`) : ""}`);
42045
+ if (!report.clamav?.available && opts.clamav !== false) {
42046
+ console.log(source_default.gray(` Tip: install ClamAV for millions more signatures: ${clamInstallHint()}`));
42047
+ }
42048
+ if (report.clamavError) console.log(source_default.yellow(` ClamAV error: ${report.clamavError}`));
42049
+ console.log();
42050
+ for (const r of flagged) {
42051
+ console.log(` ${icon2(r.verdict)} ${r.path}`);
42052
+ for (const d of r.detections.filter((x) => x.impact !== "info")) {
42053
+ console.log(` ${source_default.bold(d.name)} ${source_default.gray(`[${d.engine}: ${d.id}]`)}`);
42054
+ console.log(` ${source_default.gray(d.description)}`);
42055
+ }
42056
+ }
42057
+ for (const q of quarantined) {
42058
+ console.log(q.id ? source_default.cyan(` Quarantined ${q.path} (id ${q.id})`) : source_default.red(` Could not quarantine ${q.path}: ${q.error}`));
42059
+ }
42060
+ console.log();
42061
+ const line2 = ` ${s.scanned} files scanned \xB7 ${source_default.red(`${s.malicious} malware`)} \xB7 ${source_default.yellow(`${s.suspicious} suspicious`)} \xB7 ${s.errors} unreadable \xB7 ${s.skipped} skipped`;
42062
+ console.log(line2);
42063
+ if (s.malicious && !opts.quarantine) console.log(source_default.gray(" Re-run with --quarantine to move malware somewhere it cannot run (reversible)."));
42064
+ if (!s.malicious && !s.suspicious) console.log(source_default.green(" Nothing found."));
42065
+ }
42066
+ if (report.summary.malicious > 0) process.exitCode = 1;
42067
+ }
42068
+ async function avStatusCommand(opts = {}) {
42069
+ const clam = await detectClamAV();
42070
+ const q = await listQuarantine();
42071
+ const status = {
42072
+ engine: "CrushAV",
42073
+ heuristic_rules: RULES.length,
42074
+ custom_signatures: (0, import_node_fs27.existsSync)(SIGNATURE_FILE) ? SIGNATURE_FILE : null,
42075
+ clamav: clam,
42076
+ reputation_endpoint: `${apiUrl()}/api/av/lookup`,
42077
+ quarantine_dir: quarantineDir(),
42078
+ quarantined: q.length
42079
+ };
42080
+ if (opts.json) {
42081
+ console.log(JSON.stringify(status, null, 2));
42082
+ return;
42083
+ }
42084
+ console.log(` ${source_default.bold("CrushAV")} free, open-source antivirus`);
42085
+ console.log(` Heuristic rules: ${RULES.length}`);
42086
+ console.log(` ClamAV: ${clam.available ? source_default.green(`${clam.version} via ${clam.mode}`) : source_default.yellow("not installed")}`);
42087
+ if (!clam.available) console.log(source_default.gray(` ${clamInstallHint()}`));
42088
+ console.log(` Hash reputation: ${status.reputation_endpoint}`);
42089
+ console.log(` Custom signatures: ${status.custom_signatures ?? source_default.gray(`none (add sha256 lines to ${SIGNATURE_FILE})`)}`);
42090
+ console.log(` Quarantine: ${q.length} file(s) in ${status.quarantine_dir}`);
42091
+ }
42092
+ async function avQuarantineCommand(action = "list", id, opts = {}) {
42093
+ try {
42094
+ if (action === "list") {
42095
+ const entries = await listQuarantine();
42096
+ if (opts.json) {
42097
+ console.log(JSON.stringify(entries, null, 2));
42098
+ return;
42099
+ }
42100
+ if (!entries.length) {
42101
+ console.log(" Quarantine is empty.");
42102
+ return;
42103
+ }
42104
+ for (const e of entries) {
42105
+ console.log(` ${source_default.cyan(e.id)} ${e.originalPath}`);
42106
+ console.log(source_default.gray(` ${e.quarantinedAt} \xB7 ${e.detections.map((d) => d.name).join(", ") || "manual"}`));
42107
+ }
42108
+ return;
42109
+ }
42110
+ if (!id) throw new Error(`usage: threatcrush av quarantine ${action} <id>`);
42111
+ if (action === "restore") {
42112
+ const dest = await restoreQuarantined(id, opts.to ? (0, import_node_path24.resolve)(opts.to) : void 0);
42113
+ console.log(source_default.yellow(` Restored to ${dest}. It was quarantined for a reason; scan it again before opening.`));
42114
+ } else if (action === "delete") {
42115
+ await deleteQuarantined(id);
42116
+ console.log(source_default.green(` Deleted ${id} permanently.`));
42117
+ } else if (action === "add") {
42118
+ const e = await quarantineFile((0, import_node_path24.resolve)(id));
42119
+ console.log(source_default.cyan(` Quarantined ${e.originalPath} (id ${e.id})`));
42120
+ } else {
42121
+ throw new Error(`unknown action "${action}". Use list, add, restore or delete.`);
42122
+ }
42123
+ } catch (e) {
42124
+ console.error(source_default.red(` ${e.message}`));
42125
+ process.exitCode = 1;
42126
+ }
42127
+ }
42128
+ async function avWatchCommand(paths, opts = {}) {
42129
+ const targets = paths.length ? paths.map((p) => ({ path: (0, import_node_path24.resolve)(p), depth: Infinity })) : quickScanTargets();
42130
+ if (!opts.json) {
42131
+ console.log(` ${source_default.bold("CrushAV")} real-time protection is watching:`);
42132
+ for (const t of targets) console.log(source_default.gray(` ${t.path}`));
42133
+ console.log(source_default.gray(" New and changed files are scanned as they arrive. Ctrl+C to stop."));
42134
+ }
42135
+ const stop = watchTargets(targets, {
42136
+ reputation: !opts.offline,
42137
+ lookupEndpoint: `${apiUrl()}/api/av/lookup`,
42138
+ onResult: async (r) => {
42139
+ let quarantinedId;
42140
+ if (opts.quarantine && r.verdict === "malicious") {
42141
+ try {
42142
+ quarantinedId = (await quarantineFile(r.path, r.detections)).id;
42143
+ } catch {
42144
+ }
42145
+ }
42146
+ if (opts.json) {
42147
+ console.log(JSON.stringify({ ...r, quarantined: quarantinedId ?? null }));
42148
+ return;
42149
+ }
42150
+ if (r.verdict === "clean") {
42151
+ console.log(source_default.gray(` \u2713 ${r.path}`));
42152
+ return;
42153
+ }
42154
+ console.log(` ${icon2(r.verdict)} ${r.path}`);
42155
+ for (const d of r.detections.filter((x) => x.impact !== "info")) console.log(` ${source_default.bold(d.name)} ${source_default.gray(d.description)}`);
42156
+ if (quarantinedId) console.log(source_default.cyan(` Quarantined (id ${quarantinedId}).`));
42157
+ },
42158
+ onError: (p, e) => {
42159
+ if (!opts.json) console.error(source_default.yellow(` cannot watch/scan ${p}: ${e.message}`));
42160
+ }
42161
+ });
42162
+ await new Promise((done) => {
42163
+ const quit = () => {
42164
+ stop();
42165
+ done();
42166
+ };
42167
+ process.once("SIGINT", quit);
42168
+ process.once("SIGTERM", quit);
42169
+ });
42170
+ }
42171
+ async function avTestCommand() {
42172
+ const r = await scanBytes({ name: "eicar.com", bytes: new TextEncoder().encode(EICAR) });
42173
+ const ok = r.verdict === "malicious";
42174
+ console.log(ok ? source_default.green(" \u2713 CrushAV detected the EICAR test file (in memory, nothing written).") : source_default.red(" \u2716 EICAR was not detected. Please report this."));
42175
+ const clam = await detectClamAV();
42176
+ console.log(clam.available ? source_default.green(` \u2713 ClamAV ready: ${clam.version}`) : source_default.yellow(` \u25B2 ClamAV not installed. ${clamInstallHint()}`));
42177
+ if (!ok) process.exitCode = 1;
42178
+ }
42179
+
42180
+ // src/commands/ai-scan.ts
42181
+ var import_node_fs29 = require("fs");
40799
42182
 
40800
42183
  // src/aiscan/probes.ts
40801
42184
  function makeCanary() {
@@ -41012,9 +42395,9 @@ ${stripShebang(source)}
41012
42395
  }
41013
42396
 
41014
42397
  // src/core/usage-ping.ts
41015
- var import_node_crypto6 = require("crypto");
41016
- var import_node_fs22 = require("fs");
41017
- var import_node_path19 = require("path");
42398
+ var import_node_crypto8 = require("crypto");
42399
+ var import_node_fs28 = require("fs");
42400
+ var import_node_path25 = require("path");
41018
42401
  init_cli_config();
41019
42402
  var STATE_FILE = "usage-ping.json";
41020
42403
  function usagePingDisabled(env3 = process.env) {
@@ -41024,16 +42407,16 @@ function usagePingDisabled(env3 = process.env) {
41024
42407
  return dnt !== "" && dnt !== "0" && dnt !== "false";
41025
42408
  }
41026
42409
  function installId(dir = CLI_CONFIG_DIR) {
41027
- const file = (0, import_node_path19.join)(dir, STATE_FILE);
42410
+ const file = (0, import_node_path25.join)(dir, STATE_FILE);
41028
42411
  try {
41029
- const j = JSON.parse((0, import_node_fs22.readFileSync)(file, "utf-8"));
42412
+ const j = JSON.parse((0, import_node_fs28.readFileSync)(file, "utf-8"));
41030
42413
  if (j.install_id) return { id: j.install_id, fresh: false };
41031
42414
  } catch {
41032
42415
  }
41033
- const id = (0, import_node_crypto6.randomUUID)();
42416
+ const id = (0, import_node_crypto8.randomUUID)();
41034
42417
  try {
41035
- if (!(0, import_node_fs22.existsSync)(dir)) (0, import_node_fs22.mkdirSync)(dir, { recursive: true });
41036
- (0, import_node_fs22.writeFileSync)(file, JSON.stringify({ install_id: id, created_at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
42418
+ if (!(0, import_node_fs28.existsSync)(dir)) (0, import_node_fs28.mkdirSync)(dir, { recursive: true });
42419
+ (0, import_node_fs28.writeFileSync)(file, JSON.stringify({ install_id: id, created_at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
41037
42420
  } catch {
41038
42421
  }
41039
42422
  return { id, fresh: true };
@@ -41141,7 +42524,7 @@ async function aiScanMoshCommand(file, args) {
41141
42524
  console.log();
41142
42525
  let source;
41143
42526
  try {
41144
- source = (0, import_node_fs23.readFileSync)(file, "utf-8");
42527
+ source = (0, import_node_fs29.readFileSync)(file, "utf-8");
41145
42528
  } catch (err) {
41146
42529
  logger.error(`Cannot read ${file}: ${err.message}`);
41147
42530
  process.exitCode = 1;
@@ -41170,22 +42553,22 @@ async function aiScanMoshCommand(file, args) {
41170
42553
  }
41171
42554
 
41172
42555
  // src/commands/orgs.ts
41173
- var import_node_os9 = require("os");
41174
- var import_node_fs24 = require("fs");
41175
- var import_node_path20 = require("path");
42556
+ var import_node_os13 = require("os");
42557
+ var import_node_fs30 = require("fs");
42558
+ var import_node_path26 = require("path");
41176
42559
  var API_URL3 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
41177
- var CONFIG_PATH = (0, import_node_path20.join)((0, import_node_os9.homedir)(), ".threatcrush", "config.json");
42560
+ var CONFIG_PATH = (0, import_node_path26.join)((0, import_node_os13.homedir)(), ".threatcrush", "config.json");
41178
42561
  function readConfig() {
41179
42562
  try {
41180
- return JSON.parse((0, import_node_fs24.readFileSync)(CONFIG_PATH, "utf-8"));
42563
+ return JSON.parse((0, import_node_fs30.readFileSync)(CONFIG_PATH, "utf-8"));
41181
42564
  } catch {
41182
42565
  return {};
41183
42566
  }
41184
42567
  }
41185
42568
  function writeConfig(config) {
41186
- const dir = (0, import_node_path20.join)((0, import_node_os9.homedir)(), ".threatcrush");
41187
- if (!(0, import_node_fs24.existsSync)(dir)) (0, import_node_fs24.mkdirSync)(dir, { recursive: true });
41188
- (0, import_node_fs24.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
42569
+ const dir = (0, import_node_path26.join)((0, import_node_os13.homedir)(), ".threatcrush");
42570
+ if (!(0, import_node_fs30.existsSync)(dir)) (0, import_node_fs30.mkdirSync)(dir, { recursive: true });
42571
+ (0, import_node_fs30.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
41189
42572
  }
41190
42573
  function getAuthHeaders() {
41191
42574
  const config = readConfig();
@@ -41320,14 +42703,14 @@ async function useOrganization(slug) {
41320
42703
  }
41321
42704
 
41322
42705
  // src/commands/credits.ts
41323
- var import_node_os10 = require("os");
41324
- var import_node_fs25 = require("fs");
41325
- var import_node_path21 = require("path");
42706
+ var import_node_os14 = require("os");
42707
+ var import_node_fs31 = require("fs");
42708
+ var import_node_path27 = require("path");
41326
42709
  var API_URL4 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
41327
- var CONFIG_PATH2 = (0, import_node_path21.join)((0, import_node_os10.homedir)(), ".threatcrush", "config.json");
42710
+ var CONFIG_PATH2 = (0, import_node_path27.join)((0, import_node_os14.homedir)(), ".threatcrush", "config.json");
41328
42711
  function sessionToken() {
41329
42712
  try {
41330
- const cfg = JSON.parse((0, import_node_fs25.readFileSync)(CONFIG_PATH2, "utf-8"));
42713
+ const cfg = JSON.parse((0, import_node_fs31.readFileSync)(CONFIG_PATH2, "utf-8"));
41331
42714
  return cfg.token ?? null;
41332
42715
  } catch {
41333
42716
  return null;
@@ -41396,7 +42779,7 @@ async function invitesCommand(action = "list", arg, f = fetch) {
41396
42779
  }
41397
42780
 
41398
42781
  // src/commands/fleet.ts
41399
- var import_promises = require("fs/promises");
42782
+ var import_promises5 = require("fs/promises");
41400
42783
  init_cli_config();
41401
42784
  async function call(path2, init = {}) {
41402
42785
  const res = await cloudFetch(path2, init);
@@ -41435,7 +42818,7 @@ async function readInventorySource(source, f = fetch) {
41435
42818
  if (!res.ok) throw new Error(`${source} answered ${res.status}`);
41436
42819
  return res.text();
41437
42820
  }
41438
- return (0, import_promises.readFile)(source, "utf-8");
42821
+ return (0, import_promises5.readFile)(source, "utf-8");
41439
42822
  }
41440
42823
  async function fleetImportCommand(source, opts = {}) {
41441
42824
  let text;
@@ -41493,7 +42876,7 @@ function formatTotal(monthly) {
41493
42876
 
41494
42877
  // src/commands/servers.ts
41495
42878
  var import_node_readline2 = __toESM(require("readline"));
41496
- var import_node_os11 = require("os");
42879
+ var import_node_os15 = require("os");
41497
42880
  init_cli_config();
41498
42881
  function connectionStatus(server, now = Date.now()) {
41499
42882
  const seen = server.last_seen ? Date.parse(server.last_seen) : NaN;
@@ -41565,9 +42948,9 @@ async function fetchOrgs() {
41565
42948
  }
41566
42949
  function askChoice(question) {
41567
42950
  const rl = import_node_readline2.default.createInterface({ input: process.stdin, output: process.stdout });
41568
- return new Promise((resolve8) => rl.question(question, (answer) => {
42951
+ return new Promise((resolve9) => rl.question(question, (answer) => {
41569
42952
  rl.close();
41570
- resolve8(answer.trim());
42953
+ resolve9(answer.trim());
41571
42954
  }));
41572
42955
  }
41573
42956
  async function chooseOrg(orgs, flag, ask2) {
@@ -41592,7 +42975,7 @@ async function chooseOrg(orgs, flag, ask2) {
41592
42975
  async function linkServer(opts = {}, ask2 = askChoice) {
41593
42976
  if (!hasSession()) throw new Error("Not logged in. Run: threatcrush login");
41594
42977
  const org = await chooseOrg(await fetchOrgs(), opts.org, ask2);
41595
- const host = opts.hostname ?? (0, import_node_os11.hostname)();
42978
+ const host = opts.hostname ?? (0, import_node_os15.hostname)();
41596
42979
  const listRes = await cloudFetch(`/api/orgs/${org.id}/servers`);
41597
42980
  if (!listRes.ok) throw new Error(`Failed to list servers in /${org.slug} (${listRes.status})`);
41598
42981
  const { servers = [] } = await listRes.json();
@@ -41709,16 +43092,16 @@ function timeAgo(dateStr) {
41709
43092
  }
41710
43093
 
41711
43094
  // src/commands/connect.ts
41712
- var import_node_os12 = require("os");
41713
- var import_node_fs26 = require("fs");
41714
- var import_node_path22 = require("path");
41715
- var import_node_child_process5 = require("child_process");
43095
+ var import_node_os16 = require("os");
43096
+ var import_node_fs32 = require("fs");
43097
+ var import_node_path28 = require("path");
43098
+ var import_node_child_process6 = require("child_process");
41716
43099
  var import_node_net4 = require("net");
41717
43100
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
41718
- var CONFIG_PATH3 = (0, import_node_path22.join)((0, import_node_os12.homedir)(), ".threatcrush", "config.json");
43101
+ var CONFIG_PATH3 = (0, import_node_path28.join)((0, import_node_os16.homedir)(), ".threatcrush", "config.json");
41719
43102
  function readConfig2() {
41720
43103
  try {
41721
- return JSON.parse((0, import_node_fs26.readFileSync)(CONFIG_PATH3, "utf-8"));
43104
+ return JSON.parse((0, import_node_fs32.readFileSync)(CONFIG_PATH3, "utf-8"));
41722
43105
  } catch {
41723
43106
  return {};
41724
43107
  }
@@ -41871,7 +43254,7 @@ async function sshConnect(options) {
41871
43254
  `));
41872
43255
  console.log(source_default.dim(" (Spawning SSH session \u2014 exit with Ctrl+D or type 'exit')\n"));
41873
43256
  const sshArgs = sshArgv({ hostname: hostname7, username: user, port, identity });
41874
- const ssh = (0, import_node_child_process5.spawn)("ssh", sshArgs, { stdio: "inherit" });
43257
+ const ssh = (0, import_node_child_process6.spawn)("ssh", sshArgs, { stdio: "inherit" });
41875
43258
  ssh.on("error", (err) => {
41876
43259
  console.log(source_default.red(`
41877
43260
  SSH error: ${err.message}
@@ -41889,22 +43272,22 @@ async function sshConnect(options) {
41889
43272
  }
41890
43273
 
41891
43274
  // src/commands/daemon.ts
41892
- var import_node_child_process20 = require("child_process");
41893
- var import_node_fs52 = require("fs");
41894
- var import_node_path40 = require("path");
41895
- var import_node_fs53 = require("fs");
43275
+ var import_node_child_process21 = require("child_process");
43276
+ var import_node_fs58 = require("fs");
43277
+ var import_node_path46 = require("path");
43278
+ var import_node_fs59 = require("fs");
41896
43279
 
41897
43280
  // src/daemon/index.ts
41898
- var import_node_fs51 = require("fs");
41899
- var import_node_child_process19 = require("child_process");
41900
- var import_node_os14 = require("os");
41901
- var import_node_path39 = require("path");
43281
+ var import_node_fs57 = require("fs");
43282
+ var import_node_child_process20 = require("child_process");
43283
+ var import_node_os18 = require("os");
43284
+ var import_node_path45 = require("path");
41902
43285
  var import_node_util4 = require("util");
41903
43286
  init_paths();
41904
43287
 
41905
43288
  // src/daemon/ipc-server.ts
41906
43289
  var import_node_net5 = require("net");
41907
- var import_node_fs27 = require("fs");
43290
+ var import_node_fs33 = require("fs");
41908
43291
  init_paths();
41909
43292
  init_control_token();
41910
43293
 
@@ -41962,13 +43345,13 @@ var IpcServer = class {
41962
43345
  controlToken = "";
41963
43346
  async start() {
41964
43347
  this.controlToken = issueControlToken();
41965
- if ((0, import_node_fs27.existsSync)(PATHS.socket)) {
43348
+ if ((0, import_node_fs33.existsSync)(PATHS.socket)) {
41966
43349
  try {
41967
- (0, import_node_fs27.unlinkSync)(PATHS.socket);
43350
+ (0, import_node_fs33.unlinkSync)(PATHS.socket);
41968
43351
  } catch {
41969
43352
  }
41970
43353
  }
41971
- return new Promise((resolve8, reject) => {
43354
+ return new Promise((resolve9, reject) => {
41972
43355
  this.server = (0, import_node_net5.createServer)((sock) => this.handleClient(sock));
41973
43356
  this.server.on("error", reject);
41974
43357
  this.server.listen(PATHS.socket, () => {
@@ -41987,7 +43370,7 @@ var IpcServer = class {
41987
43370
  }
41988
43371
  }
41989
43372
  }
41990
- resolve8();
43373
+ resolve9();
41991
43374
  });
41992
43375
  });
41993
43376
  }
@@ -41999,20 +43382,20 @@ var IpcServer = class {
41999
43382
  }
42000
43383
  }
42001
43384
  this.clients.clear();
42002
- return new Promise((resolve8) => {
43385
+ return new Promise((resolve9) => {
42003
43386
  if (!this.server) {
42004
43387
  try {
42005
- if ((0, import_node_fs27.existsSync)(PATHS.socket)) (0, import_node_fs27.unlinkSync)(PATHS.socket);
43388
+ if ((0, import_node_fs33.existsSync)(PATHS.socket)) (0, import_node_fs33.unlinkSync)(PATHS.socket);
42006
43389
  } catch {
42007
43390
  }
42008
- return resolve8();
43391
+ return resolve9();
42009
43392
  }
42010
43393
  this.server.close(() => {
42011
43394
  try {
42012
- if ((0, import_node_fs27.existsSync)(PATHS.socket)) (0, import_node_fs27.unlinkSync)(PATHS.socket);
43395
+ if ((0, import_node_fs33.existsSync)(PATHS.socket)) (0, import_node_fs33.unlinkSync)(PATHS.socket);
42013
43396
  } catch {
42014
43397
  }
42015
- resolve8();
43398
+ resolve9();
42016
43399
  });
42017
43400
  });
42018
43401
  }
@@ -42189,7 +43572,7 @@ var IpcServer = class {
42189
43572
  }
42190
43573
  }
42191
43574
  };
42192
- function admGid(readGroup = () => (0, import_node_fs27.readFileSync)("/etc/group", "utf-8"), statAuthLog = () => (0, import_node_fs27.statSync)("/var/log/auth.log")) {
43575
+ function admGid(readGroup = () => (0, import_node_fs33.readFileSync)("/etc/group", "utf-8"), statAuthLog = () => (0, import_node_fs33.statSync)("/var/log/auth.log")) {
42193
43576
  try {
42194
43577
  for (const line2 of readGroup().split("\n")) {
42195
43578
  const [name, , gid] = line2.split(":");
@@ -42205,14 +43588,14 @@ function admGid(readGroup = () => (0, import_node_fs27.readFileSync)("/etc/group
42205
43588
  }
42206
43589
 
42207
43590
  // src/daemon/module-host.ts
42208
- var import_node_fs33 = require("fs");
42209
- var import_node_path24 = require("path");
43591
+ var import_node_fs39 = require("fs");
43592
+ var import_node_path30 = require("path");
42210
43593
  var import_node_url = require("url");
42211
43594
  var import_toml4 = __toESM(require_toml());
42212
43595
  init_paths();
42213
43596
 
42214
43597
  // src/daemon/watchers/log-watcher.ts
42215
- var import_node_fs28 = require("fs");
43598
+ var import_node_fs34 = require("fs");
42216
43599
  var DEFAULT_SOURCES = [
42217
43600
  { path: "/var/log/auth.log", module: "ssh-guard", category: "auth" },
42218
43601
  { path: "/var/log/secure", module: "ssh-guard", category: "auth" },
@@ -42235,9 +43618,9 @@ var LogWatcher = class {
42235
43618
  start() {
42236
43619
  const started = [];
42237
43620
  for (const src of this.sources) {
42238
- if (!(0, import_node_fs28.existsSync)(src.path)) continue;
43621
+ if (!(0, import_node_fs34.existsSync)(src.path)) continue;
42239
43622
  try {
42240
- (0, import_node_fs28.accessSync)(src.path, import_node_fs28.constants.R_OK);
43623
+ (0, import_node_fs34.accessSync)(src.path, import_node_fs34.constants.R_OK);
42241
43624
  } catch {
42242
43625
  continue;
42243
43626
  }
@@ -42398,13 +43781,13 @@ var JournalProvenance = class {
42398
43781
  };
42399
43782
 
42400
43783
  // src/daemon/watchers/journal-watcher.ts
42401
- var import_node_child_process6 = require("child_process");
43784
+ var import_node_child_process7 = require("child_process");
42402
43785
  var SSHD_COMMS = ["sshd", "sshd-session"];
42403
43786
  var accountNames = /* @__PURE__ */ new Map();
42404
43787
  function accountNameForUid(value) {
42405
43788
  if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
42406
43789
  if (accountNames.has(value)) return accountNames.get(value) ?? null;
42407
- const result = (0, import_node_child_process6.spawnSync)("getent", ["passwd", value], {
43790
+ const result = (0, import_node_child_process7.spawnSync)("getent", ["passwd", value], {
42408
43791
  encoding: "utf-8",
42409
43792
  timeout: 1e3,
42410
43793
  maxBuffer: 4096,
@@ -42467,14 +43850,14 @@ var JournalWatcher = class _JournalWatcher {
42467
43850
  return isRoot4 ? [] : ["--user"];
42468
43851
  }
42469
43852
  static isAvailable() {
42470
- const probe = (0, import_node_child_process6.spawnSync)("journalctl", [...this.scopeArgs(), "-n", "0", "--no-pager"], {
43853
+ const probe = (0, import_node_child_process7.spawnSync)("journalctl", [...this.scopeArgs(), "-n", "0", "--no-pager"], {
42471
43854
  stdio: ["ignore", "ignore", "ignore"]
42472
43855
  });
42473
43856
  return probe.status === 0;
42474
43857
  }
42475
43858
  start() {
42476
43859
  if (!_JournalWatcher.isAvailable()) return false;
42477
- const child = (0, import_node_child_process6.spawn)(
43860
+ const child = (0, import_node_child_process7.spawn)(
42478
43861
  "journalctl",
42479
43862
  [..._JournalWatcher.scopeArgs(), "-o", "json", "-f", "--since", "now"],
42480
43863
  { stdio: ["ignore", "pipe", "pipe"] }
@@ -42499,14 +43882,14 @@ var JournalWatcher = class _JournalWatcher {
42499
43882
  * nothing and looking like protection.
42500
43883
  */
42501
43884
  startSshd() {
42502
- const probe = (0, import_node_child_process6.spawnSync)("journalctl", ["-q", "-n", "1", "-o", "cat", "--no-pager", "_UID=0"], {
43885
+ const probe = (0, import_node_child_process7.spawnSync)("journalctl", ["-q", "-n", "1", "-o", "cat", "--no-pager", "_UID=0"], {
42503
43886
  stdio: ["ignore", "pipe", "ignore"],
42504
43887
  encoding: "utf-8"
42505
43888
  });
42506
43889
  if (probe.error || probe.status !== 0) return "unavailable";
42507
43890
  if (!probe.stdout.trim()) return "unreadable";
42508
43891
  const matches2 = ["_UID=0", ...SSHD_COMMS.map((comm) => `_COMM=${comm}`)];
42509
- const child = (0, import_node_child_process6.spawn)("journalctl", ["-o", "json", "-f", "--since", "now", ...matches2], {
43892
+ const child = (0, import_node_child_process7.spawn)("journalctl", ["-o", "json", "-f", "--since", "now", ...matches2], {
42510
43893
  stdio: ["ignore", "pipe", "ignore"]
42511
43894
  });
42512
43895
  if (!child.stdout) return "unavailable";
@@ -42622,8 +44005,8 @@ function realtimeToDate(rt) {
42622
44005
  }
42623
44006
 
42624
44007
  // src/modules/network-monitor/index.ts
42625
- var import_node_child_process7 = require("child_process");
42626
- var import_node_fs29 = require("fs");
44008
+ var import_node_child_process8 = require("child_process");
44009
+ var import_node_fs35 = require("fs");
42627
44010
  var NetworkMonitor = class {
42628
44011
  constructor(bus2) {
42629
44012
  this.bus = bus2;
@@ -42685,9 +44068,9 @@ var NetworkMonitor = class {
42685
44068
  return this.active;
42686
44069
  }
42687
44070
  hasConntrackOrSs() {
42688
- const ss = (0, import_node_child_process7.spawnSync)("ss", ["--version"], { stdio: "pipe" });
44071
+ const ss = (0, import_node_child_process8.spawnSync)("ss", ["--version"], { stdio: "pipe" });
42689
44072
  if (ss.status === 0) return true;
42690
- return (0, import_node_fs29.existsSync)("/proc/net/tcp");
44073
+ return (0, import_node_fs35.existsSync)("/proc/net/tcp");
42691
44074
  }
42692
44075
  /**
42693
44076
  * The TCP ports this host actually listens on.
@@ -42702,7 +44085,7 @@ var NetworkMonitor = class {
42702
44085
  listeningPorts() {
42703
44086
  const ports = /* @__PURE__ */ new Set();
42704
44087
  try {
42705
- const out = (0, import_node_child_process7.spawnSync)("ss", ["-ltnH"], { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"], timeout: 3e3 });
44088
+ const out = (0, import_node_child_process8.spawnSync)("ss", ["-ltnH"], { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"], timeout: 3e3 });
42706
44089
  if (out.status === 0 && out.stdout) {
42707
44090
  for (const line2 of out.stdout.split("\n")) {
42708
44091
  const parts = line2.trim().split(/\s+/);
@@ -42733,7 +44116,7 @@ var NetworkMonitor = class {
42733
44116
  const listening = this.listeningPorts();
42734
44117
  if (listening.size === 0) return records;
42735
44118
  try {
42736
- const ct = (0, import_node_child_process7.spawnSync)("conntrack", ["-L", "-p", "tcp", "-o", "extended"], {
44119
+ const ct = (0, import_node_child_process8.spawnSync)("conntrack", ["-L", "-p", "tcp", "-o", "extended"], {
42737
44120
  encoding: "utf-8",
42738
44121
  stdio: ["pipe", "pipe", "pipe"],
42739
44122
  timeout: 3e3
@@ -42753,7 +44136,7 @@ var NetworkMonitor = class {
42753
44136
  } catch {
42754
44137
  }
42755
44138
  try {
42756
- const ss = (0, import_node_child_process7.spawnSync)("ss", ["-tnp", "-H"], {
44139
+ const ss = (0, import_node_child_process8.spawnSync)("ss", ["-tnp", "-H"], {
42757
44140
  encoding: "utf-8",
42758
44141
  stdio: ["pipe", "pipe", "pipe"],
42759
44142
  timeout: 3e3
@@ -42817,7 +44200,7 @@ var NetworkMonitor = class {
42817
44200
  }
42818
44201
  analyzeSynFlood(connections) {
42819
44202
  try {
42820
- const ss = (0, import_node_child_process7.spawnSync)("ss", ["-tn", "state", "syn-recv", "-H"], {
44203
+ const ss = (0, import_node_child_process8.spawnSync)("ss", ["-tn", "state", "syn-recv", "-H"], {
42821
44204
  encoding: "utf-8",
42822
44205
  stdio: ["pipe", "pipe", "pipe"],
42823
44206
  timeout: 3e3
@@ -42874,18 +44257,18 @@ var NetworkMonitor = class {
42874
44257
  };
42875
44258
 
42876
44259
  // src/modules/dns-monitor/index.ts
42877
- var import_node_fs32 = require("fs");
42878
- var import_node_child_process9 = require("child_process");
44260
+ var import_node_fs38 = require("fs");
44261
+ var import_node_child_process10 = require("child_process");
42879
44262
  var import_node_readline3 = require("readline");
42880
44263
 
42881
44264
  // src/core/threat-feeds/index.ts
42882
- var import_node_fs31 = require("fs");
42883
- var import_node_path23 = require("path");
44265
+ var import_node_fs37 = require("fs");
44266
+ var import_node_path29 = require("path");
42884
44267
  var import_node_net7 = require("net");
42885
44268
 
42886
44269
  // src/daemon/firewall/protected.ts
42887
- var import_node_child_process8 = require("child_process");
42888
- var import_node_fs30 = require("fs");
44270
+ var import_node_child_process9 = require("child_process");
44271
+ var import_node_fs36 = require("fs");
42889
44272
  var import_node_net6 = require("net");
42890
44273
  var DEFAULT_PROTECTED = [
42891
44274
  "127.0.0.0/8",
@@ -42894,6 +44277,12 @@ var DEFAULT_PROTECTED = [
42894
44277
  "172.16.0.0/12",
42895
44278
  "192.168.0.0/16",
42896
44279
  "169.254.0.0/16",
44280
+ // RFC 6598 shared address space. Never routed on the public internet, so a
44281
+ // source here is a tailnet peer (Tailscale hands out 100.64.0.0/10) or the
44282
+ // carrier's own NAT, not an attacker. 2026-11-02: dev3's port-scan detector
44283
+ // banned a Tailscale peer four times for dialling several c0mpute ports.
44284
+ // Tailscale's IPv6 range (fd7a:115c:a1e0::/48) is already inside fc00::/7.
44285
+ "100.64.0.0/10",
42897
44286
  "fc00::/7",
42898
44287
  "fe80::/10"
42899
44288
  ];
@@ -43013,7 +44402,7 @@ function currentSshClient(env3 = process.env) {
43013
44402
  function establishedSshPeers() {
43014
44403
  const peers = /* @__PURE__ */ new Set();
43015
44404
  try {
43016
- const out = (0, import_node_child_process8.execFileSync)("ss", ["-tnpH"], {
44405
+ const out = (0, import_node_child_process9.execFileSync)("ss", ["-tnpH"], {
43017
44406
  encoding: "utf-8",
43018
44407
  stdio: ["ignore", "pipe", "ignore"],
43019
44408
  timeout: 3e3
@@ -43041,14 +44430,14 @@ function moshClients(procDir = "/proc") {
43041
44430
  const found = /* @__PURE__ */ new Set();
43042
44431
  let pids = [];
43043
44432
  try {
43044
- pids = (0, import_node_fs30.readdirSync)(procDir).filter((p) => /^\d+$/.test(p));
44433
+ pids = (0, import_node_fs36.readdirSync)(procDir).filter((p) => /^\d+$/.test(p));
43045
44434
  } catch {
43046
44435
  return [];
43047
44436
  }
43048
44437
  for (const pid of pids) {
43049
44438
  try {
43050
- if ((0, import_node_fs30.readFileSync)(`${procDir}/${pid}/comm`, "utf-8").trim() !== "mosh-server") continue;
43051
- const ip = sshClientFromEnviron((0, import_node_fs30.readFileSync)(`${procDir}/${pid}/environ`, "latin1"));
44439
+ if ((0, import_node_fs36.readFileSync)(`${procDir}/${pid}/comm`, "utf-8").trim() !== "mosh-server") continue;
44440
+ const ip = sshClientFromEnviron((0, import_node_fs36.readFileSync)(`${procDir}/${pid}/environ`, "latin1"));
43052
44441
  if (ip) found.add(ip);
43053
44442
  } catch {
43054
44443
  }
@@ -43073,7 +44462,7 @@ function defaultGateways() {
43073
44462
  const found = /* @__PURE__ */ new Set();
43074
44463
  for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
43075
44464
  try {
43076
- const out = (0, import_node_child_process8.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
44465
+ const out = (0, import_node_child_process9.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
43077
44466
  for (const line2 of out.split("\n")) {
43078
44467
  const match = line2.match(/\bvia\s+(\S+)/);
43079
44468
  if (match && (0, import_node_net6.isIP)(match[1])) found.add(match[1]);
@@ -43254,17 +44643,17 @@ async function fetchFeeds(settings, fetchImpl = fetch) {
43254
44643
  }
43255
44644
  function readFeedCache(path2) {
43256
44645
  try {
43257
- const set = JSON.parse((0, import_node_fs31.readFileSync)(path2, "utf-8"));
44646
+ const set = JSON.parse((0, import_node_fs37.readFileSync)(path2, "utf-8"));
43258
44647
  return set && typeof set.ips === "object" && typeof set.domains === "object" ? set : null;
43259
44648
  } catch {
43260
44649
  return null;
43261
44650
  }
43262
44651
  }
43263
44652
  function writeFeedCache(path2, set) {
43264
- (0, import_node_fs31.mkdirSync)((0, import_node_path23.dirname)(path2), { recursive: true });
44653
+ (0, import_node_fs37.mkdirSync)((0, import_node_path29.dirname)(path2), { recursive: true });
43265
44654
  const tmp = `${path2}.tmp`;
43266
- (0, import_node_fs31.writeFileSync)(tmp, JSON.stringify(set));
43267
- (0, import_node_fs31.renameSync)(tmp, path2);
44655
+ (0, import_node_fs37.writeFileSync)(tmp, JSON.stringify(set));
44656
+ (0, import_node_fs37.renameSync)(tmp, path2);
43268
44657
  }
43269
44658
  var RESOLVER_FILES = {
43270
44659
  hosts: "blocked-domains.hosts",
@@ -43377,7 +44766,7 @@ var DnsMonitor = class {
43377
44766
  /** True if a systemd unit is loaded on this host (so we do not tail nothing). */
43378
44767
  unitExists(unit) {
43379
44768
  try {
43380
- const r = (0, import_node_child_process9.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
44769
+ const r = (0, import_node_child_process10.spawnSync)("systemctl", ["show", unit, "--property=LoadState", "--value"], {
43381
44770
  encoding: "utf-8",
43382
44771
  stdio: ["ignore", "pipe", "ignore"],
43383
44772
  timeout: 3e3
@@ -43389,9 +44778,9 @@ var DnsMonitor = class {
43389
44778
  }
43390
44779
  start() {
43391
44780
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
43392
- if (!(0, import_node_fs32.existsSync)(p)) return false;
44781
+ if (!(0, import_node_fs38.existsSync)(p)) return false;
43393
44782
  try {
43394
- (0, import_node_fs32.accessSync)(p, import_node_fs32.constants.R_OK);
44783
+ (0, import_node_fs38.accessSync)(p, import_node_fs38.constants.R_OK);
43395
44784
  return true;
43396
44785
  } catch {
43397
44786
  return false;
@@ -43450,7 +44839,7 @@ var DnsMonitor = class {
43450
44839
  /** Follow one systemd unit's journal, feeding its lines to the same parser. */
43451
44840
  tailJournalUnit(unit) {
43452
44841
  try {
43453
- const child = (0, import_node_child_process9.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
44842
+ const child = (0, import_node_child_process10.spawn)("journalctl", ["-u", unit, "-f", "-n", "0", "--output=cat"], {
43454
44843
  stdio: ["ignore", "pipe", "ignore"]
43455
44844
  });
43456
44845
  if (!child.stdout) return;
@@ -43748,15 +45137,15 @@ var ModuleHost = class {
43748
45137
  }
43749
45138
  }
43750
45139
  async discoverAndStartInstalled() {
43751
- if (!(0, import_node_fs33.existsSync)(PATHS.moduleDir)) return;
45140
+ if (!(0, import_node_fs39.existsSync)(PATHS.moduleDir)) return;
43752
45141
  const configs = loadModuleConfigs(PATHS.confD);
43753
- const entries = (0, import_node_fs33.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
45142
+ const entries = (0, import_node_fs39.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
43754
45143
  for (const entry of entries) {
43755
45144
  if (!entry.isDirectory()) continue;
43756
- const manifestPath = (0, import_node_path24.join)(PATHS.moduleDir, entry.name, "mod.toml");
43757
- if (!(0, import_node_fs33.existsSync)(manifestPath)) continue;
45145
+ const manifestPath = (0, import_node_path30.join)(PATHS.moduleDir, entry.name, "mod.toml");
45146
+ if (!(0, import_node_fs39.existsSync)(manifestPath)) continue;
43758
45147
  try {
43759
- const manifest = import_toml4.default.parse((0, import_node_fs33.readFileSync)(manifestPath, "utf-8"));
45148
+ const manifest = import_toml4.default.parse((0, import_node_fs39.readFileSync)(manifestPath, "utf-8"));
43760
45149
  const name = manifest.module?.name || entry.name;
43761
45150
  const defaults = manifest.module?.config?.defaults || {};
43762
45151
  const config = {
@@ -43770,7 +45159,7 @@ var ModuleHost = class {
43770
45159
  source: "installed",
43771
45160
  status: config.enabled === false ? "disabled" : "loaded",
43772
45161
  events: 0,
43773
- path: (0, import_node_path24.join)(PATHS.moduleDir, entry.name),
45162
+ path: (0, import_node_path30.join)(PATHS.moduleDir, entry.name),
43774
45163
  config
43775
45164
  };
43776
45165
  this.modules.set(name, hosted);
@@ -43785,7 +45174,7 @@ var ModuleHost = class {
43785
45174
  status: "error",
43786
45175
  events: 0,
43787
45176
  detail: `manifest load failed: ${String(err.message || err)}`,
43788
- path: (0, import_node_path24.join)(PATHS.moduleDir, entry.name)
45177
+ path: (0, import_node_path30.join)(PATHS.moduleDir, entry.name)
43789
45178
  });
43790
45179
  }
43791
45180
  }
@@ -43824,17 +45213,17 @@ var ModuleHost = class {
43824
45213
  }
43825
45214
  }
43826
45215
  installedEntrypoint(modulePath) {
43827
- const packageJson = (0, import_node_path24.join)(modulePath, "package.json");
45216
+ const packageJson = (0, import_node_path30.join)(modulePath, "package.json");
43828
45217
  const candidates = [];
43829
- if ((0, import_node_fs33.existsSync)(packageJson)) {
45218
+ if ((0, import_node_fs39.existsSync)(packageJson)) {
43830
45219
  try {
43831
- const pkg = JSON.parse((0, import_node_fs33.readFileSync)(packageJson, "utf-8"));
43832
- if (pkg.main) candidates.push((0, import_node_path24.join)(modulePath, pkg.main));
45220
+ const pkg = JSON.parse((0, import_node_fs39.readFileSync)(packageJson, "utf-8"));
45221
+ if (pkg.main) candidates.push((0, import_node_path30.join)(modulePath, pkg.main));
43833
45222
  } catch {
43834
45223
  }
43835
45224
  }
43836
- candidates.push((0, import_node_path24.join)(modulePath, "dist", "index.js"), (0, import_node_path24.join)(modulePath, "index.js"));
43837
- return candidates.find((candidate) => (0, import_node_fs33.existsSync)(candidate)) || null;
45225
+ candidates.push((0, import_node_path30.join)(modulePath, "dist", "index.js"), (0, import_node_path30.join)(modulePath, "index.js"));
45226
+ return candidates.find((candidate) => (0, import_node_fs39.existsSync)(candidate)) || null;
43838
45227
  }
43839
45228
  isThreatCrushModule(value) {
43840
45229
  return Boolean(
@@ -44031,11 +45420,11 @@ function pagerdutyChannel(config) {
44031
45420
  }
44032
45421
 
44033
45422
  // src/daemon/alerts/smshub.ts
44034
- var import_node_os13 = require("os");
45423
+ var import_node_os17 = require("os");
44035
45424
  var SEVERITY_RANK6 = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
44036
45425
  var DEDUPE_MS = 10 * 6e4;
44037
45426
  var MAX_PER_HOUR = 6;
44038
- function smshubText(event, host = (0, import_node_os13.hostname)()) {
45427
+ function smshubText(event, host = (0, import_node_os17.hostname)()) {
44039
45428
  const evidence = event.details?.evidence?.message;
44040
45429
  const ip = event.source_ip && ![event.message, evidence ?? ""].some((t) => t.includes(event.source_ip)) ? ` from ${event.source_ip}` : "";
44041
45430
  const text = `ThreatCrush ${event.severity.toUpperCase()} on ${host}: ${event.message}${evidence && !event.message.includes(evidence) ? ` | ${evidence}` : ""}${ip}`;
@@ -44155,14 +45544,14 @@ function slackChannel(webhookUrl) {
44155
45544
  }
44156
45545
 
44157
45546
  // src/daemon/workers/runs-worker.ts
44158
- var import_promises2 = require("dns/promises");
44159
- var import_node_fs34 = require("fs");
45547
+ var import_promises6 = require("dns/promises");
45548
+ var import_node_fs40 = require("fs");
44160
45549
  var import_node_net9 = require("net");
44161
- var import_node_path25 = require("path");
45550
+ var import_node_path31 = require("path");
44162
45551
  init_cli_config();
44163
45552
 
44164
45553
  // src/core/cloud-events.ts
44165
- var import_node_crypto7 = require("crypto");
45554
+ var import_node_crypto9 = require("crypto");
44166
45555
  var import_node_net8 = require("net");
44167
45556
  init_cli_config();
44168
45557
  function currentLink() {
@@ -44246,7 +45635,7 @@ function remediationEvent(serverId, event) {
44246
45635
  return {
44247
45636
  type: "remediation",
44248
45637
  server_id: serverId,
44249
- event_id: (0, import_node_crypto7.randomUUID)(),
45638
+ event_id: (0, import_node_crypto9.randomUUID)(),
44250
45639
  action_type: d.action,
44251
45640
  target_value: event.source_ip,
44252
45641
  status: d.failed === true ? "failed" : "executed",
@@ -44290,7 +45679,7 @@ var NOT_PUBLIC = [
44290
45679
  function isPublicTarget(ip) {
44291
45680
  return (0, import_node_net9.isIP)(ip) !== 0 && !isProtected(ip, NOT_PUBLIC);
44292
45681
  }
44293
- async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0, import_promises2.lookup)(h, { all: true })).map((a) => a.address)) {
45682
+ async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0, import_promises6.lookup)(h, { all: true })).map((a) => a.address)) {
44294
45683
  let url;
44295
45684
  try {
44296
45685
  url = new URL(rawUrl.startsWith("http") ? rawUrl : `https://${rawUrl}`);
@@ -44309,24 +45698,24 @@ async function pentestTargetError(rawUrl, resolveHost = async (h) => (await (0,
44309
45698
  const inside = addresses.find((a) => !isPublicTarget(a));
44310
45699
  return inside ? `${host} resolves to ${inside}, which is not a public address; dashboard runs never reach inside this network` : null;
44311
45700
  }
44312
- function scanTargetError(target, roots, real = import_node_fs34.realpathSync) {
45701
+ function scanTargetError(target, roots, real = import_node_fs40.realpathSync) {
44313
45702
  if (roots.length === 0) {
44314
45703
  return "dashboard scans of this machine are off; list the directories they may read in [cloud] run_scan_paths";
44315
45704
  }
44316
45705
  let path2;
44317
45706
  try {
44318
- path2 = real((0, import_node_path25.resolve)(target));
45707
+ path2 = real((0, import_node_path31.resolve)(target));
44319
45708
  } catch {
44320
45709
  return `no such path: ${target}`;
44321
45710
  }
44322
45711
  for (const root of roots) {
44323
45712
  let base;
44324
45713
  try {
44325
- base = real((0, import_node_path25.resolve)(root));
45714
+ base = real((0, import_node_path31.resolve)(root));
44326
45715
  } catch {
44327
45716
  continue;
44328
45717
  }
44329
- if (path2 === base || path2.startsWith(base.endsWith(import_node_path25.sep) ? base : base + import_node_path25.sep)) return null;
45718
+ if (path2 === base || path2.startsWith(base.endsWith(import_node_path31.sep) ? base : base + import_node_path31.sep)) return null;
44330
45719
  }
44331
45720
  return `${target} is outside [cloud] run_scan_paths`;
44332
45721
  }
@@ -44412,11 +45801,11 @@ var RunsWorker = class {
44412
45801
  return null;
44413
45802
  }
44414
45803
  }
44415
- async execute(run) {
44416
- const target = run.property?.target;
45804
+ async execute(run2) {
45805
+ const target = run2.property?.target;
44417
45806
  if (!target) {
44418
45807
  return {
44419
- type: run.type,
45808
+ type: run2.type,
44420
45809
  target: "",
44421
45810
  findings: [],
44422
45811
  severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },
@@ -44424,11 +45813,11 @@ var RunsWorker = class {
44424
45813
  error: "property target missing"
44425
45814
  };
44426
45815
  }
44427
- const refused = run.type === "scan" ? scanTargetError(target, this.opts.scanRoots) : await pentestTargetError(target);
45816
+ const refused = run2.type === "scan" ? scanTargetError(target, this.opts.scanRoots) : await pentestTargetError(target);
44428
45817
  if (refused) {
44429
- this.opts.log?.(`[runs] refused ${run.type} ${target}: ${refused}`);
45818
+ this.opts.log?.(`[runs] refused ${run2.type} ${target}: ${refused}`);
44430
45819
  return {
44431
- type: run.type,
45820
+ type: run2.type,
44432
45821
  target,
44433
45822
  findings: [],
44434
45823
  severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },
@@ -44436,13 +45825,13 @@ var RunsWorker = class {
44436
45825
  error: refused
44437
45826
  };
44438
45827
  }
44439
- this.bus.announceModule("runs-worker", "running", `${run.type} ${run.property?.name || target}`);
45828
+ this.bus.announceModule("runs-worker", "running", `${run2.type} ${run2.property?.name || target}`);
44440
45829
  try {
44441
- if (run.type === "scan") return await runScan(target);
45830
+ if (run2.type === "scan") return await runScan(target);
44442
45831
  return await runPentest(target);
44443
45832
  } catch (err) {
44444
45833
  return {
44445
- type: run.type,
45834
+ type: run2.type,
44446
45835
  target,
44447
45836
  findings: [],
44448
45837
  severity_summary: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },
@@ -44480,16 +45869,16 @@ var RunsWorker = class {
44480
45869
  init_cli_config();
44481
45870
 
44482
45871
  // src/daemon/workers/cloud-spool.ts
44483
- var import_node_fs35 = require("fs");
44484
- var import_promises3 = require("fs/promises");
44485
- var import_node_path26 = require("path");
45872
+ var import_node_fs41 = require("fs");
45873
+ var import_promises7 = require("fs/promises");
45874
+ var import_node_path32 = require("path");
44486
45875
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
44487
45876
  var CloudSpool = class {
44488
45877
  constructor(path2, limits = DEFAULT_SPOOL_LIMITS) {
44489
45878
  this.path = path2;
44490
45879
  this.limits = limits;
44491
45880
  try {
44492
- (0, import_node_fs35.mkdirSync)((0, import_node_path26.dirname)(path2), { recursive: true });
45881
+ (0, import_node_fs41.mkdirSync)((0, import_node_path32.dirname)(path2), { recursive: true });
44493
45882
  } catch {
44494
45883
  }
44495
45884
  this.load();
@@ -44558,7 +45947,7 @@ var CloudSpool = class {
44558
45947
  load() {
44559
45948
  let raw;
44560
45949
  try {
44561
- raw = (0, import_node_fs35.readFileSync)(this.path, "utf-8");
45950
+ raw = (0, import_node_fs41.readFileSync)(this.path, "utf-8");
44562
45951
  } catch {
44563
45952
  return;
44564
45953
  }
@@ -44589,13 +45978,13 @@ var CloudSpool = class {
44589
45978
  const body = this.lines.length > 0 ? `${this.lines.join("\n")}
44590
45979
  ` : "";
44591
45980
  const tmp = `${this.path}.tmp`;
44592
- await (0, import_promises3.writeFile)(tmp, body, { mode: 384 });
44593
- await (0, import_promises3.rename)(tmp, this.path);
45981
+ await (0, import_promises7.writeFile)(tmp, body, { mode: 384 });
45982
+ await (0, import_promises7.rename)(tmp, this.path);
44594
45983
  } else if (this.pendingAppend.length > 0) {
44595
45984
  const chunk2 = `${this.pendingAppend.join("\n")}
44596
45985
  `;
44597
45986
  this.pendingAppend = [];
44598
- await (0, import_promises3.appendFile)(this.path, chunk2, { mode: 384 });
45987
+ await (0, import_promises7.appendFile)(this.path, chunk2, { mode: 384 });
44599
45988
  }
44600
45989
  }).catch(() => {
44601
45990
  this.needsRewrite = true;
@@ -44803,7 +46192,7 @@ var CloudSync = class {
44803
46192
  };
44804
46193
 
44805
46194
  // src/daemon/workers/abuse-reporter.ts
44806
- var import_node_crypto8 = require("crypto");
46195
+ var import_node_crypto10 = require("crypto");
44807
46196
 
44808
46197
  // src/daemon/workers/abuse-evidence.ts
44809
46198
  var import_node_net10 = require("net");
@@ -45032,32 +46421,32 @@ function resolveConfig(section) {
45032
46421
  }
45033
46422
 
45034
46423
  // src/core/abuse-report-log.ts
45035
- var import_node_fs36 = require("fs");
45036
- var import_node_path27 = require("path");
46424
+ var import_node_fs42 = require("fs");
46425
+ var import_node_path33 = require("path");
45037
46426
  init_paths();
45038
46427
  var ABUSE_DIRNAME = "abuse-reports";
45039
46428
  var LOG_FILE2 = "reports.jsonl";
45040
46429
  function resolveAbuseDir(dir) {
45041
46430
  if (dir) return dir;
45042
46431
  if (process.env.THREATCRUSH_ABUSE_DIR) return process.env.THREATCRUSH_ABUSE_DIR;
45043
- const system = (0, import_node_path27.join)("/var/lib/threatcrush", ABUSE_DIRNAME);
45044
- if ((0, import_node_fs36.existsSync)(system)) return system;
45045
- return (0, import_node_path27.join)(PATHS.stateDir, ABUSE_DIRNAME);
46432
+ const system = (0, import_node_path33.join)("/var/lib/threatcrush", ABUSE_DIRNAME);
46433
+ if ((0, import_node_fs42.existsSync)(system)) return system;
46434
+ return (0, import_node_path33.join)(PATHS.stateDir, ABUSE_DIRNAME);
45046
46435
  }
45047
46436
  function logPath(dir) {
45048
- return (0, import_node_path27.join)(resolveAbuseDir(dir), LOG_FILE2);
46437
+ return (0, import_node_path33.join)(resolveAbuseDir(dir), LOG_FILE2);
45049
46438
  }
45050
46439
  function appendReport(record, dir) {
45051
46440
  const path2 = logPath(dir);
45052
- (0, import_node_fs36.mkdirSync)(resolveAbuseDir(dir), { recursive: true, mode: 493 });
45053
- (0, import_node_fs36.appendFileSync)(path2, `${JSON.stringify(record)}
46441
+ (0, import_node_fs42.mkdirSync)(resolveAbuseDir(dir), { recursive: true, mode: 493 });
46442
+ (0, import_node_fs42.appendFileSync)(path2, `${JSON.stringify(record)}
45054
46443
  `, { mode: 420 });
45055
46444
  }
45056
46445
  function readReports(dir) {
45057
46446
  const path2 = logPath(dir);
45058
46447
  let raw;
45059
46448
  try {
45060
- raw = (0, import_node_fs36.readFileSync)(path2, "utf-8");
46449
+ raw = (0, import_node_fs42.readFileSync)(path2, "utf-8");
45061
46450
  } catch {
45062
46451
  return [];
45063
46452
  }
@@ -45196,7 +46585,7 @@ var AbuseReporter = class {
45196
46585
  const payload = buildPayload(ip, evidence);
45197
46586
  const results = this.cfg.dryRun ? [] : await dispatch(payload, this.cfg.destinations, this.cfg.keys);
45198
46587
  const record = {
45199
- id: (0, import_node_crypto8.randomUUID)().slice(0, 8),
46588
+ id: (0, import_node_crypto10.randomUUID)().slice(0, 8),
45200
46589
  ip,
45201
46590
  reported_at: new Date(now).toISOString(),
45202
46591
  mode: this.cfg.dryRun ? "dry_run" : "live",
@@ -45482,9 +46871,9 @@ var RemediationConsumer = class {
45482
46871
  };
45483
46872
 
45484
46873
  // src/daemon/workers/auto-update.ts
45485
- var import_node_child_process10 = require("child_process");
45486
- var import_node_fs37 = require("fs");
45487
- var import_node_path28 = require("path");
46874
+ var import_node_child_process11 = require("child_process");
46875
+ var import_node_fs43 = require("fs");
46876
+ var import_node_path34 = require("path");
45488
46877
  init_backoff();
45489
46878
  var PKG_NAME = "@profullstack/threatcrush";
45490
46879
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
@@ -45528,12 +46917,12 @@ function pickUpdate(doc, current, opts) {
45528
46917
  return { version: null, reason: `${latest} is younger than min_age, and nothing older is newer than ${current}; waiting` };
45529
46918
  }
45530
46919
  function installPlan(opts) {
45531
- const expected = `${import_node_path28.sep}lib${import_node_path28.sep}node_modules${import_node_path28.sep}@profullstack${import_node_path28.sep}threatcrush`;
46920
+ const expected = `${import_node_path34.sep}lib${import_node_path34.sep}node_modules${import_node_path34.sep}@profullstack${import_node_path34.sep}threatcrush`;
45532
46921
  if (!opts.pkgRoot.endsWith(expected)) {
45533
46922
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
45534
46923
  }
45535
- const nodeBin = (0, import_node_path28.dirname)(opts.execPath);
45536
- const npm = (0, import_node_path28.join)(nodeBin, "npm");
46924
+ const nodeBin = (0, import_node_path34.dirname)(opts.execPath);
46925
+ const npm = (0, import_node_path34.join)(nodeBin, "npm");
45537
46926
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
45538
46927
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
45539
46928
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -45565,10 +46954,10 @@ function installPlan(opts) {
45565
46954
  }
45566
46955
  function ownerOf(path2, passwd = "/etc/passwd") {
45567
46956
  try {
45568
- const st = (0, import_node_fs37.statSync)(path2);
46957
+ const st = (0, import_node_fs43.statSync)(path2);
45569
46958
  let home = st.uid === 0 ? "/root" : "";
45570
46959
  try {
45571
- for (const line2 of (0, import_node_fs37.readFileSync)(passwd, "utf8").split("\n")) {
46960
+ for (const line2 of (0, import_node_fs43.readFileSync)(passwd, "utf8").split("\n")) {
45572
46961
  const f = line2.split(":");
45573
46962
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
45574
46963
  }
@@ -45590,8 +46979,8 @@ function updateSettings(section, env3 = process.env) {
45590
46979
  };
45591
46980
  }
45592
46981
  function defaultRun(argv, env3) {
45593
- return new Promise((resolve8) => {
45594
- const child = (0, import_node_child_process10.spawn)(argv[0], argv.slice(1), {
46982
+ return new Promise((resolve9) => {
46983
+ const child = (0, import_node_child_process11.spawn)(argv[0], argv.slice(1), {
45595
46984
  env: { ...process.env, ...env3 },
45596
46985
  stdio: ["ignore", "pipe", "pipe"]
45597
46986
  });
@@ -45601,8 +46990,8 @@ function defaultRun(argv, env3) {
45601
46990
  };
45602
46991
  child.stdout?.on("data", keep);
45603
46992
  child.stderr?.on("data", keep);
45604
- child.on("error", (err) => resolve8({ code: -1, output: err.message }));
45605
- child.on("close", (code) => resolve8({ code: code ?? -1, output }));
46993
+ child.on("error", (err) => resolve9({ code: -1, output: err.message }));
46994
+ child.on("close", (code) => resolve9({ code: code ?? -1, output }));
45606
46995
  });
45607
46996
  }
45608
46997
  var AutoUpdate = class {
@@ -45678,7 +47067,7 @@ var AutoUpdate = class {
45678
47067
  uid: process.getuid?.() ?? -1,
45679
47068
  owner: ownerOf(this.opts.pkgRoot),
45680
47069
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
45681
- npmExists: import_node_fs37.existsSync
47070
+ npmExists: import_node_fs43.existsSync
45682
47071
  });
45683
47072
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
45684
47073
  this.recordAttempt(target);
@@ -45714,7 +47103,7 @@ var AutoUpdate = class {
45714
47103
  }
45715
47104
  lastAttempt() {
45716
47105
  try {
45717
- const v = JSON.parse((0, import_node_fs37.readFileSync)(this.opts.statePath, "utf8"));
47106
+ const v = JSON.parse((0, import_node_fs43.readFileSync)(this.opts.statePath, "utf8"));
45718
47107
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
45719
47108
  } catch {
45720
47109
  return null;
@@ -45722,7 +47111,7 @@ var AutoUpdate = class {
45722
47111
  }
45723
47112
  recordAttempt(version) {
45724
47113
  try {
45725
- (0, import_node_fs37.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
47114
+ (0, import_node_fs43.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
45726
47115
  } catch (err) {
45727
47116
  this.opts.log(`[update] could not record attempt: ${err.message}`);
45728
47117
  }
@@ -45730,9 +47119,9 @@ var AutoUpdate = class {
45730
47119
  };
45731
47120
 
45732
47121
  // src/daemon/workers/threat-feeds.ts
45733
- var import_node_child_process11 = require("child_process");
45734
- var import_node_fs38 = require("fs");
45735
- var import_node_path29 = require("path");
47122
+ var import_node_child_process12 = require("child_process");
47123
+ var import_node_fs44 = require("fs");
47124
+ var import_node_path35 = require("path");
45736
47125
  var import_node_net13 = require("net");
45737
47126
  init_backoff();
45738
47127
  var EGRESS_TABLE = "threatcrush_egress";
@@ -45810,7 +47199,7 @@ function parseListeningPorts(text) {
45810
47199
  return ports;
45811
47200
  }
45812
47201
  function defaultRun2(cmd, args, input) {
45813
- const res = (0, import_node_child_process11.spawnSync)(cmd, args, { encoding: "utf-8", input, timeout: 15e3, stdio: ["pipe", "pipe", "pipe"] });
47202
+ const res = (0, import_node_child_process12.spawnSync)(cmd, args, { encoding: "utf-8", input, timeout: 15e3, stdio: ["pipe", "pipe", "pipe"] });
45814
47203
  return res.status === 0 ? res.stdout : null;
45815
47204
  }
45816
47205
  var ThreatFeeds = class {
@@ -45904,14 +47293,14 @@ var ThreatFeeds = class {
45904
47293
  */
45905
47294
  writeResolverFiles(set) {
45906
47295
  const domains = this.wantsDomainBlock ? Object.keys(set.domains).sort() : [];
45907
- const dir = this.opts.resolverDir ?? (0, import_node_path29.dirname)(this.opts.cachePath);
47296
+ const dir = this.opts.resolverDir ?? (0, import_node_path35.dirname)(this.opts.cachePath);
45908
47297
  const hooks = this.opts.resolverHooks ?? RESOLVER_HOOKS;
45909
47298
  const write = (name, content) => {
45910
- const path2 = (0, import_node_path29.join)(dir, name);
47299
+ const path2 = (0, import_node_path35.join)(dir, name);
45911
47300
  if (this.resolverWritten.get(name) === content) return false;
45912
47301
  try {
45913
- (0, import_node_fs38.writeFileSync)(`${path2}.tmp`, content);
45914
- (0, import_node_fs38.renameSync)(`${path2}.tmp`, path2);
47302
+ (0, import_node_fs44.writeFileSync)(`${path2}.tmp`, content);
47303
+ (0, import_node_fs44.renameSync)(`${path2}.tmp`, path2);
45915
47304
  this.resolverWritten.set(name, content);
45916
47305
  return true;
45917
47306
  } catch (err) {
@@ -45922,11 +47311,11 @@ var ThreatFeeds = class {
45922
47311
  const hostsChanged = write(RESOLVER_FILES.hosts, hostsBlocklist(domains));
45923
47312
  const unboundChanged = write(RESOLVER_FILES.unbound, unboundBlocklist(domains));
45924
47313
  const via = [];
45925
- if ((0, import_node_fs38.existsSync)(hooks.dnsmasq)) {
47314
+ if ((0, import_node_fs44.existsSync)(hooks.dnsmasq)) {
45926
47315
  via.push("dnsmasq");
45927
47316
  if (hostsChanged) this.run("systemctl", ["kill", "-s", "HUP", "dnsmasq.service"]);
45928
47317
  }
45929
- if ((0, import_node_fs38.existsSync)(hooks.unbound)) {
47318
+ if ((0, import_node_fs44.existsSync)(hooks.unbound)) {
45930
47319
  via.push("unbound");
45931
47320
  if (unboundChanged && this.run("unbound-control", ["reload"]) === null) {
45932
47321
  this.run("systemctl", ["reload", "unbound.service"]);
@@ -45987,12 +47376,12 @@ var ThreatFeeds = class {
45987
47376
  };
45988
47377
 
45989
47378
  // src/daemon/workers/privilege-watch.ts
45990
- var import_node_fs39 = require("fs");
45991
- var import_node_path30 = require("path");
45992
- var import_node_child_process12 = require("child_process");
47379
+ var import_node_fs45 = require("fs");
47380
+ var import_node_path36 = require("path");
47381
+ var import_node_child_process13 = require("child_process");
45993
47382
 
45994
47383
  // src/core/privileges/index.ts
45995
- var import_node_crypto9 = require("crypto");
47384
+ var import_node_crypto11 = require("crypto");
45996
47385
  var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
45997
47386
  function parseUsers(text) {
45998
47387
  const out = [];
@@ -46033,7 +47422,7 @@ function sudoReadsIncluded(name) {
46033
47422
  }
46034
47423
  function keyFingerprint(blobBase64) {
46035
47424
  if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
46036
- const digest = (0, import_node_crypto9.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
47425
+ const digest = (0, import_node_crypto11.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
46037
47426
  return `SHA256:${digest.replace(/=+$/, "")}`;
46038
47427
  }
46039
47428
  function parseAuthorizedKeys(text) {
@@ -46214,34 +47603,34 @@ function countryName(code) {
46214
47603
  var fsIO = {
46215
47604
  readFile: (p) => {
46216
47605
  try {
46217
- return (0, import_node_fs39.readFileSync)(p, "utf-8");
47606
+ return (0, import_node_fs45.readFileSync)(p, "utf-8");
46218
47607
  } catch {
46219
47608
  return null;
46220
47609
  }
46221
47610
  },
46222
47611
  readDir: (p) => {
46223
47612
  try {
46224
- return (0, import_node_fs39.readdirSync)(p);
47613
+ return (0, import_node_fs45.readdirSync)(p);
46225
47614
  } catch {
46226
47615
  return null;
46227
47616
  }
46228
47617
  },
46229
- exists: (p) => (0, import_node_fs39.existsSync)(p)
47618
+ exists: (p) => (0, import_node_fs45.existsSync)(p)
46230
47619
  };
46231
47620
  function readJson(path2) {
46232
47621
  try {
46233
- return JSON.parse((0, import_node_fs39.readFileSync)(path2, "utf-8"));
47622
+ return JSON.parse((0, import_node_fs45.readFileSync)(path2, "utf-8"));
46234
47623
  } catch {
46235
47624
  return null;
46236
47625
  }
46237
47626
  }
46238
47627
  function writeJson(path2, value) {
46239
- (0, import_node_fs39.mkdirSync)((0, import_node_path30.dirname)(path2), { recursive: true });
46240
- (0, import_node_fs39.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
46241
- (0, import_node_fs39.renameSync)(`${path2}.tmp`, path2);
47628
+ (0, import_node_fs45.mkdirSync)((0, import_node_path36.dirname)(path2), { recursive: true });
47629
+ (0, import_node_fs45.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
47630
+ (0, import_node_fs45.renameSync)(`${path2}.tmp`, path2);
46242
47631
  }
46243
47632
  function defaultRun3(cmd, args) {
46244
- const res = (0, import_node_child_process12.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
47633
+ const res = (0, import_node_child_process13.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
46245
47634
  return res.status === 0 ? res.stdout : null;
46246
47635
  }
46247
47636
  async function geolocateViaThreatcrush(ip, fetchImpl = fetch) {
@@ -46355,7 +47744,7 @@ var PrivilegeWatch = class {
46355
47744
  for (const dir of dirs) {
46356
47745
  if (this.watchers.has(dir) || !this.io.exists(dir)) continue;
46357
47746
  try {
46358
- const w = (0, import_node_fs39.watch)(dir, { persistent: false }, (_type2, name) => {
47747
+ const w = (0, import_node_fs45.watch)(dir, { persistent: false }, (_type2, name) => {
46359
47748
  if (name && !String(name).startsWith("authorized_keys")) return;
46360
47749
  if (this.debounce) clearTimeout(this.debounce);
46361
47750
  this.debounce = setTimeout(() => {
@@ -46454,7 +47843,7 @@ var PrivilegeWatch = class {
46454
47843
  * raised a "new country" alert on its first run; on dev2 it did, at once.
46455
47844
  */
46456
47845
  async backfillLogins() {
46457
- if ((0, import_node_fs39.existsSync)(this.opts.loginsPath)) return;
47846
+ if ((0, import_node_fs45.existsSync)(this.opts.loginsPath)) return;
46458
47847
  const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "cat", "--no-pager"]);
46459
47848
  const byUser = parseAcceptedLogins(out ?? "");
46460
47849
  const ips = [...new Set([...byUser.values()].flatMap((s) => [...s]))];
@@ -46467,7 +47856,7 @@ var PrivilegeWatch = class {
46467
47856
  return;
46468
47857
  }
46469
47858
  }
46470
- if ((0, import_node_fs39.existsSync)(this.opts.loginsPath)) return;
47859
+ if ((0, import_node_fs45.existsSync)(this.opts.loginsPath)) return;
46471
47860
  const at = this.now().toISOString();
46472
47861
  const history = {};
46473
47862
  for (const [user, userIps] of byUser) {
@@ -46519,11 +47908,11 @@ var PrivilegeWatch = class {
46519
47908
  };
46520
47909
 
46521
47910
  // src/daemon/workers/command-history.ts
46522
- var import_node_fs40 = require("fs");
46523
- var import_node_child_process13 = require("child_process");
46524
- var import_node_path31 = require("path");
47911
+ var import_node_fs46 = require("fs");
47912
+ var import_node_child_process14 = require("child_process");
47913
+ var import_node_path37 = require("path");
46525
47914
  var import_node_zlib2 = require("zlib");
46526
- var import_node_crypto10 = require("crypto");
47915
+ var import_node_crypto12 = require("crypto");
46527
47916
  var POLL_MS3 = 6e4;
46528
47917
  var MAX_HISTORY_BYTES = 4 * 1024 * 1024;
46529
47918
  var MAX_COMPRESSED_HISTORY_BYTES = MAX_HISTORY_BYTES + 65536;
@@ -46541,10 +47930,10 @@ function commandHistorySettings(section) {
46541
47930
  function historyAccounts() {
46542
47931
  let passwd;
46543
47932
  try {
46544
- passwd = (0, import_node_child_process13.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
47933
+ passwd = (0, import_node_child_process14.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
46545
47934
  } catch {
46546
47935
  try {
46547
- passwd = (0, import_node_fs40.readFileSync)("/etc/passwd", "utf8");
47936
+ passwd = (0, import_node_fs46.readFileSync)("/etc/passwd", "utf8");
46548
47937
  } catch {
46549
47938
  return [];
46550
47939
  }
@@ -46557,9 +47946,9 @@ function historyAccounts() {
46557
47946
  const name = fields[0] ?? "";
46558
47947
  const home = fields[5] ?? "";
46559
47948
  const shell = fields[6] ?? "";
46560
- if (!Number.isInteger(uid) || !Number.isInteger(gid) || !(0, import_node_path31.isAbsolute)(home) || home === "/" || home.split("/").includes("..")) return [];
47949
+ if (!Number.isInteger(uid) || !Number.isInteger(gid) || !(0, import_node_path37.isAbsolute)(home) || home === "/" || home.split("/").includes("..")) return [];
46561
47950
  if (root ? uid !== 0 && uid < 1e3 : uid !== process.getuid?.()) return [];
46562
- if (!HISTORY_TARGETS[(0, import_node_path31.basename)(shell)]) return [];
47951
+ if (!HISTORY_TARGETS[(0, import_node_path37.basename)(shell)]) return [];
46563
47952
  return [{ uid, gid, name, home, shell }];
46564
47953
  });
46565
47954
  }
@@ -46570,18 +47959,18 @@ function descriptorPath(directoryFd, name) {
46570
47959
  return `/proc/self/fd/${directoryFd}/${name}`;
46571
47960
  }
46572
47961
  function openDirectoryChain(path2) {
46573
- if (!(0, import_node_path31.isAbsolute)(path2) || path2.split(import_node_path31.sep).includes("..")) throw new Error("directory path is not a safe absolute path");
46574
- const flags = import_node_fs40.constants.O_RDONLY | import_node_fs40.constants.O_DIRECTORY | (import_node_fs40.constants.O_NOFOLLOW ?? 0);
46575
- let fd = (0, import_node_fs40.openSync)("/", flags);
47962
+ if (!(0, import_node_path37.isAbsolute)(path2) || path2.split(import_node_path37.sep).includes("..")) throw new Error("directory path is not a safe absolute path");
47963
+ const flags = import_node_fs46.constants.O_RDONLY | import_node_fs46.constants.O_DIRECTORY | (import_node_fs46.constants.O_NOFOLLOW ?? 0);
47964
+ let fd = (0, import_node_fs46.openSync)("/", flags);
46576
47965
  try {
46577
- for (const part of path2.split(import_node_path31.sep).filter((item) => item && item !== ".")) {
46578
- const next = (0, import_node_fs40.openSync)(descriptorPath(fd, part), flags);
46579
- (0, import_node_fs40.closeSync)(fd);
47966
+ for (const part of path2.split(import_node_path37.sep).filter((item) => item && item !== ".")) {
47967
+ const next = (0, import_node_fs46.openSync)(descriptorPath(fd, part), flags);
47968
+ (0, import_node_fs46.closeSync)(fd);
46580
47969
  fd = next;
46581
47970
  }
46582
47971
  return fd;
46583
47972
  } catch (error2) {
46584
- (0, import_node_fs40.closeSync)(fd);
47973
+ (0, import_node_fs46.closeSync)(fd);
46585
47974
  throw error2;
46586
47975
  }
46587
47976
  }
@@ -46589,89 +47978,89 @@ function readExact(fd, size) {
46589
47978
  const data = Buffer.alloc(size);
46590
47979
  let offset = 0;
46591
47980
  while (offset < data.length) {
46592
- const read = (0, import_node_fs40.readSync)(fd, data, offset, data.length - offset, offset);
47981
+ const read = (0, import_node_fs46.readSync)(fd, data, offset, data.length - offset, offset);
46593
47982
  if (read === 0) break;
46594
47983
  offset += read;
46595
47984
  }
46596
47985
  return offset === data.length ? data : null;
46597
47986
  }
46598
47987
  function privateDirectory(path2) {
46599
- (0, import_node_fs40.mkdirSync)(path2, { recursive: true, mode: 448 });
46600
- const stat = (0, import_node_fs40.lstatSync)(path2);
47988
+ (0, import_node_fs46.mkdirSync)(path2, { recursive: true, mode: 448 });
47989
+ const stat = (0, import_node_fs46.lstatSync)(path2);
46601
47990
  if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("history storage path is not a directory");
46602
- (0, import_node_fs40.chmodSync)(path2, 448);
47991
+ (0, import_node_fs46.chmodSync)(path2, 448);
46603
47992
  }
46604
47993
  function safeReadHistory(directoryFd, name, uid) {
46605
- const noFollow = import_node_fs40.constants.O_NOFOLLOW ?? 0;
46606
- const fd = (0, import_node_fs40.openSync)(descriptorPath(directoryFd, name), import_node_fs40.constants.O_RDONLY | noFollow);
47994
+ const noFollow = import_node_fs46.constants.O_NOFOLLOW ?? 0;
47995
+ const fd = (0, import_node_fs46.openSync)(descriptorPath(directoryFd, name), import_node_fs46.constants.O_RDONLY | noFollow);
46607
47996
  try {
46608
- const opened = (0, import_node_fs40.fstatSync)(fd);
47997
+ const opened = (0, import_node_fs46.fstatSync)(fd);
46609
47998
  if (!opened.isFile() || opened.nlink !== 1 || opened.uid !== uid) return null;
46610
47999
  if (opened.size > MAX_HISTORY_BYTES) throw new Error(`history file exceeds ${MAX_HISTORY_BYTES} bytes`);
46611
48000
  const data = readExact(fd, opened.size);
46612
48001
  if (data === null) return null;
46613
- const after = (0, import_node_fs40.fstatSync)(fd);
48002
+ const after = (0, import_node_fs46.fstatSync)(fd);
46614
48003
  if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs) return null;
46615
48004
  return data;
46616
48005
  } finally {
46617
- (0, import_node_fs40.closeSync)(fd);
48006
+ (0, import_node_fs46.closeSync)(fd);
46618
48007
  }
46619
48008
  }
46620
48009
  function atomicWrite(path2, data, mode = 384, owner, parentFd) {
46621
- const dirFd = parentFd ?? openDirectoryChain((0, import_node_path31.dirname)(path2));
48010
+ const dirFd = parentFd ?? openDirectoryChain((0, import_node_path37.dirname)(path2));
46622
48011
  const ownsDirFd = parentFd === void 0;
46623
- const name = (0, import_node_path31.basename)(path2);
46624
- const temp = descriptorPath(dirFd, `${name}.${(0, import_node_crypto10.randomUUID)()}.tmp`);
48012
+ const name = (0, import_node_path37.basename)(path2);
48013
+ const temp = descriptorPath(dirFd, `${name}.${(0, import_node_crypto12.randomUUID)()}.tmp`);
46625
48014
  const destination = descriptorPath(dirFd, name);
46626
- const noFollow = import_node_fs40.constants.O_NOFOLLOW ?? 0;
48015
+ const noFollow = import_node_fs46.constants.O_NOFOLLOW ?? 0;
46627
48016
  let fd;
46628
48017
  try {
46629
- fd = (0, import_node_fs40.openSync)(temp, import_node_fs40.constants.O_WRONLY | import_node_fs40.constants.O_CREAT | import_node_fs40.constants.O_EXCL | noFollow, mode);
48018
+ fd = (0, import_node_fs46.openSync)(temp, import_node_fs46.constants.O_WRONLY | import_node_fs46.constants.O_CREAT | import_node_fs46.constants.O_EXCL | noFollow, mode);
46630
48019
  let offset = 0;
46631
- while (offset < data.length) offset += (0, import_node_fs40.writeSync)(fd, data, offset, data.length - offset);
46632
- (0, import_node_fs40.fchmodSync)(fd, mode);
48020
+ while (offset < data.length) offset += (0, import_node_fs46.writeSync)(fd, data, offset, data.length - offset);
48021
+ (0, import_node_fs46.fchmodSync)(fd, mode);
46633
48022
  if (owner && typeof process.getuid === "function" && process.getuid() === 0) {
46634
- (0, import_node_fs40.fchownSync)(fd, owner.uid, owner.gid);
48023
+ (0, import_node_fs46.fchownSync)(fd, owner.uid, owner.gid);
46635
48024
  }
46636
- (0, import_node_fs40.fsyncSync)(fd);
46637
- (0, import_node_fs40.closeSync)(fd);
48025
+ (0, import_node_fs46.fsyncSync)(fd);
48026
+ (0, import_node_fs46.closeSync)(fd);
46638
48027
  fd = void 0;
46639
- (0, import_node_fs40.renameSync)(temp, destination);
48028
+ (0, import_node_fs46.renameSync)(temp, destination);
46640
48029
  } catch (error2) {
46641
48030
  if (fd !== void 0) {
46642
48031
  try {
46643
- (0, import_node_fs40.closeSync)(fd);
48032
+ (0, import_node_fs46.closeSync)(fd);
46644
48033
  } catch {
46645
48034
  }
46646
48035
  }
46647
48036
  try {
46648
- (0, import_node_fs40.unlinkSync)(temp);
48037
+ (0, import_node_fs46.unlinkSync)(temp);
46649
48038
  } catch {
46650
48039
  }
46651
48040
  throw error2;
46652
48041
  } finally {
46653
- if (ownsDirFd) (0, import_node_fs40.closeSync)(dirFd);
48042
+ if (ownsDirFd) (0, import_node_fs46.closeSync)(dirFd);
46654
48043
  }
46655
48044
  }
46656
48045
  function readCurrentBackup(path2) {
46657
48046
  let fd;
46658
48047
  try {
46659
- const parentFd = openDirectoryChain((0, import_node_path31.dirname)(path2));
48048
+ const parentFd = openDirectoryChain((0, import_node_path37.dirname)(path2));
46660
48049
  try {
46661
- fd = (0, import_node_fs40.openSync)(descriptorPath(parentFd, (0, import_node_path31.basename)(path2)), import_node_fs40.constants.O_RDONLY | (import_node_fs40.constants.O_NOFOLLOW ?? 0));
48050
+ fd = (0, import_node_fs46.openSync)(descriptorPath(parentFd, (0, import_node_path37.basename)(path2)), import_node_fs46.constants.O_RDONLY | (import_node_fs46.constants.O_NOFOLLOW ?? 0));
46662
48051
  } finally {
46663
- (0, import_node_fs40.closeSync)(parentFd);
48052
+ (0, import_node_fs46.closeSync)(parentFd);
46664
48053
  }
46665
- const stat = (0, import_node_fs40.fstatSync)(fd);
48054
+ const stat = (0, import_node_fs46.fstatSync)(fd);
46666
48055
  if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_COMPRESSED_HISTORY_BYTES) return null;
46667
48056
  const compressed = readExact(fd, stat.size);
46668
- const after = (0, import_node_fs40.fstatSync)(fd);
48057
+ const after = (0, import_node_fs46.fstatSync)(fd);
46669
48058
  if (!compressed || after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) return null;
46670
48059
  return (0, import_node_zlib2.gunzipSync)(compressed, { maxOutputLength: MAX_HISTORY_BYTES });
46671
48060
  } catch {
46672
48061
  return null;
46673
48062
  } finally {
46674
- if (fd !== void 0) (0, import_node_fs40.closeSync)(fd);
48063
+ if (fd !== void 0) (0, import_node_fs46.closeSync)(fd);
46675
48064
  }
46676
48065
  }
46677
48066
  function compactTime(date) {
@@ -46683,7 +48072,7 @@ var CommandHistoryWatcher = class {
46683
48072
  this.pollMs = Math.max(1e4, opts.pollMs ?? POLL_MS3);
46684
48073
  this.now = opts.now ?? (() => /* @__PURE__ */ new Date());
46685
48074
  this.listAccounts = opts.listAccounts ?? historyAccounts;
46686
- this.root = (0, import_node_path31.join)(opts.stateDir, "command-history");
48075
+ this.root = (0, import_node_path37.join)(opts.stateDir, "command-history");
46687
48076
  }
46688
48077
  opts;
46689
48078
  timer = null;
@@ -46724,7 +48113,7 @@ var CommandHistoryWatcher = class {
46724
48113
  try {
46725
48114
  privateDirectory(this.root);
46726
48115
  for (const account of this.listAccounts()) {
46727
- if (!Number.isInteger(account.uid) || account.uid < 0 || !(0, import_node_path31.isAbsolute)(account.home)) continue;
48116
+ if (!Number.isInteger(account.uid) || account.uid < 0 || !(0, import_node_path37.isAbsolute)(account.home)) continue;
46728
48117
  const targets = this.targetsFor(account);
46729
48118
  for (const relative4 of targets) this.scanFile(account, relative4);
46730
48119
  }
@@ -46735,39 +48124,39 @@ var CommandHistoryWatcher = class {
46735
48124
  }
46736
48125
  }
46737
48126
  targetsFor(account) {
46738
- const targets = new Set(HISTORY_TARGETS[(0, import_node_path31.basename)(account.shell)] ?? []);
48127
+ const targets = new Set(HISTORY_TARGETS[(0, import_node_path37.basename)(account.shell)] ?? []);
46739
48128
  for (const relative4 of Object.values(HISTORY_TARGETS).flat()) {
46740
48129
  if (targets.has(relative4)) continue;
46741
- const path2 = (0, import_node_path31.join)(account.home, relative4);
48130
+ const path2 = (0, import_node_path37.join)(account.home, relative4);
46742
48131
  try {
46743
- (0, import_node_fs40.lstatSync)(path2);
48132
+ (0, import_node_fs46.lstatSync)(path2);
46744
48133
  targets.add(relative4);
46745
48134
  continue;
46746
48135
  } catch (error2) {
46747
48136
  if (error2.code !== "ENOENT") continue;
46748
48137
  }
46749
- const current = (0, import_node_path31.join)(this.root, String(account.uid), `${(0, import_node_path31.basename)(relative4)}.current.gz`);
48138
+ const current = (0, import_node_path37.join)(this.root, String(account.uid), `${(0, import_node_path37.basename)(relative4)}.current.gz`);
46750
48139
  if (readCurrentBackup(current) !== null) targets.add(relative4);
46751
48140
  }
46752
48141
  return [...targets];
46753
48142
  }
46754
48143
  scanFile(account, relative4) {
46755
- const path2 = (0, import_node_path31.join)(account.home, relative4);
46756
- const store = (0, import_node_path31.join)(this.root, String(account.uid), (0, import_node_path31.basename)(relative4));
48144
+ const path2 = (0, import_node_path37.join)(account.home, relative4);
48145
+ const store = (0, import_node_path37.join)(this.root, String(account.uid), (0, import_node_path37.basename)(relative4));
46757
48146
  const current = `${store}.current.gz`;
46758
48147
  let userParentFd;
46759
48148
  try {
46760
- userParentFd = openDirectoryChain((0, import_node_path31.dirname)(path2));
48149
+ userParentFd = openDirectoryChain((0, import_node_path37.dirname)(path2));
46761
48150
  } catch {
46762
- this.opts.log(`[command-history] skipped uid=${account.uid} ${(0, import_node_path31.basename)(relative4)} because its parent path is missing or not a real directory`);
48151
+ this.opts.log(`[command-history] skipped uid=${account.uid} ${(0, import_node_path37.basename)(relative4)} because its parent path is missing or not a real directory`);
46763
48152
  return;
46764
48153
  }
46765
48154
  try {
46766
- privateDirectory((0, import_node_path31.dirname)(store));
46767
- const userPath = descriptorPath(userParentFd, (0, import_node_path31.basename)(path2));
48155
+ privateDirectory((0, import_node_path37.dirname)(store));
48156
+ const userPath = descriptorPath(userParentFd, (0, import_node_path37.basename)(path2));
46768
48157
  let status;
46769
48158
  try {
46770
- status = (0, import_node_fs40.lstatSync)(userPath);
48159
+ status = (0, import_node_fs46.lstatSync)(userPath);
46771
48160
  } catch (error2) {
46772
48161
  if (error2.code !== "ENOENT") throw error2;
46773
48162
  }
@@ -46782,7 +48171,7 @@ var CommandHistoryWatcher = class {
46782
48171
  } else if (!status) {
46783
48172
  this.restore(path2, Buffer.alloc(0), account, userParentFd);
46784
48173
  }
46785
- const data = safeReadHistory(userParentFd, (0, import_node_path31.basename)(path2), account.uid);
48174
+ const data = safeReadHistory(userParentFd, (0, import_node_path37.basename)(path2), account.uid);
46786
48175
  if (data === null) return;
46787
48176
  const previous = backup;
46788
48177
  if (previous?.equals(data)) {
@@ -46791,13 +48180,13 @@ var CommandHistoryWatcher = class {
46791
48180
  }
46792
48181
  const compressed = (0, import_node_zlib2.gzipSync)(data, { level: 6 });
46793
48182
  const stamp = compactTime(this.now());
46794
- atomicWrite(`${store}.${stamp}-${(0, import_node_crypto10.randomUUID)().slice(0, 8)}.gz`, compressed);
48183
+ atomicWrite(`${store}.${stamp}-${(0, import_node_crypto12.randomUUID)().slice(0, 8)}.gz`, compressed);
46795
48184
  atomicWrite(current, compressed);
46796
48185
  this.pruneSnapshots(store);
46797
48186
  } catch (error2) {
46798
- this.opts.log(`[command-history] could not snapshot uid=${account.uid} ${(0, import_node_path31.basename)(relative4)}: ${error2.message}`);
48187
+ this.opts.log(`[command-history] could not snapshot uid=${account.uid} ${(0, import_node_path37.basename)(relative4)}: ${error2.message}`);
46799
48188
  } finally {
46800
- (0, import_node_fs40.closeSync)(userParentFd);
48189
+ (0, import_node_fs46.closeSync)(userParentFd);
46801
48190
  }
46802
48191
  }
46803
48192
  restore(path2, content, account, parentFd) {
@@ -46810,22 +48199,22 @@ var CommandHistoryWatcher = class {
46810
48199
  module: "command-history",
46811
48200
  category: "system",
46812
48201
  severity: "medium",
46813
- message: `Shell history for ${name} (${(0, import_node_path31.basename)(relative4)}) was ${reason}; restored${hadBackup ? " from the latest backup" : " as an empty file"}`,
46814
- details: { uid: account.uid, account: name, history_file: (0, import_node_path31.basename)(relative4), action: "restored", reason, had_backup: hadBackup }
48202
+ message: `Shell history for ${name} (${(0, import_node_path37.basename)(relative4)}) was ${reason}; restored${hadBackup ? " from the latest backup" : " as an empty file"}`,
48203
+ details: { uid: account.uid, account: name, history_file: (0, import_node_path37.basename)(relative4), action: "restored", reason, had_backup: hadBackup }
46815
48204
  };
46816
48205
  this.opts.bus.publish(event);
46817
48206
  this.opts.log(`[command-history] ${event.message}`);
46818
48207
  }
46819
48208
  pruneSnapshots(current) {
46820
- const dir = (0, import_node_path31.dirname)(current);
46821
- const prefix = `${(0, import_node_path31.basename)(current).replace(/\.current\.gz$/, "")}.`;
46822
- const snapshots = (0, import_node_fs40.readdirSync)(dir).filter((name) => name !== (0, import_node_path31.basename)(current) && name.startsWith(prefix) && name.endsWith(".gz")).map((name) => ({ path: (0, import_node_path31.join)(dir, name), name, time: (0, import_node_fs40.lstatSync)((0, import_node_path31.join)(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time);
48209
+ const dir = (0, import_node_path37.dirname)(current);
48210
+ const prefix = `${(0, import_node_path37.basename)(current).replace(/\.current\.gz$/, "")}.`;
48211
+ const snapshots = (0, import_node_fs46.readdirSync)(dir).filter((name) => name !== (0, import_node_path37.basename)(current) && name.startsWith(prefix) && name.endsWith(".gz")).map((name) => ({ path: (0, import_node_path37.join)(dir, name), name, time: (0, import_node_fs46.lstatSync)((0, import_node_path37.join)(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time);
46823
48212
  const cutoff = this.now().getTime() - SNAPSHOT_RETENTION_MS;
46824
48213
  const removeCount = Math.max(0, snapshots.length - MAX_SNAPSHOTS);
46825
48214
  snapshots.forEach((snapshot, index) => {
46826
48215
  if (snapshot.time < cutoff || index < removeCount) {
46827
48216
  try {
46828
- (0, import_node_fs40.unlinkSync)(snapshot.path);
48217
+ (0, import_node_fs46.unlinkSync)(snapshot.path);
46829
48218
  } catch {
46830
48219
  }
46831
48220
  }
@@ -46834,10 +48223,10 @@ var CommandHistoryWatcher = class {
46834
48223
  };
46835
48224
 
46836
48225
  // src/daemon/workers/file-integrity.ts
46837
- var import_node_fs41 = require("fs");
46838
- var import_promises4 = require("fs/promises");
46839
- var import_node_crypto11 = require("crypto");
46840
- var import_node_path32 = require("path");
48226
+ var import_node_fs47 = require("fs");
48227
+ var import_promises8 = require("fs/promises");
48228
+ var import_node_crypto13 = require("crypto");
48229
+ var import_node_path38 = require("path");
46841
48230
  var DEFAULT_POLL_MS = 15 * 6e4;
46842
48231
  var MAX_FILES = 5e4;
46843
48232
  var MAX_FILE_BYTES = 64 * 1024 * 1024;
@@ -46852,8 +48241,8 @@ var READ_CHUNK_BYTES = 64 * 1024;
46852
48241
  var CANARY_CONTENT = "ThreatCrush file integrity canary v1\n";
46853
48242
  function fileIntegritySettings(section) {
46854
48243
  const safePath = (value) => {
46855
- if (typeof value !== "string" || !(0, import_node_path32.isAbsolute)(value) || value.split(import_node_path32.sep).includes("..")) return null;
46856
- const path2 = (0, import_node_path32.normalize)(value);
48244
+ if (typeof value !== "string" || !(0, import_node_path38.isAbsolute)(value) || value.split(import_node_path38.sep).includes("..")) return null;
48245
+ const path2 = (0, import_node_path38.normalize)(value);
46857
48246
  return path2 === "/" ? null : path2;
46858
48247
  };
46859
48248
  const strings = (values) => Array.isArray(values) ? [...new Set(values.map(safePath).filter((path2) => path2 !== null))] : [];
@@ -46874,7 +48263,7 @@ function signature(value) {
46874
48263
  }
46875
48264
  async function readState(path2) {
46876
48265
  try {
46877
- const parsed = JSON.parse(await (0, import_promises4.readFile)(path2, "utf8"));
48266
+ const parsed = JSON.parse(await (0, import_promises8.readFile)(path2, "utf8"));
46878
48267
  if (parsed.schema !== 1 || !Array.isArray(parsed.targets) || !parsed.files || typeof parsed.files !== "object") return null;
46879
48268
  return parsed;
46880
48269
  } catch {
@@ -46882,13 +48271,13 @@ async function readState(path2) {
46882
48271
  }
46883
48272
  }
46884
48273
  async function writeState(path2, state) {
46885
- await (0, import_promises4.mkdir)((0, import_node_path32.dirname)(path2), { recursive: true, mode: 448 });
46886
- const temp = `${path2}.${process.pid}.${(0, import_node_crypto11.randomUUID)()}.tmp`;
46887
- await (0, import_promises4.writeFile)(temp, JSON.stringify(state), { mode: 384 });
46888
- await (0, import_promises4.rename)(temp, path2);
48274
+ await (0, import_promises8.mkdir)((0, import_node_path38.dirname)(path2), { recursive: true, mode: 448 });
48275
+ const temp = `${path2}.${process.pid}.${(0, import_node_crypto13.randomUUID)()}.tmp`;
48276
+ await (0, import_promises8.writeFile)(temp, JSON.stringify(state), { mode: 384 });
48277
+ await (0, import_promises8.rename)(temp, path2);
46889
48278
  }
46890
48279
  async function hashFile(path2, handle, size) {
46891
- const hash = (0, import_node_crypto11.createHash)("sha256");
48280
+ const hash = (0, import_node_crypto13.createHash)("sha256");
46892
48281
  const buffer = Buffer.alloc(READ_CHUNK_BYTES);
46893
48282
  const counts = new Uint32Array(256);
46894
48283
  let position = 0;
@@ -46908,19 +48297,19 @@ async function hashFile(path2, handle, size) {
46908
48297
  }
46909
48298
  return { sha256: hash.digest("hex"), entropy };
46910
48299
  }
46911
- var OPEN_FILE_FLAGS = import_promises4.constants.O_RDONLY | import_promises4.constants.O_NONBLOCK | (import_promises4.constants.O_NOFOLLOW ?? 0);
46912
- var OPEN_DIR_FLAGS = OPEN_FILE_FLAGS | import_promises4.constants.O_DIRECTORY;
46913
- var CREATE_FILE_FLAGS = import_promises4.constants.O_WRONLY | import_promises4.constants.O_CREAT | import_promises4.constants.O_EXCL | import_promises4.constants.O_NOFOLLOW;
48300
+ var OPEN_FILE_FLAGS = import_promises8.constants.O_RDONLY | import_promises8.constants.O_NONBLOCK | (import_promises8.constants.O_NOFOLLOW ?? 0);
48301
+ var OPEN_DIR_FLAGS = OPEN_FILE_FLAGS | import_promises8.constants.O_DIRECTORY;
48302
+ var CREATE_FILE_FLAGS = import_promises8.constants.O_WRONLY | import_promises8.constants.O_CREAT | import_promises8.constants.O_EXCL | import_promises8.constants.O_NOFOLLOW;
46914
48303
  function autoCanaryPath(directory) {
46915
- return (0, import_node_path32.join)(directory, ".threatcrush-canary");
48304
+ return (0, import_node_path38.join)(directory, ".threatcrush-canary");
46916
48305
  }
46917
48306
  async function openAbsoluteDirectory(path2) {
46918
- const parts = path2.split(import_node_path32.sep).filter((part) => part && part !== ".");
48307
+ const parts = path2.split(import_node_path38.sep).filter((part) => part && part !== ".");
46919
48308
  if (parts.includes("..")) throw new Error("invalid canary directory");
46920
- let directory = await (0, import_promises4.open)("/", OPEN_DIR_FLAGS);
48309
+ let directory = await (0, import_promises8.open)("/", OPEN_DIR_FLAGS);
46921
48310
  try {
46922
48311
  for (const part of parts) {
46923
- const next = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
48312
+ const next = await (0, import_promises8.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
46924
48313
  await directory.close();
46925
48314
  directory = next;
46926
48315
  }
@@ -46938,9 +48327,9 @@ async function createAutoCanary(path2) {
46938
48327
  } catch (error2) {
46939
48328
  if (error2.code !== "ENOENT") return false;
46940
48329
  }
46941
- const directory = await openAbsoluteDirectory((0, import_node_path32.dirname)(path2));
48330
+ const directory = await openAbsoluteDirectory((0, import_node_path38.dirname)(path2));
46942
48331
  try {
46943
- const file = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${(0, import_node_path32.basename)(path2)}`, CREATE_FILE_FLAGS, 438);
48332
+ const file = await (0, import_promises8.open)(`/proc/self/fd/${directory.fd}/${(0, import_node_path38.basename)(path2)}`, CREATE_FILE_FLAGS, 438);
46944
48333
  try {
46945
48334
  await file.chmod(438);
46946
48335
  await file.writeFile(CANARY_CONTENT);
@@ -46957,16 +48346,16 @@ async function createAutoCanary(path2) {
46957
48346
  }
46958
48347
  }
46959
48348
  async function openAbsoluteTarget(path2) {
46960
- const parts = path2.split(import_node_path32.sep).filter((part) => part && part !== ".");
48349
+ const parts = path2.split(import_node_path38.sep).filter((part) => part && part !== ".");
46961
48350
  if (parts.length === 0 || parts.includes("..")) throw new Error("invalid file integrity path");
46962
- let directory = await (0, import_promises4.open)("/", OPEN_DIR_FLAGS);
48351
+ let directory = await (0, import_promises8.open)("/", OPEN_DIR_FLAGS);
46963
48352
  try {
46964
48353
  for (const part of parts.slice(0, -1)) {
46965
- const next = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
48354
+ const next = await (0, import_promises8.open)(`/proc/self/fd/${directory.fd}/${part}`, OPEN_DIR_FLAGS);
46966
48355
  await directory.close();
46967
48356
  directory = next;
46968
48357
  }
46969
- const target = await (0, import_promises4.open)(`/proc/self/fd/${directory.fd}/${parts.at(-1)}`, OPEN_FILE_FLAGS);
48358
+ const target = await (0, import_promises8.open)(`/proc/self/fd/${directory.fd}/${parts.at(-1)}`, OPEN_FILE_FLAGS);
46970
48359
  await directory.close();
46971
48360
  return target;
46972
48361
  } catch (error2) {
@@ -46992,7 +48381,7 @@ async function scanTargets(targets, canaries) {
46992
48381
  }
46993
48382
  let handle;
46994
48383
  try {
46995
- handle = parent ? await (0, import_promises4.open)(`/proc/self/fd/${parent.fd}/${path2.slice(path2.lastIndexOf(import_node_path32.sep) + 1)}`, OPEN_FILE_FLAGS) : await openAbsoluteTarget(path2);
48384
+ handle = parent ? await (0, import_promises8.open)(`/proc/self/fd/${parent.fd}/${path2.slice(path2.lastIndexOf(import_node_path38.sep) + 1)}`, OPEN_FILE_FLAGS) : await openAbsoluteTarget(path2);
46996
48385
  const stat = await handle.stat();
46997
48386
  if (stat.isDirectory()) {
46998
48387
  directories.push(path2);
@@ -47003,14 +48392,14 @@ async function scanTargets(targets, canaries) {
47003
48392
  }
47004
48393
  let entries;
47005
48394
  try {
47006
- entries = await (0, import_promises4.readdir)(`/proc/self/fd/${handle.fd}`, { withFileTypes: true });
48395
+ entries = await (0, import_promises8.readdir)(`/proc/self/fd/${handle.fd}`, { withFileTypes: true });
47007
48396
  } catch {
47008
48397
  complete = false;
47009
48398
  errors.add(path2);
47010
48399
  return;
47011
48400
  }
47012
48401
  for (const entry of entries) {
47013
- await walk((0, import_node_path32.join)(path2, entry.name), handle);
48402
+ await walk((0, import_node_path38.join)(path2, entry.name), handle);
47014
48403
  if (!complete) return;
47015
48404
  }
47016
48405
  return;
@@ -47148,7 +48537,7 @@ var FileIntegrityWatch = class {
47148
48537
  for (const path2 of wanted) {
47149
48538
  if (this.watchers.has(path2)) continue;
47150
48539
  try {
47151
- const watcher = (0, import_node_fs41.watch)(path2, { persistent: false }, () => {
48540
+ const watcher = (0, import_node_fs47.watch)(path2, { persistent: false }, () => {
47152
48541
  this.scheduleEventScan();
47153
48542
  });
47154
48543
  watcher.on("error", (error2) => {
@@ -47204,7 +48593,7 @@ var FileIntegrityWatch = class {
47204
48593
  let baselineFilePresent = false;
47205
48594
  if (!baseline) {
47206
48595
  try {
47207
- await (0, import_promises4.lstat)(this.opts.baselinePath);
48596
+ await (0, import_promises8.lstat)(this.opts.baselinePath);
47208
48597
  baselineFilePresent = true;
47209
48598
  } catch (error2) {
47210
48599
  baselineFilePresent = error2.code !== "ENOENT";
@@ -47220,7 +48609,7 @@ var FileIntegrityWatch = class {
47220
48609
  if (current.complete) {
47221
48610
  const directories = new Set(current.directories);
47222
48611
  for (const path2 of Object.keys(current.files)) {
47223
- if (!directories.has(path2)) directories.add((0, import_node_path32.dirname)(path2));
48612
+ if (!directories.has(path2)) directories.add((0, import_node_path38.dirname)(path2));
47224
48613
  }
47225
48614
  this.refreshWatchers([...directories]);
47226
48615
  }
@@ -47329,9 +48718,9 @@ var FileIntegrityWatch = class {
47329
48718
  };
47330
48719
 
47331
48720
  // src/daemon/workers/edr.ts
47332
- var import_node_fs42 = require("fs");
47333
- var import_node_path33 = require("path");
47334
- var import_node_child_process14 = require("child_process");
48721
+ var import_node_fs48 = require("fs");
48722
+ var import_node_path39 = require("path");
48723
+ var import_node_child_process15 = require("child_process");
47335
48724
  var DEFAULT_AUDIT_LOG = "/var/log/audit/audit.log";
47336
48725
  var DEFAULT_WEB_USERS = ["www-data", "nginx", "apache", "httpd", "caddy", "node"];
47337
48726
  var DEFAULT_TEMP_PATHS = ["/tmp", "/var/tmp", "/dev/shm"];
@@ -47348,8 +48737,8 @@ var SHELLS = /* @__PURE__ */ new Set(["sh", "bash", "dash", "zsh", "ksh", "fish"
47348
48737
  var DOWNLOADERS = /* @__PURE__ */ new Set(["curl", "wget"]);
47349
48738
  var MINERS = /* @__PURE__ */ new Set(["xmrig", "minerd", "cpuminer", "cpuminer-multi", "kdevtmpfsi", "kinsing", "cryptonight"]);
47350
48739
  function safeAbsolutePath(value) {
47351
- if (typeof value !== "string" || !(0, import_node_path33.isAbsolute)(value) || value.split(import_node_path33.sep).includes("..")) return null;
47352
- const path2 = (0, import_node_path33.normalize)(value);
48740
+ if (typeof value !== "string" || !(0, import_node_path39.isAbsolute)(value) || value.split(import_node_path39.sep).includes("..")) return null;
48741
+ const path2 = (0, import_node_path39.normalize)(value);
47353
48742
  return path2 === "/" ? null : path2;
47354
48743
  }
47355
48744
  function edrSettings(section) {
@@ -47395,7 +48784,7 @@ function parseAuditRecord(line2) {
47395
48784
  serial: header2[2],
47396
48785
  key: fields.key,
47397
48786
  executable,
47398
- comm: fields.comm ?? (0, import_node_path33.basename)(executable),
48787
+ comm: fields.comm ?? (0, import_node_path39.basename)(executable),
47399
48788
  euid,
47400
48789
  ...Number.isInteger(pid) && pid > 0 ? { pid } : {},
47401
48790
  ...Number.isInteger(ppid) && ppid > 0 ? { ppid } : {}
@@ -47404,10 +48793,10 @@ function parseAuditRecord(line2) {
47404
48793
  function accountNames2() {
47405
48794
  let raw = "";
47406
48795
  try {
47407
- raw = (0, import_node_child_process14.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
48796
+ raw = (0, import_node_child_process15.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
47408
48797
  } catch {
47409
48798
  try {
47410
- raw = (0, import_node_fs42.readFileSync)("/etc/passwd", "utf8");
48799
+ raw = (0, import_node_fs48.readFileSync)("/etc/passwd", "utf8");
47411
48800
  } catch {
47412
48801
  return /* @__PURE__ */ new Map();
47413
48802
  }
@@ -47425,7 +48814,7 @@ function pathWithin(path2, root) {
47425
48814
  }
47426
48815
  function executableInWorldWritableDirectory(executable) {
47427
48816
  try {
47428
- return ((0, import_node_fs42.statSync)((0, import_node_path33.dirname)(executable)).mode & 2) !== 0;
48817
+ return ((0, import_node_fs48.statSync)((0, import_node_path39.dirname)(executable)).mode & 2) !== 0;
47429
48818
  } catch {
47430
48819
  return false;
47431
48820
  }
@@ -47459,11 +48848,11 @@ var EdrWatch = class {
47459
48848
  this.opts.log("[edr] disabled; set [edr] enabled = true after installing the generated audit rules");
47460
48849
  return;
47461
48850
  }
47462
- if (!(0, import_node_fs42.existsSync)(this.opts.settings.auditLogPath)) {
48851
+ if (!(0, import_node_fs48.existsSync)(this.opts.settings.auditLogPath)) {
47463
48852
  this.opts.log(`[edr] audit log not found at ${this.opts.settings.auditLogPath}; auditd detections are unavailable`);
47464
48853
  } else {
47465
48854
  try {
47466
- (0, import_node_fs42.accessSync)(this.opts.settings.auditLogPath, import_node_fs42.constants.R_OK);
48855
+ (0, import_node_fs48.accessSync)(this.opts.settings.auditLogPath, import_node_fs48.constants.R_OK);
47467
48856
  this.tail = new LogTail(this.opts.settings.auditLogPath);
47468
48857
  this.timer = setInterval(() => this.poll(), this.opts.settings.pollMs);
47469
48858
  this.timer.unref?.();
@@ -47511,7 +48900,7 @@ var EdrWatch = class {
47511
48900
  this.opts.bus.publish(event);
47512
48901
  }
47513
48902
  classify(execution) {
47514
- const name = (0, import_node_path33.basename)(execution.executable).toLowerCase();
48903
+ const name = (0, import_node_path39.basename)(execution.executable).toLowerCase();
47515
48904
  const account = this.usersById.get(execution.euid) ?? String(execution.euid);
47516
48905
  let severity;
47517
48906
  let ruleId;
@@ -47574,7 +48963,7 @@ var EdrWatch = class {
47574
48963
  const path2 = this.opts.networkBaselinePath;
47575
48964
  if (!path2) return;
47576
48965
  try {
47577
- const parsed = JSON.parse((0, import_node_fs42.readFileSync)(path2, "utf8"));
48966
+ const parsed = JSON.parse((0, import_node_fs48.readFileSync)(path2, "utf8"));
47578
48967
  if (Array.isArray(parsed)) {
47579
48968
  for (const value of parsed.slice(0, 1e4)) {
47580
48969
  if (typeof value === "string" && value.startsWith("/")) this.outboundExecutables.add(value);
@@ -47591,9 +48980,9 @@ var EdrWatch = class {
47591
48980
  if (!path2) return;
47592
48981
  try {
47593
48982
  const temp = `${path2}.${process.pid}.tmp`;
47594
- (0, import_node_fs42.writeFileSync)(temp, `${JSON.stringify([...this.outboundExecutables])}
48983
+ (0, import_node_fs48.writeFileSync)(temp, `${JSON.stringify([...this.outboundExecutables])}
47595
48984
  `, { mode: 384 });
47596
- (0, import_node_fs42.renameSync)(temp, path2);
48985
+ (0, import_node_fs48.renameSync)(temp, path2);
47597
48986
  this.baselineWriteFailed = false;
47598
48987
  } catch (error2) {
47599
48988
  if (!this.baselineWriteFailed) this.opts.log(`[edr] could not persist outbound executable baseline: ${error2.message.split("\n")[0]}`);
@@ -47602,7 +48991,7 @@ var EdrWatch = class {
47602
48991
  }
47603
48992
  readTicksPerSecond() {
47604
48993
  try {
47605
- const value = Number((0, import_node_child_process14.execFileSync)("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }).trim());
48994
+ const value = Number((0, import_node_child_process15.execFileSync)("getconf", ["CLK_TCK"], { encoding: "utf8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }).trim());
47606
48995
  if (Number.isFinite(value) && value > 0) return value;
47607
48996
  } catch {
47608
48997
  }
@@ -47614,7 +49003,7 @@ var EdrWatch = class {
47614
49003
  const current = /* @__PURE__ */ new Map();
47615
49004
  let pids;
47616
49005
  try {
47617
- pids = (0, import_node_fs42.readdirSync)("/proc");
49006
+ pids = (0, import_node_fs48.readdirSync)("/proc");
47618
49007
  } catch {
47619
49008
  return;
47620
49009
  }
@@ -47622,7 +49011,7 @@ var EdrWatch = class {
47622
49011
  if (!/^\d+$/.test(pid)) continue;
47623
49012
  const proc = `/proc/${pid}`;
47624
49013
  try {
47625
- const raw = (0, import_node_fs42.readFileSync)(`${proc}/stat`, "utf8");
49014
+ const raw = (0, import_node_fs48.readFileSync)(`${proc}/stat`, "utf8");
47626
49015
  const end = raw.lastIndexOf(")");
47627
49016
  if (end < 0) continue;
47628
49017
  const fields = raw.slice(end + 1).trim().split(/\s+/);
@@ -47630,10 +49019,10 @@ var EdrWatch = class {
47630
49019
  const systemTicks = Number(fields[12]);
47631
49020
  const startTicks = fields[19];
47632
49021
  if (!Number.isFinite(userTicks) || !Number.isFinite(systemTicks) || !startTicks) continue;
47633
- let executable = (0, import_node_fs42.readlinkSync)(`${proc}/exe`);
49022
+ let executable = (0, import_node_fs48.readlinkSync)(`${proc}/exe`);
47634
49023
  executable = executable.replace(/ \(deleted\)$/, "");
47635
49024
  if (!this.opts.settings.tempExecPaths.some((path2) => pathWithin(executable, path2))) continue;
47636
- const name = (0, import_node_path33.basename)(executable).toLowerCase();
49025
+ const name = (0, import_node_path39.basename)(executable).toLowerCase();
47637
49026
  if (MINERS.has(name)) continue;
47638
49027
  const key = `${pid}:${startTicks}`;
47639
49028
  const ticks = userTicks + systemTicks;
@@ -47669,9 +49058,9 @@ var EdrWatch = class {
47669
49058
  };
47670
49059
 
47671
49060
  // src/daemon/workers/ssh-intrusion.ts
47672
- var import_node_fs43 = require("fs");
47673
- var import_node_path34 = require("path");
47674
- var import_node_child_process15 = require("child_process");
49061
+ var import_node_fs49 = require("fs");
49062
+ var import_node_path40 = require("path");
49063
+ var import_node_child_process16 = require("child_process");
47675
49064
 
47676
49065
  // src/core/asn.ts
47677
49066
  var import_node_dns = require("dns");
@@ -47822,11 +49211,11 @@ var AsnLookup = class {
47822
49211
  }
47823
49212
  };
47824
49213
  function withTimeout(p, ms) {
47825
- return new Promise((resolve8, reject) => {
49214
+ return new Promise((resolve9, reject) => {
47826
49215
  const t = setTimeout(() => reject(new Error("timeout")), ms);
47827
49216
  p.then((v) => {
47828
49217
  clearTimeout(t);
47829
- resolve8(v);
49218
+ resolve9(v);
47830
49219
  }, (e) => {
47831
49220
  clearTimeout(t);
47832
49221
  reject(e);
@@ -47864,35 +49253,35 @@ function parseKeyLoginsByFingerprint(text) {
47864
49253
  }
47865
49254
  function readJson2(path2) {
47866
49255
  try {
47867
- return JSON.parse((0, import_node_fs43.readFileSync)(path2, "utf-8"));
49256
+ return JSON.parse((0, import_node_fs49.readFileSync)(path2, "utf-8"));
47868
49257
  } catch {
47869
49258
  return null;
47870
49259
  }
47871
49260
  }
47872
49261
  function writeJson2(path2, value) {
47873
- (0, import_node_fs43.mkdirSync)((0, import_node_path34.dirname)(path2), { recursive: true });
47874
- (0, import_node_fs43.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
47875
- (0, import_node_fs43.renameSync)(`${path2}.tmp`, path2);
49262
+ (0, import_node_fs49.mkdirSync)((0, import_node_path40.dirname)(path2), { recursive: true });
49263
+ (0, import_node_fs49.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
49264
+ (0, import_node_fs49.renameSync)(`${path2}.tmp`, path2);
47876
49265
  }
47877
49266
  var fsIO2 = {
47878
49267
  readFile: (p) => {
47879
49268
  try {
47880
- return (0, import_node_fs43.readFileSync)(p, "utf-8");
49269
+ return (0, import_node_fs49.readFileSync)(p, "utf-8");
47881
49270
  } catch {
47882
49271
  return null;
47883
49272
  }
47884
49273
  },
47885
49274
  readDir: (p) => {
47886
49275
  try {
47887
- return (0, import_node_fs43.readdirSync)(p);
49276
+ return (0, import_node_fs49.readdirSync)(p);
47888
49277
  } catch {
47889
49278
  return null;
47890
49279
  }
47891
49280
  },
47892
- exists: (p) => (0, import_node_fs43.existsSync)(p)
49281
+ exists: (p) => (0, import_node_fs49.existsSync)(p)
47893
49282
  };
47894
49283
  function defaultRun4(cmd, args) {
47895
- const res = (0, import_node_child_process15.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
49284
+ const res = (0, import_node_child_process16.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 6e4, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
47896
49285
  return res.status === 0 ? res.stdout : null;
47897
49286
  }
47898
49287
  var SshIntrusionWatch = class {
@@ -48090,23 +49479,23 @@ var SshIntrusionWatch = class {
48090
49479
  };
48091
49480
 
48092
49481
  // src/daemon/key-directory.ts
48093
- var import_node_fs44 = require("fs");
49482
+ var import_node_fs50 = require("fs");
48094
49483
  var fsIO3 = {
48095
49484
  readFile: (p) => {
48096
49485
  try {
48097
- return (0, import_node_fs44.readFileSync)(p, "utf-8");
49486
+ return (0, import_node_fs50.readFileSync)(p, "utf-8");
48098
49487
  } catch {
48099
49488
  return null;
48100
49489
  }
48101
49490
  },
48102
49491
  readDir: (p) => {
48103
49492
  try {
48104
- return (0, import_node_fs44.readdirSync)(p);
49493
+ return (0, import_node_fs50.readdirSync)(p);
48105
49494
  } catch {
48106
49495
  return null;
48107
49496
  }
48108
49497
  },
48109
- exists: (p) => (0, import_node_fs44.existsSync)(p)
49498
+ exists: (p) => (0, import_node_fs50.existsSync)(p)
48110
49499
  };
48111
49500
  var KeyDirectory = class {
48112
49501
  constructor(io = fsIO3, now = Date.now, ttlMs = 3e5) {
@@ -48150,7 +49539,7 @@ function enrichLoginEvent(event, keys) {
48150
49539
  }
48151
49540
 
48152
49541
  // src/daemon/workers/lightning-watch.ts
48153
- var import_node_fs45 = require("fs");
49542
+ var import_node_fs51 = require("fs");
48154
49543
  var DEFAULT_CLN_LOGS = [
48155
49544
  "/home/lightning/.lightning/cln.log",
48156
49545
  "/root/.lightning/cln.log",
@@ -48206,9 +49595,9 @@ var LightningWatch = class {
48206
49595
  if (this.opts.enabled === false) return [];
48207
49596
  const found = [];
48208
49597
  for (const path2 of this.opts.paths?.length ? this.opts.paths : DEFAULT_CLN_LOGS) {
48209
- if (!(0, import_node_fs45.existsSync)(path2)) continue;
49598
+ if (!(0, import_node_fs51.existsSync)(path2)) continue;
48210
49599
  try {
48211
- (0, import_node_fs45.accessSync)(path2, import_node_fs45.constants.R_OK);
49600
+ (0, import_node_fs51.accessSync)(path2, import_node_fs51.constants.R_OK);
48212
49601
  } catch {
48213
49602
  continue;
48214
49603
  }
@@ -48243,8 +49632,8 @@ var LightningWatch = class {
48243
49632
  };
48244
49633
 
48245
49634
  // src/core/tor-exits.ts
48246
- var import_node_fs46 = require("fs");
48247
- var import_node_path35 = require("path");
49635
+ var import_node_fs52 = require("fs");
49636
+ var import_node_path41 = require("path");
48248
49637
  var import_node_net15 = require("net");
48249
49638
  var TOR_BULK_EXIT_LIST_URL = "https://check.torproject.org/torbulkexitlist";
48250
49639
  function parseTorExitList(text) {
@@ -48312,10 +49701,10 @@ var TorExitList = class _TorExitList {
48312
49701
  }
48313
49702
  loadCache() {
48314
49703
  try {
48315
- if (!(0, import_node_fs46.existsSync)(this.opts.cachePath)) return false;
48316
- const parsed = parseTorExitList((0, import_node_fs46.readFileSync)(this.opts.cachePath, "utf-8"));
49704
+ if (!(0, import_node_fs52.existsSync)(this.opts.cachePath)) return false;
49705
+ const parsed = parseTorExitList((0, import_node_fs52.readFileSync)(this.opts.cachePath, "utf-8"));
48317
49706
  if (parsed.size === 0) return false;
48318
- this.load(parsed, (0, import_node_fs46.statSync)(this.opts.cachePath).mtimeMs);
49707
+ this.load(parsed, (0, import_node_fs52.statSync)(this.opts.cachePath).mtimeMs);
48319
49708
  this.log(`[tor] loaded ${parsed.size} Tor exit addresses from cache (${new Date(this.updatedAt).toISOString()})`);
48320
49709
  return true;
48321
49710
  } catch (err) {
@@ -48347,9 +49736,9 @@ var TorExitList = class _TorExitList {
48347
49736
  const before2 = this.exits.size;
48348
49737
  this.load(parsed);
48349
49738
  try {
48350
- (0, import_node_fs46.mkdirSync)((0, import_node_path35.dirname)(this.opts.cachePath), { recursive: true });
48351
- (0, import_node_fs46.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
48352
- (0, import_node_fs46.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
49739
+ (0, import_node_fs52.mkdirSync)((0, import_node_path41.dirname)(this.opts.cachePath), { recursive: true });
49740
+ (0, import_node_fs52.writeFileSync)(`${this.opts.cachePath}.tmp`, [...parsed].join("\n") + "\n");
49741
+ (0, import_node_fs52.renameSync)(`${this.opts.cachePath}.tmp`, this.opts.cachePath);
48353
49742
  } catch (err) {
48354
49743
  this.log(`[tor] could not save the exit list cache: ${err.message}`);
48355
49744
  }
@@ -48570,8 +49959,8 @@ var RuleEngine = class {
48570
49959
  };
48571
49960
 
48572
49961
  // src/daemon/rules/loader.ts
48573
- var import_node_fs47 = require("fs");
48574
- var import_node_path36 = require("path");
49962
+ var import_node_fs53 = require("fs");
49963
+ var import_node_path42 = require("path");
48575
49964
 
48576
49965
  // src/daemon/rules/default-rules.ts
48577
49966
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -48635,7 +50024,15 @@ var DEFAULT_RULES = [
48635
50024
  operator: "regex",
48636
50025
  // Attempts only. Matching `accepted` here meant a successful root login
48637
50026
  // banned the administrator who had just made it.
48638
- value: "failed.*\\broot\\b"
50027
+ //
50028
+ // Anchored to the start of an sshd failure ("Failed SSH login for root
50029
+ // from …" from classifySshAuth, or a raw "[sshd] Failed password for
50030
+ // root …" journal line). Unanchored, `failed.*\broot\b` matched any auth
50031
+ // event that said "failed" anywhere before "root": privilege-watch logs
50032
+ // every sudo as "sudo: <user> ran <command> as root", so a backup script
50033
+ // whose text read "the copy failed its integrity check" paged a
50034
+ // high-severity "Root SSH Login Attempt" against the admin's own account.
50035
+ value: "^(?:\\[[^\\]]*\\] )?failed (?:ssh login|password|publickey|keyboard-interactive\\S*|none) for (?:invalid user )?root\\b"
48639
50036
  },
48640
50037
  threshold: 1,
48641
50038
  window_seconds: 60,
@@ -49162,11 +50559,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
49162
50559
  function loadAllRules(customDir) {
49163
50560
  const rules = [...DEFAULT_RULES];
49164
50561
  const dir = customDir || RULES_DIR;
49165
- if ((0, import_node_fs47.existsSync)(dir)) {
49166
- const files = (0, import_node_fs47.readdirSync)(dir).filter((f) => f.endsWith(".json"));
50562
+ if ((0, import_node_fs53.existsSync)(dir)) {
50563
+ const files = (0, import_node_fs53.readdirSync)(dir).filter((f) => f.endsWith(".json"));
49167
50564
  for (const file of files) {
49168
50565
  try {
49169
- const raw = (0, import_node_fs47.readFileSync)((0, import_node_path36.join)(dir, file), "utf-8");
50566
+ const raw = (0, import_node_fs53.readFileSync)((0, import_node_path42.join)(dir, file), "utf-8");
49170
50567
  const parsed = JSON.parse(raw);
49171
50568
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
49172
50569
  for (const rule of customRules) {
@@ -49197,9 +50594,9 @@ function loadAllRules(customDir) {
49197
50594
  }
49198
50595
 
49199
50596
  // src/daemon/firewall/adapters.ts
49200
- var import_node_child_process16 = require("child_process");
49201
- var import_node_fs48 = require("fs");
49202
- var import_node_path37 = require("path");
50597
+ var import_node_child_process17 = require("child_process");
50598
+ var import_node_fs54 = require("fs");
50599
+ var import_node_path43 = require("path");
49203
50600
  var import_node_net16 = require("net");
49204
50601
  function assertValidFirewallIp(ip) {
49205
50602
  if ((0, import_node_net16.isIP)(ip) !== 4) {
@@ -49212,9 +50609,9 @@ function assertBannableIp(ip) {
49212
50609
  }
49213
50610
  }
49214
50611
  function writeIfAbsent(path2, contents) {
49215
- (0, import_node_fs48.mkdirSync)((0, import_node_path37.dirname)(path2), { recursive: true });
50612
+ (0, import_node_fs54.mkdirSync)((0, import_node_path43.dirname)(path2), { recursive: true });
49216
50613
  try {
49217
- (0, import_node_fs48.writeFileSync)(path2, contents, { flag: "wx" });
50614
+ (0, import_node_fs54.writeFileSync)(path2, contents, { flag: "wx" });
49218
50615
  } catch (err) {
49219
50616
  if (err.code !== "EEXIST") throw err;
49220
50617
  }
@@ -49233,11 +50630,11 @@ var Fail2banAdapter = class {
49233
50630
  enforces = true;
49234
50631
  jailReady = false;
49235
50632
  isAvailable() {
49236
- const result = (0, import_node_child_process16.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
50633
+ const result = (0, import_node_child_process17.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
49237
50634
  return result.status === 0;
49238
50635
  }
49239
50636
  client(args) {
49240
- return (0, import_node_child_process16.execFileSync)("fail2ban-client", args, {
50637
+ return (0, import_node_child_process17.execFileSync)("fail2ban-client", args, {
49241
50638
  encoding: "utf-8",
49242
50639
  stdio: ["ignore", "pipe", "pipe"]
49243
50640
  });
@@ -49333,35 +50730,35 @@ var NftablesAdapter = class {
49333
50730
  table = "threatcrush";
49334
50731
  set = "blocklist";
49335
50732
  isAvailable() {
49336
- const result = (0, import_node_child_process16.spawnSync)("nft", ["--version"], { stdio: "pipe" });
50733
+ const result = (0, import_node_child_process17.spawnSync)("nft", ["--version"], { stdio: "pipe" });
49337
50734
  return result.status === 0;
49338
50735
  }
49339
50736
  ensureSetup() {
49340
50737
  try {
49341
- (0, import_node_child_process16.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
50738
+ (0, import_node_child_process17.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
49342
50739
  } catch {
49343
- (0, import_node_child_process16.execSync)(`nft add table inet ${this.table}`);
49344
- (0, import_node_child_process16.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
49345
- (0, import_node_child_process16.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
49346
- (0, import_node_child_process16.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
50740
+ (0, import_node_child_process17.execSync)(`nft add table inet ${this.table}`);
50741
+ (0, import_node_child_process17.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
50742
+ (0, import_node_child_process17.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
50743
+ (0, import_node_child_process17.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
49347
50744
  }
49348
50745
  }
49349
50746
  async block(ip) {
49350
50747
  assertValidFirewallIp(ip);
49351
50748
  this.ensureSetup();
49352
- (0, import_node_child_process16.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
50749
+ (0, import_node_child_process17.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
49353
50750
  }
49354
50751
  async unblock(ip) {
49355
50752
  assertValidFirewallIp(ip);
49356
50753
  try {
49357
- (0, import_node_child_process16.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
50754
+ (0, import_node_child_process17.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
49358
50755
  } catch {
49359
50756
  }
49360
50757
  }
49361
50758
  async isBlocked(ip) {
49362
50759
  assertValidFirewallIp(ip);
49363
50760
  try {
49364
- const output = (0, import_node_child_process16.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
50761
+ const output = (0, import_node_child_process17.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
49365
50762
  return output.includes(ip);
49366
50763
  } catch {
49367
50764
  return false;
@@ -49369,7 +50766,7 @@ var NftablesAdapter = class {
49369
50766
  }
49370
50767
  async listBlocked() {
49371
50768
  try {
49372
- const output = (0, import_node_child_process16.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
50769
+ const output = (0, import_node_child_process17.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
49373
50770
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
49374
50771
  if (!match) return [];
49375
50772
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -49382,34 +50779,34 @@ var IptablesAdapter = class {
49382
50779
  name = "iptables";
49383
50780
  chain = "THREATCRUSH";
49384
50781
  isAvailable() {
49385
- const result = (0, import_node_child_process16.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
50782
+ const result = (0, import_node_child_process17.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
49386
50783
  return result.status === 0;
49387
50784
  }
49388
50785
  ensureChain() {
49389
50786
  try {
49390
- (0, import_node_child_process16.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
50787
+ (0, import_node_child_process17.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
49391
50788
  } catch {
49392
- (0, import_node_child_process16.execSync)(`iptables -N ${this.chain}`);
49393
- (0, import_node_child_process16.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
50789
+ (0, import_node_child_process17.execSync)(`iptables -N ${this.chain}`);
50790
+ (0, import_node_child_process17.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
49394
50791
  }
49395
50792
  }
49396
50793
  async block(ip) {
49397
50794
  assertValidFirewallIp(ip);
49398
50795
  this.ensureChain();
49399
50796
  if (await this.isBlocked(ip)) return;
49400
- (0, import_node_child_process16.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
50797
+ (0, import_node_child_process17.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
49401
50798
  }
49402
50799
  async unblock(ip) {
49403
50800
  assertValidFirewallIp(ip);
49404
50801
  try {
49405
- (0, import_node_child_process16.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
50802
+ (0, import_node_child_process17.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
49406
50803
  } catch {
49407
50804
  }
49408
50805
  }
49409
50806
  async isBlocked(ip) {
49410
50807
  assertValidFirewallIp(ip);
49411
50808
  try {
49412
- const output = (0, import_node_child_process16.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
50809
+ const output = (0, import_node_child_process17.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
49413
50810
  return output.includes(ip);
49414
50811
  } catch {
49415
50812
  return false;
@@ -49417,7 +50814,7 @@ var IptablesAdapter = class {
49417
50814
  }
49418
50815
  async listBlocked() {
49419
50816
  try {
49420
- const output = (0, import_node_child_process16.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
50817
+ const output = (0, import_node_child_process17.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
49421
50818
  const ips = [];
49422
50819
  for (const line2 of output.split("\n")) {
49423
50820
  const match = line2.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -49473,8 +50870,8 @@ function detectFirewallAdapter(backend = "auto") {
49473
50870
  }
49474
50871
 
49475
50872
  // src/daemon/firewall/remediation.ts
49476
- var import_node_fs49 = require("fs");
49477
- var import_node_child_process17 = require("child_process");
50873
+ var import_node_fs55 = require("fs");
50874
+ var import_node_child_process18 = require("child_process");
49478
50875
  var import_node_net17 = require("net");
49479
50876
  init_paths();
49480
50877
  init_backoff();
@@ -49545,19 +50942,19 @@ var defaultDiscovery = {
49545
50942
  const snapshot = takeSnapshot({
49546
50943
  readFile: (p) => {
49547
50944
  try {
49548
- return (0, import_node_fs49.readFileSync)(p, "utf-8");
50945
+ return (0, import_node_fs55.readFileSync)(p, "utf-8");
49549
50946
  } catch {
49550
50947
  return null;
49551
50948
  }
49552
50949
  },
49553
50950
  readDir: (p) => {
49554
50951
  try {
49555
- return (0, import_node_fs49.readdirSync)(p);
50952
+ return (0, import_node_fs55.readdirSync)(p);
49556
50953
  } catch {
49557
50954
  return null;
49558
50955
  }
49559
50956
  },
49560
- exists: (p) => (0, import_node_fs49.existsSync)(p)
50957
+ exists: (p) => (0, import_node_fs55.existsSync)(p)
49561
50958
  });
49562
50959
  const out = /* @__PURE__ */ new Set();
49563
50960
  for (const keys of Object.values(snapshot.keys)) {
@@ -49565,12 +50962,12 @@ var defaultDiscovery = {
49565
50962
  }
49566
50963
  return out;
49567
50964
  },
49568
- keyLoginJournal: (sinceSeconds) => new Promise((resolve8) => {
49569
- (0, import_node_child_process17.execFile)(
50965
+ keyLoginJournal: (sinceSeconds) => new Promise((resolve9) => {
50966
+ (0, import_node_child_process18.execFile)(
49570
50967
  "journalctl",
49571
50968
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
49572
50969
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
49573
- (_err, stdout) => resolve8(stdout ?? "")
50970
+ (_err, stdout) => resolve9(stdout ?? "")
49574
50971
  );
49575
50972
  })
49576
50973
  };
@@ -50070,7 +51467,7 @@ var RemediationManager = class {
50070
51467
  }
50071
51468
  logLine(line2) {
50072
51469
  try {
50073
- (0, import_node_fs49.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
51470
+ (0, import_node_fs55.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
50074
51471
  `);
50075
51472
  } catch {
50076
51473
  }
@@ -50114,19 +51511,19 @@ function remediationSettings(section) {
50114
51511
  init_backoff();
50115
51512
 
50116
51513
  // src/daemon/watchdog-service.ts
50117
- var import_node_fs50 = require("fs");
50118
- var import_node_path38 = require("path");
51514
+ var import_node_fs56 = require("fs");
51515
+ var import_node_path44 = require("path");
50119
51516
  function defaultShareGid() {
50120
51517
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
50121
51518
  if (!isRoot4) return void 0;
50122
51519
  try {
50123
- return (0, import_node_fs50.statSync)("/var/log/auth.log").gid;
51520
+ return (0, import_node_fs56.statSync)("/var/log/auth.log").gid;
50124
51521
  } catch {
50125
51522
  return void 0;
50126
51523
  }
50127
51524
  }
50128
51525
  function startWatchdog(opts) {
50129
- const dir = opts.config?.dir ?? (0, import_node_path38.join)(opts.stateDir, WATCHDOG_DIRNAME);
51526
+ const dir = opts.config?.dir ?? (0, import_node_path44.join)(opts.stateDir, WATCHDOG_DIRNAME);
50130
51527
  const base = { dir, logged: 0, answered: 0, errored: 0 };
50131
51528
  if (opts.config?.enabled === false) {
50132
51529
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -50220,7 +51617,7 @@ async function flushTelemetry(timeoutMs = 2e3) {
50220
51617
  }
50221
51618
 
50222
51619
  // src/core/node-runtime.ts
50223
- var import_node_child_process18 = require("child_process");
51620
+ var import_node_child_process19 = require("child_process");
50224
51621
  var MIN_DAEMON_NODE_MAJOR = 22;
50225
51622
  function nodeMajor(version) {
50226
51623
  const m = String(version ?? "").trim().replace(/^v/, "").match(/^(\d+)\./);
@@ -50234,23 +51631,23 @@ function daemonNodeProblem(version) {
50234
51631
  }
50235
51632
  function versionOfNode(path2) {
50236
51633
  if (path2 === process.execPath) return process.versions.node;
50237
- const res = (0, import_node_child_process18.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
51634
+ const res = (0, import_node_child_process19.spawnSync)(path2, ["-p", "process.versions.node"], { encoding: "utf-8", timeout: 5e3 });
50238
51635
  return res.status === 0 ? res.stdout.trim() : null;
50239
51636
  }
50240
51637
 
50241
51638
  // src/daemon/index.ts
50242
51639
  function readVersion2() {
50243
51640
  try {
50244
- const pkg = JSON.parse((0, import_node_fs51.readFileSync)((0, import_node_path39.join)(__dirname, "..", "package.json"), "utf-8"));
51641
+ const pkg = JSON.parse((0, import_node_fs57.readFileSync)((0, import_node_path45.join)(__dirname, "..", "package.json"), "utf-8"));
50245
51642
  return pkg.version || "0.0.0";
50246
51643
  } catch {
50247
51644
  return "0.0.0";
50248
51645
  }
50249
51646
  }
50250
51647
  async function runHardeningChecks() {
50251
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process19.execFile)(
51648
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process20.execFile)(
50252
51649
  process.execPath,
50253
- [(0, import_node_path39.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
51650
+ [(0, import_node_path45.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
50254
51651
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
50255
51652
  );
50256
51653
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -50262,9 +51659,9 @@ async function runHardeningChecks() {
50262
51659
  return patches ? [...findings2, patches] : findings2;
50263
51660
  }
50264
51661
  async function runPatchCheck() {
50265
- const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process19.execFile)(
51662
+ const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process20.execFile)(
50266
51663
  process.execPath,
50267
- [(0, import_node_path39.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
51664
+ [(0, import_node_path45.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
50268
51665
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
50269
51666
  );
50270
51667
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -50272,7 +51669,7 @@ async function runPatchCheck() {
50272
51669
  }
50273
51670
  function logLine(line2) {
50274
51671
  try {
50275
- (0, import_node_fs51.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
51672
+ (0, import_node_fs57.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
50276
51673
  `);
50277
51674
  } catch {
50278
51675
  }
@@ -50297,9 +51694,9 @@ async function runDaemon() {
50297
51694
  logLine(`[daemon] starting threatcrushd v${version} mode=${PATHS.mode}`);
50298
51695
  const restartDaemon = () => {
50299
51696
  if (PATHS.mode === "system") {
50300
- (0, import_node_child_process19.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
51697
+ (0, import_node_child_process20.spawn)("systemctl", ["restart", "threatcrushd"], { detached: true, stdio: "ignore" }).unref();
50301
51698
  } else {
50302
- (0, import_node_child_process19.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
51699
+ (0, import_node_child_process20.spawn)(process.execPath, process.argv.slice(1), { detached: true, stdio: "ignore" }).unref();
50303
51700
  setTimeout(() => process.exit(0), 500).unref();
50304
51701
  }
50305
51702
  };
@@ -50314,7 +51711,7 @@ async function runDaemon() {
50314
51711
  } catch (err) {
50315
51712
  logLine(`[daemon] state db unavailable: ${err.message}`);
50316
51713
  }
50317
- const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path39.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
51714
+ const loaded = loadDaemonConfig(PATHS.configFile, (0, import_node_path45.join)(PATHS.stateDir, "threatcrushd.conf.last-good"));
50318
51715
  const config = loaded.config;
50319
51716
  if (loaded.error) {
50320
51717
  logLine(`[daemon] CONFIG ERROR: ${loaded.error}; ${loaded.usedLastGood ? "running on the last config that parsed" : "no earlier good copy, running on DEFAULTS (no protected list)"}`);
@@ -50385,7 +51782,7 @@ async function runDaemon() {
50385
51782
  const threatFeeds = new ThreatFeeds({
50386
51783
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
50387
51784
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
50388
- cachePath: (0, import_node_path39.join)(PATHS.stateDir, "threat-feeds.json"),
51785
+ cachePath: (0, import_node_path45.join)(PATHS.stateDir, "threat-feeds.json"),
50389
51786
  bus,
50390
51787
  log: logLine
50391
51788
  });
@@ -50393,9 +51790,9 @@ async function runDaemon() {
50393
51790
  const privilegeWatch = new PrivilegeWatch({
50394
51791
  settings: privilegeSettings(config.privileged),
50395
51792
  bus,
50396
- snapshotPath: (0, import_node_path39.join)(PATHS.stateDir, "privileges.json"),
50397
- loginsPath: (0, import_node_path39.join)(PATHS.stateDir, "login-countries.json"),
50398
- cursorPath: (0, import_node_path39.join)(PATHS.stateDir, "sudo-cursor.json"),
51793
+ snapshotPath: (0, import_node_path45.join)(PATHS.stateDir, "privileges.json"),
51794
+ loginsPath: (0, import_node_path45.join)(PATHS.stateDir, "login-countries.json"),
51795
+ cursorPath: (0, import_node_path45.join)(PATHS.stateDir, "sudo-cursor.json"),
50399
51796
  log: logLine
50400
51797
  });
50401
51798
  privilegeWatch.start();
@@ -50409,20 +51806,20 @@ async function runDaemon() {
50409
51806
  const fileIntegrity = new FileIntegrityWatch({
50410
51807
  bus,
50411
51808
  settings: fileIntegritySettings(config.file_integrity),
50412
- baselinePath: (0, import_node_path39.join)(PATHS.stateDir, "file-integrity-baseline.json"),
50413
- observedPath: (0, import_node_path39.join)(PATHS.stateDir, "file-integrity-observed.json"),
51809
+ baselinePath: (0, import_node_path45.join)(PATHS.stateDir, "file-integrity-baseline.json"),
51810
+ observedPath: (0, import_node_path45.join)(PATHS.stateDir, "file-integrity-observed.json"),
50414
51811
  log: logLine
50415
51812
  });
50416
51813
  fileIntegrity.start();
50417
51814
  const edr = new EdrWatch({
50418
51815
  bus,
50419
51816
  settings: edrSettings(config.edr),
50420
- networkBaselinePath: (0, import_node_path39.join)(PATHS.stateDir, "edr-outbound-executables.json"),
51817
+ networkBaselinePath: (0, import_node_path45.join)(PATHS.stateDir, "edr-outbound-executables.json"),
50421
51818
  log: logLine
50422
51819
  });
50423
51820
  edr.start();
50424
51821
  const torExits = new TorExitList({
50425
- cachePath: (0, import_node_path39.join)(PATHS.stateDir, "tor-exits.txt"),
51822
+ cachePath: (0, import_node_path45.join)(PATHS.stateDir, "tor-exits.txt"),
50426
51823
  url: config.remediation?.tor_exit_list_url,
50427
51824
  log: logLine
50428
51825
  });
@@ -50430,7 +51827,7 @@ async function runDaemon() {
50430
51827
  bus,
50431
51828
  manager: remediation,
50432
51829
  tor: torExits,
50433
- historyPath: (0, import_node_path39.join)(PATHS.stateDir, "key-logins.json"),
51830
+ historyPath: (0, import_node_path45.join)(PATHS.stateDir, "key-logins.json"),
50434
51831
  keyLoginWatch: config.privileged?.key_login_watch !== false,
50435
51832
  log: logLine
50436
51833
  });
@@ -50475,9 +51872,9 @@ async function runDaemon() {
50475
51872
  cloudSync = new CloudSync({
50476
51873
  bus,
50477
51874
  version,
50478
- hostname: (0, import_node_os14.hostname)(),
51875
+ hostname: (0, import_node_os18.hostname)(),
50479
51876
  minSeverity,
50480
- spoolPath: (0, import_node_path39.join)(PATHS.stateDir, "cloud-spool.jsonl"),
51877
+ spoolPath: (0, import_node_path45.join)(PATHS.stateDir, "cloud-spool.jsonl"),
50481
51878
  log: logLine,
50482
51879
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
50483
51880
  runHardening: runHardeningChecks
@@ -50510,8 +51907,8 @@ async function runDaemon() {
50510
51907
  const autoUpdate = autoUpdateRef = new AutoUpdate({
50511
51908
  version,
50512
51909
  settings: updateSettings(config.update),
50513
- pkgRoot: (0, import_node_path39.join)(__dirname, ".."),
50514
- statePath: (0, import_node_path39.join)(PATHS.stateDir, "auto-update.json"),
51910
+ pkgRoot: (0, import_node_path45.join)(__dirname, ".."),
51911
+ statePath: (0, import_node_path45.join)(PATHS.stateDir, "auto-update.json"),
50515
51912
  bus,
50516
51913
  log: logLine,
50517
51914
  restartDaemon
@@ -50621,7 +52018,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
50621
52018
  function isRoot2() {
50622
52019
  return typeof process.getuid === "function" && process.getuid() === 0;
50623
52020
  }
50624
- var DAEMON_ENTRY = (0, import_node_path40.join)(__dirname, "daemon.js");
52021
+ var DAEMON_ENTRY = (0, import_node_path46.join)(__dirname, "daemon.js");
50625
52022
  async function daemonForeground() {
50626
52023
  await runDaemon();
50627
52024
  }
@@ -50642,7 +52039,7 @@ async function daemonStart() {
50642
52039
  return;
50643
52040
  }
50644
52041
  ensureRuntimeDirs();
50645
- if (!(0, import_node_fs52.existsSync)(DAEMON_ENTRY)) {
52042
+ if (!(0, import_node_fs58.existsSync)(DAEMON_ENTRY)) {
50646
52043
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
50647
52044
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
50648
52045
  return;
@@ -50650,8 +52047,8 @@ async function daemonStart() {
50650
52047
  let out;
50651
52048
  let err;
50652
52049
  try {
50653
- out = (0, import_node_fs53.openSync)(PATHS.logFile, "a");
50654
- err = (0, import_node_fs53.openSync)(PATHS.logFile, "a");
52050
+ out = (0, import_node_fs59.openSync)(PATHS.logFile, "a");
52051
+ err = (0, import_node_fs59.openSync)(PATHS.logFile, "a");
50655
52052
  } catch (e) {
50656
52053
  const code = e.code;
50657
52054
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -50664,7 +52061,7 @@ async function daemonStart() {
50664
52061
  }
50665
52062
  return;
50666
52063
  }
50667
- const child = (0, import_node_child_process20.spawn)(process.execPath, [DAEMON_ENTRY], {
52064
+ const child = (0, import_node_child_process21.spawn)(process.execPath, [DAEMON_ENTRY], {
50668
52065
  detached: true,
50669
52066
  stdio: ["ignore", out, err],
50670
52067
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -50739,41 +52136,41 @@ async function waitForExit(pid, timeoutMs) {
50739
52136
  }
50740
52137
  async function releaseStaleSocket() {
50741
52138
  const deadline = Date.now() + 2e3;
50742
- while ((0, import_node_fs52.existsSync)(PATHS.socket) && Date.now() < deadline) {
52139
+ while ((0, import_node_fs58.existsSync)(PATHS.socket) && Date.now() < deadline) {
50743
52140
  await new Promise((r) => setTimeout(r, 50));
50744
52141
  }
50745
- if ((0, import_node_fs52.existsSync)(PATHS.socket)) {
52142
+ if ((0, import_node_fs58.existsSync)(PATHS.socket)) {
50746
52143
  try {
50747
- (0, import_node_fs52.unlinkSync)(PATHS.socket);
52144
+ (0, import_node_fs58.unlinkSync)(PATHS.socket);
50748
52145
  } catch {
50749
52146
  }
50750
52147
  }
50751
52148
  }
50752
52149
 
50753
52150
  // src/commands/service.ts
50754
- var import_node_child_process21 = require("child_process");
50755
- var import_node_fs54 = require("fs");
50756
- var import_node_path41 = require("path");
50757
- var import_node_os15 = require("os");
52151
+ var import_node_child_process22 = require("child_process");
52152
+ var import_node_fs60 = require("fs");
52153
+ var import_node_path47 = require("path");
52154
+ var import_node_os19 = require("os");
50758
52155
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
50759
52156
  var DAEMON_UNIT_NAME = "threatcrushd.service";
50760
52157
  function resolveTemplate() {
50761
- const templatePath = (0, import_node_path41.join)(__dirname, "systemd", "threatcrushd.service");
50762
- if (!(0, import_node_fs54.existsSync)(templatePath)) {
52158
+ const templatePath = (0, import_node_path47.join)(__dirname, "systemd", "threatcrushd.service");
52159
+ if (!(0, import_node_fs60.existsSync)(templatePath)) {
50763
52160
  throw new Error(`systemd unit template not found at ${templatePath}`);
50764
52161
  }
50765
- return (0, import_node_fs54.readFileSync)(templatePath, "utf-8");
52162
+ return (0, import_node_fs60.readFileSync)(templatePath, "utf-8");
50766
52163
  }
50767
52164
  function stableBinPath(binPath) {
50768
52165
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
50769
52166
  if (stable === binPath) return binPath;
50770
- return (0, import_node_fs54.existsSync)(stable) ? stable : binPath;
52167
+ return (0, import_node_fs60.existsSync)(stable) ? stable : binPath;
50771
52168
  }
50772
52169
  function resolveBinPath() {
50773
52170
  const arg = process.argv[1];
50774
- if (arg && (0, import_node_fs54.existsSync)(arg)) return stableBinPath(arg);
52171
+ if (arg && (0, import_node_fs60.existsSync)(arg)) return stableBinPath(arg);
50775
52172
  try {
50776
- return (0, import_node_child_process21.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
52173
+ return (0, import_node_child_process22.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
50777
52174
  } catch {
50778
52175
  return "threatcrush";
50779
52176
  }
@@ -50781,11 +52178,11 @@ function resolveBinPath() {
50781
52178
  function stableNodePath(execPath) {
50782
52179
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
50783
52180
  if (stable === execPath) return execPath;
50784
- return (0, import_node_fs54.existsSync)(stable) ? stable : execPath;
52181
+ return (0, import_node_fs60.existsSync)(stable) ? stable : execPath;
50785
52182
  }
50786
52183
  function looksLikeNodeScript(path2) {
50787
52184
  try {
50788
- const head = (0, import_node_fs54.readFileSync)(path2, "utf-8").slice(0, 120);
52185
+ const head = (0, import_node_fs60.readFileSync)(path2, "utf-8").slice(0, 120);
50789
52186
  return /^#!.*\bnode\b/.test(head);
50790
52187
  } catch {
50791
52188
  return false;
@@ -50812,20 +52209,20 @@ function isRoot3() {
50812
52209
  return typeof process.getuid === "function" && process.getuid() === 0;
50813
52210
  }
50814
52211
  function reexecWithSudo(args) {
50815
- if ((0, import_node_child_process21.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
52212
+ if ((0, import_node_child_process22.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
50816
52213
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
50817
52214
  const bin = resolveBinPath();
50818
52215
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
50819
- const result = (0, import_node_child_process21.spawnSync)("sudo", argv, { stdio: "inherit" });
52216
+ const result = (0, import_node_child_process22.spawnSync)("sudo", argv, { stdio: "inherit" });
50820
52217
  return result.status === 0;
50821
52218
  }
50822
52219
  function callerHome() {
50823
52220
  const user = process.env.SUDO_USER;
50824
52221
  if (!user) return null;
50825
52222
  try {
50826
- const line2 = (0, import_node_child_process21.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
52223
+ const line2 = (0, import_node_child_process22.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
50827
52224
  const home = line2.split(":")[5];
50828
- return home && (0, import_node_fs54.existsSync)(home) ? home : null;
52225
+ return home && (0, import_node_fs60.existsSync)(home) ? home : null;
50829
52226
  } catch {
50830
52227
  return null;
50831
52228
  }
@@ -50833,13 +52230,13 @@ function callerHome() {
50833
52230
  function stopUserModeDaemon() {
50834
52231
  const home = callerHome();
50835
52232
  if (!home) return;
50836
- const runDir = (0, import_node_path41.join)(home, ".threatcrush", "run");
50837
- const pidFile = (0, import_node_path41.join)(runDir, "threatcrushd.pid");
50838
- const socket = (0, import_node_path41.join)(runDir, "threatcrushd.sock");
50839
- if (!(0, import_node_fs54.existsSync)(pidFile) && !(0, import_node_fs54.existsSync)(socket)) return;
52233
+ const runDir = (0, import_node_path47.join)(home, ".threatcrush", "run");
52234
+ const pidFile = (0, import_node_path47.join)(runDir, "threatcrushd.pid");
52235
+ const socket = (0, import_node_path47.join)(runDir, "threatcrushd.sock");
52236
+ if (!(0, import_node_fs60.existsSync)(pidFile) && !(0, import_node_fs60.existsSync)(socket)) return;
50840
52237
  let pid = null;
50841
52238
  try {
50842
- pid = Number.parseInt((0, import_node_fs54.readFileSync)(pidFile, "utf-8").trim(), 10);
52239
+ pid = Number.parseInt((0, import_node_fs60.readFileSync)(pidFile, "utf-8").trim(), 10);
50843
52240
  } catch {
50844
52241
  pid = null;
50845
52242
  }
@@ -50852,13 +52249,13 @@ function stopUserModeDaemon() {
50852
52249
  }
50853
52250
  for (const path2 of [socket, pidFile]) {
50854
52251
  try {
50855
- if ((0, import_node_fs54.existsSync)(path2)) (0, import_node_fs54.rmSync)(path2);
52252
+ if ((0, import_node_fs60.existsSync)(path2)) (0, import_node_fs60.rmSync)(path2);
50856
52253
  } catch {
50857
52254
  }
50858
52255
  }
50859
52256
  }
50860
52257
  function unitIsActive() {
50861
- const result = (0, import_node_child_process21.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
52258
+ const result = (0, import_node_child_process22.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
50862
52259
  return result.status === 0;
50863
52260
  }
50864
52261
  async function installServiceCommand() {
@@ -50869,8 +52266,8 @@ async function installServiceCommand() {
50869
52266
  return;
50870
52267
  }
50871
52268
  const noSystemd = systemdUnavailableReason({
50872
- hasSystemctl: (0, import_node_child_process21.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
50873
- booted: (0, import_node_fs54.existsSync)("/run/systemd/system")
52269
+ hasSystemctl: (0, import_node_child_process22.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
52270
+ booted: (0, import_node_fs60.existsSync)("/run/systemd/system")
50874
52271
  });
50875
52272
  if (noSystemd) {
50876
52273
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -50892,7 +52289,7 @@ async function installServiceCommand() {
50892
52289
  const isNodeScript = looksLikeNodeScript(binPath);
50893
52290
  let nodePath = stableNodePath(process.execPath);
50894
52291
  if (isNodeScript && nodeVersionDir(binPath)) {
50895
- binPath = (0, import_node_fs54.realpathSync)(binPath);
52292
+ binPath = (0, import_node_fs60.realpathSync)(binPath);
50896
52293
  nodePath = process.execPath;
50897
52294
  }
50898
52295
  if (isNodeScript) {
@@ -50905,11 +52302,11 @@ async function installServiceCommand() {
50905
52302
  }
50906
52303
  }
50907
52304
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
50908
- const configDir = (0, import_node_path41.join)((0, import_node_os15.homedir)(), ".threatcrush");
52305
+ const configDir = (0, import_node_path47.join)((0, import_node_os19.homedir)(), ".threatcrush");
50909
52306
  const commandHistoryEnabled = commandHistorySettings(loadConfig().command_history).enabled;
50910
52307
  const historyPaths = commandHistoryEnabled ? historyWritableHomes() : [];
50911
52308
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir, historyPaths });
50912
- (0, import_node_fs54.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
52309
+ (0, import_node_fs60.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
50913
52310
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
50914
52311
  console.log(source_default.dim(` ExecStart=${exec}`));
50915
52312
  const nodeDir = nodeVersionDir(nodePath);
@@ -50924,8 +52321,8 @@ async function installServiceCommand() {
50924
52321
  installLogrotate();
50925
52322
  stopUserModeDaemon();
50926
52323
  try {
50927
- (0, import_node_child_process21.execSync)("systemctl daemon-reload", { stdio: "inherit" });
50928
- (0, import_node_child_process21.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
52324
+ (0, import_node_child_process22.execSync)("systemctl daemon-reload", { stdio: "inherit" });
52325
+ (0, import_node_child_process22.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
50929
52326
  } catch (err) {
50930
52327
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
50931
52328
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
@@ -50962,9 +52359,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
50962
52359
  ].join("\n");
50963
52360
  }
50964
52361
  function installLogrotate() {
50965
- if (!(0, import_node_fs54.existsSync)((0, import_node_path41.dirname)(LOGROTATE_PATH))) return;
52362
+ if (!(0, import_node_fs60.existsSync)((0, import_node_path47.dirname)(LOGROTATE_PATH))) return;
50966
52363
  try {
50967
- (0, import_node_fs54.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
52364
+ (0, import_node_fs60.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
50968
52365
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
50969
52366
  } catch (err) {
50970
52367
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -50986,20 +52383,20 @@ function ensureSystemDirs(configDir) {
50986
52383
  ];
50987
52384
  let admGid2 = null;
50988
52385
  try {
50989
- admGid2 = (0, import_node_fs54.statSync)("/var/log/auth.log").gid;
52386
+ admGid2 = (0, import_node_fs60.statSync)("/var/log/auth.log").gid;
50990
52387
  } catch {
50991
52388
  }
50992
52389
  for (const { path: path2, groupWritable, sticky } of dirs) {
50993
52390
  try {
50994
- (0, import_node_fs54.mkdirSync)(path2, { recursive: true });
52391
+ (0, import_node_fs60.mkdirSync)(path2, { recursive: true });
50995
52392
  } catch {
50996
52393
  }
50997
52394
  try {
50998
52395
  if (groupWritable && admGid2 !== null) {
50999
- (0, import_node_fs54.chmodSync)(path2, sticky ? 1533 : 509);
51000
- (0, import_node_child_process21.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
52396
+ (0, import_node_fs60.chmodSync)(path2, sticky ? 1533 : 509);
52397
+ (0, import_node_child_process22.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
51001
52398
  } else {
51002
- (0, import_node_fs54.chmodSync)(path2, 493);
52399
+ (0, import_node_fs60.chmodSync)(path2, 493);
51003
52400
  }
51004
52401
  } catch {
51005
52402
  }
@@ -51019,29 +52416,29 @@ async function uninstallServiceCommand() {
51019
52416
  return;
51020
52417
  }
51021
52418
  try {
51022
- (0, import_node_child_process21.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
52419
+ (0, import_node_child_process22.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
51023
52420
  } catch {
51024
52421
  }
51025
52422
  try {
51026
- (0, import_node_child_process21.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
52423
+ (0, import_node_child_process22.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
51027
52424
  } catch {
51028
52425
  }
51029
52426
  try {
51030
- if ((0, import_node_fs54.existsSync)(UNIT_PATH)) {
51031
- (0, import_node_child_process21.execSync)(`rm -f ${UNIT_PATH}`);
52427
+ if ((0, import_node_fs60.existsSync)(UNIT_PATH)) {
52428
+ (0, import_node_child_process22.execSync)(`rm -f ${UNIT_PATH}`);
51032
52429
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
51033
52430
  }
51034
52431
  } catch {
51035
52432
  }
51036
52433
  try {
51037
- (0, import_node_child_process21.execSync)("systemctl daemon-reload", { stdio: "inherit" });
52434
+ (0, import_node_child_process22.execSync)("systemctl daemon-reload", { stdio: "inherit" });
51038
52435
  } catch {
51039
52436
  }
51040
52437
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
51041
52438
  }
51042
52439
 
51043
52440
  // src/commands/save.ts
51044
- var import_node_fs55 = require("fs");
52441
+ var import_node_fs61 = require("fs");
51045
52442
  var import_toml5 = __toESM(require_toml());
51046
52443
  init_cli_config();
51047
52444
  init_paths();
@@ -51080,9 +52477,9 @@ async function saveCommand(opts = {}) {
51080
52477
  }
51081
52478
  const path2 = opts.config ?? PATHS.configFile;
51082
52479
  let config = {};
51083
- if ((0, import_node_fs55.existsSync)(path2)) {
52480
+ if ((0, import_node_fs61.existsSync)(path2)) {
51084
52481
  try {
51085
- config = import_toml5.default.parse((0, import_node_fs55.readFileSync)(path2, "utf-8"));
52482
+ config = import_toml5.default.parse((0, import_node_fs61.readFileSync)(path2, "utf-8"));
51086
52483
  } catch (err) {
51087
52484
  console.log(source_default.red(` \u2717 ${path2} is not valid TOML: ${err.message}
51088
52485
  `));
@@ -51195,17 +52592,17 @@ function welcomeCommand() {
51195
52592
  }
51196
52593
 
51197
52594
  // src/commands/properties.ts
51198
- var import_node_fs56 = require("fs");
51199
- var import_node_path42 = require("path");
52595
+ var import_node_fs62 = require("fs");
52596
+ var import_node_path48 = require("path");
51200
52597
  var import_node_readline4 = __toESM(require("readline"));
51201
52598
  init_cli_config();
51202
52599
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
51203
52600
  var KINDS = ["url", "api", "domain", "ip", "repo"];
51204
52601
  function prompt(question) {
51205
52602
  const rl = import_node_readline4.default.createInterface({ input: process.stdin, output: process.stdout });
51206
- return new Promise((resolve8) => rl.question(question, (answer) => {
52603
+ return new Promise((resolve9) => rl.question(question, (answer) => {
51207
52604
  rl.close();
51208
- resolve8(answer.trim());
52605
+ resolve9(answer.trim());
51209
52606
  }));
51210
52607
  }
51211
52608
  async function requireAuth() {
@@ -51509,12 +52906,12 @@ async function propertiesRunsCommand(opts) {
51509
52906
  const runs = data.runs || [];
51510
52907
  if (runs.length === 0) continue;
51511
52908
  console.log(` ${source_default.white.bold(prop.name)} ${KIND_COLOR[prop.kind](`[${prop.kind}]`)}`);
51512
- for (const run of runs) {
51513
- const statusColor = run.status === "succeeded" ? source_default.green : run.status === "failed" ? source_default.red : run.status === "running" ? source_default.yellow : run.status === "cancelled" ? source_default.gray : source_default.cyan;
51514
- const when = (run.completed_at || run.started_at || run.queued_at).slice(0, 19).replace("T", " ");
51515
- const sev = run.severity_summary;
52909
+ for (const run2 of runs) {
52910
+ 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;
52911
+ const when = (run2.completed_at || run2.started_at || run2.queued_at).slice(0, 19).replace("T", " ");
52912
+ const sev = run2.severity_summary;
51516
52913
  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]");
51517
- console.log(` ${source_default.gray(when)} ${statusColor(run.status.padEnd(10))} ${source_default.dim(run.type.padEnd(8))} ${sevStr} ${source_default.gray(run.summary || "")}`);
52914
+ console.log(` ${source_default.gray(when)} ${statusColor(run2.status.padEnd(10))} ${source_default.dim(run2.type.padEnd(8))} ${sevStr} ${source_default.gray(run2.summary || "")}`);
51518
52915
  total++;
51519
52916
  }
51520
52917
  console.log();
@@ -51526,8 +52923,8 @@ async function propertiesRunsCommand(opts) {
51526
52923
  }
51527
52924
  }
51528
52925
  function parseImportFile(path2) {
51529
- const ext = (0, import_node_path42.extname)(path2).toLowerCase();
51530
- const raw = (0, import_node_fs56.readFileSync)(path2, "utf-8");
52926
+ const ext = (0, import_node_path48.extname)(path2).toLowerCase();
52927
+ const raw = (0, import_node_fs62.readFileSync)(path2, "utf-8");
51531
52928
  if (ext === ".json") {
51532
52929
  const parsed = JSON.parse(raw);
51533
52930
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -51722,13 +53119,13 @@ async function rulesCommand(opts) {
51722
53119
  }
51723
53120
 
51724
53121
  // src/commands/harden.ts
51725
- var import_node_fs58 = require("fs");
51726
- var import_node_child_process22 = require("child_process");
53122
+ var import_node_fs64 = require("fs");
53123
+ var import_node_child_process23 = require("child_process");
51727
53124
  init_cli_config();
51728
53125
 
51729
53126
  // src/commands/cis-report.ts
51730
- var import_node_os16 = require("os");
51731
- var import_node_fs57 = require("fs");
53127
+ var import_node_os20 = require("os");
53128
+ var import_node_fs63 = require("fs");
51732
53129
  var CIS_UBUNTU_URL = "https://www.cisecurity.org/benchmark/ubuntu_linux";
51733
53130
  var CIS_DEBIAN_URL = "https://www.cisecurity.org/benchmark/debian_linux";
51734
53131
  var UBUNTU_2404_CIS_CONTROL_SOURCE = "https://github.com/ComplianceAsCode/content/blob/v0.1.78/controls/cis_ubuntu2404.yml";
@@ -51748,7 +53145,7 @@ var EDITIONS = {
51748
53145
  function osRelease() {
51749
53146
  let raw = "";
51750
53147
  try {
51751
- raw = (0, import_node_fs57.readFileSync)("/etc/os-release", "utf8");
53148
+ raw = (0, import_node_fs63.readFileSync)("/etc/os-release", "utf8");
51752
53149
  } catch {
51753
53150
  return {};
51754
53151
  }
@@ -51821,7 +53218,7 @@ function buildCisEvidenceReport(findings2, score, now = /* @__PURE__ */ new Date
51821
53218
  schema_version: 1,
51822
53219
  generated_at: now.toISOString(),
51823
53220
  benchmark_catalog_checked_at: "2026-11-01",
51824
- host: { hostname: (0, import_node_os16.hostname)(), os_id: id, os_version: version, pretty_name: os4.PRETTY_NAME ?? null },
53221
+ host: { hostname: (0, import_node_os20.hostname)(), os_id: id, os_version: version, pretty_name: os4.PRETTY_NAME ?? null },
51825
53222
  benchmark: edition ? { name: edition.name, version: edition.version, source: edition.source } : null,
51826
53223
  assessment: "partial",
51827
53224
  mapped_controls: mappedControls.size,
@@ -51928,20 +53325,20 @@ function writeCisReport(path2, format2, report) {
51928
53325
  const markdown = renderCisMarkdown(report);
51929
53326
  const content = format2 === "json" ? `${JSON.stringify(report, null, 2)}
51930
53327
  ` : format2 === "pdf" ? renderCisPdf(markdown) : markdown;
51931
- (0, import_node_fs57.writeFileSync)(path2, content);
53328
+ (0, import_node_fs63.writeFileSync)(path2, content);
51932
53329
  }
51933
53330
 
51934
53331
  // src/commands/harden.ts
51935
53332
  function tryExec(cmd) {
51936
53333
  try {
51937
- return (0, import_node_child_process22.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
53334
+ return (0, import_node_child_process23.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
51938
53335
  } catch {
51939
53336
  return null;
51940
53337
  }
51941
53338
  }
51942
53339
  function tryRead(path2) {
51943
53340
  try {
51944
- return (0, import_node_fs58.readFileSync)(path2, "utf-8");
53341
+ return (0, import_node_fs64.readFileSync)(path2, "utf-8");
51945
53342
  } catch {
51946
53343
  return null;
51947
53344
  }
@@ -52055,8 +53452,8 @@ function checkSshWeakConfig() {
52055
53452
  };
52056
53453
  }
52057
53454
  function checkAutoUpdates() {
52058
- const unattended = (0, import_node_fs58.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs58.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
52059
- const dnfAuto = (0, import_node_fs58.existsSync)("/etc/dnf/automatic.conf");
53455
+ const unattended = (0, import_node_fs64.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs64.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
53456
+ const dnfAuto = (0, import_node_fs64.existsSync)("/etc/dnf/automatic.conf");
52060
53457
  if (unattended || dnfAuto) {
52061
53458
  return {
52062
53459
  key: "auto-updates",
@@ -52182,7 +53579,7 @@ function checkFail2ban() {
52182
53579
  explanation: "fail2ban is installed and running."
52183
53580
  };
52184
53581
  }
52185
- if ((0, import_node_fs58.existsSync)("/etc/fail2ban/fail2ban.conf")) {
53582
+ if ((0, import_node_fs64.existsSync)("/etc/fail2ban/fail2ban.conf")) {
52186
53583
  return {
52187
53584
  key: checkKey,
52188
53585
  status: "warn",
@@ -52402,9 +53799,9 @@ async function hardenCommand(opts) {
52402
53799
  }
52403
53800
 
52404
53801
  // src/core/patches/index.ts
52405
- var import_node_fs59 = require("fs");
52406
- var import_node_path43 = require("path");
52407
- var import_node_child_process23 = require("child_process");
53802
+ var import_node_fs65 = require("fs");
53803
+ var import_node_path49 = require("path");
53804
+ var import_node_child_process24 = require("child_process");
52408
53805
  var import_node_util5 = require("util");
52409
53806
 
52410
53807
  // src/core/patches/dpkg-version.ts
@@ -52464,7 +53861,7 @@ var STALE_AFTER_MS = 2 * 864e5;
52464
53861
  var SEVERITIES2 = ["info", "low", "medium", "high", "critical"];
52465
53862
  var RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
52466
53863
  var defaultExec = async (file, args) => {
52467
- const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process23.execFile)(file, args, {
53864
+ const { stdout } = await (0, import_node_util5.promisify)(import_node_child_process24.execFile)(file, args, {
52468
53865
  timeout: 12e4,
52469
53866
  maxBuffer: 32 * 1024 * 1024,
52470
53867
  env: { ...process.env, LC_ALL: "C" }
@@ -52563,9 +53960,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
52563
53960
  function newestReleaseMtime(dir) {
52564
53961
  try {
52565
53962
  let newest = 0;
52566
- for (const name of (0, import_node_fs59.readdirSync)(dir)) {
53963
+ for (const name of (0, import_node_fs65.readdirSync)(dir)) {
52567
53964
  if (!/Release$/.test(name)) continue;
52568
- newest = Math.max(newest, (0, import_node_fs59.statSync)((0, import_node_path43.join)(dir, name)).mtimeMs);
53965
+ newest = Math.max(newest, (0, import_node_fs65.statSync)((0, import_node_path49.join)(dir, name)).mtimeMs);
52569
53966
  }
52570
53967
  return newest > 0 ? new Date(newest) : null;
52571
53968
  } catch {
@@ -52582,7 +53979,7 @@ async function checkPatches(opts = {}) {
52582
53979
  let osText = opts.osRelease;
52583
53980
  if (osText === void 0) {
52584
53981
  try {
52585
- osText = (0, import_node_fs59.readFileSync)("/etc/os-release", "utf-8");
53982
+ osText = (0, import_node_fs65.readFileSync)("/etc/os-release", "utf-8");
52586
53983
  } catch {
52587
53984
  osText = "";
52588
53985
  }
@@ -52809,26 +54206,26 @@ async function patchesCommand(opts) {
52809
54206
 
52810
54207
  // src/commands/feeds.ts
52811
54208
  var import_node_net18 = require("net");
52812
- var import_node_path45 = require("path");
54209
+ var import_node_path51 = require("path");
52813
54210
  init_paths();
52814
54211
 
52815
54212
  // src/commands/feeds-resolver.ts
52816
- var import_node_child_process24 = require("child_process");
52817
- var import_node_fs60 = require("fs");
52818
- var import_node_path44 = require("path");
54213
+ var import_node_child_process25 = require("child_process");
54214
+ var import_node_fs66 = require("fs");
54215
+ var import_node_path50 = require("path");
52819
54216
  var realIO = {
52820
- exists: (p) => (0, import_node_fs60.existsSync)(p),
54217
+ exists: (p) => (0, import_node_fs66.existsSync)(p),
52821
54218
  read: (p) => {
52822
54219
  try {
52823
- return (0, import_node_fs60.readFileSync)(p, "utf-8");
54220
+ return (0, import_node_fs66.readFileSync)(p, "utf-8");
52824
54221
  } catch {
52825
54222
  return null;
52826
54223
  }
52827
54224
  },
52828
- write: (p, c) => (0, import_node_fs60.writeFileSync)(p, c),
52829
- remove: (p) => (0, import_node_fs60.rmSync)(p, { force: true }),
54225
+ write: (p, c) => (0, import_node_fs66.writeFileSync)(p, c),
54226
+ remove: (p) => (0, import_node_fs66.rmSync)(p, { force: true }),
52830
54227
  run: (cmd, args) => {
52831
- const r = (0, import_node_child_process24.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
54228
+ const r = (0, import_node_child_process25.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
52832
54229
  return { code: r.status ?? 1, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
52833
54230
  }
52834
54231
  };
@@ -52836,17 +54233,17 @@ var APPARMOR_LOCAL = "/etc/apparmor.d/local/usr.sbin.unbound";
52836
54233
  var APPARMOR_PROFILE = "/etc/apparmor.d/usr.sbin.unbound";
52837
54234
  function hookContent(resolver, stateDir) {
52838
54235
  const head = "# Installed by `threatcrush feeds resolver install`; `threatcrush feeds resolver remove` takes it out.\n";
52839
- return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path44.join)(stateDir, RESOLVER_FILES.hosts)}
52840
- ` : `${head}include: "${(0, import_node_path44.join)(stateDir, RESOLVER_FILES.unbound)}"
54236
+ return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path50.join)(stateDir, RESOLVER_FILES.hosts)}
54237
+ ` : `${head}include: "${(0, import_node_path50.join)(stateDir, RESOLVER_FILES.unbound)}"
52841
54238
  `;
52842
54239
  }
52843
54240
  function apparmorRule(stateDir) {
52844
- return ` ${(0, import_node_path44.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
54241
+ return ` ${(0, import_node_path50.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
52845
54242
  }
52846
54243
  function detectResolvers(io = realIO) {
52847
54244
  const found = [];
52848
- if (io.exists((0, import_node_path44.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
52849
- if (io.exists((0, import_node_path44.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
54245
+ if (io.exists((0, import_node_path50.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
54246
+ if (io.exists((0, import_node_path50.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
52850
54247
  return found;
52851
54248
  }
52852
54249
  function check(resolver, io) {
@@ -52859,7 +54256,7 @@ function restartIfActive(resolver, io) {
52859
54256
  }
52860
54257
  function installHook(resolver, stateDir, io = realIO) {
52861
54258
  const hook = RESOLVER_HOOKS[resolver];
52862
- const file = (0, import_node_path44.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
54259
+ const file = (0, import_node_path50.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
52863
54260
  if (!io.exists(file)) io.write(file, resolver === "dnsmasq" ? hostsBlocklist([]) : unboundBlocklist([]));
52864
54261
  io.write(hook, hookContent(resolver, stateDir));
52865
54262
  if (resolver === "unbound" && io.exists(APPARMOR_LOCAL)) {
@@ -52920,8 +54317,8 @@ function resolverCommand(sub, stateDir, io = realIO) {
52920
54317
  }
52921
54318
  return failed ? 1 : 0;
52922
54319
  }
52923
- const hosts = io.read((0, import_node_path44.join)(stateDir, RESOLVER_FILES.hosts));
52924
- const unbound = io.read((0, import_node_path44.join)(stateDir, RESOLVER_FILES.unbound));
54320
+ const hosts = io.read((0, import_node_path50.join)(stateDir, RESOLVER_FILES.hosts));
54321
+ const unbound = io.read((0, import_node_path50.join)(stateDir, RESOLVER_FILES.unbound));
52925
54322
  console.log(` resolvers here: ${found.join(", ") || "none that can block (systemd-resolved only?)"}`);
52926
54323
  for (const r of ["dnsmasq", "unbound"]) {
52927
54324
  console.log(` ${r.padEnd(8)} hook ${io.exists(RESOLVER_HOOKS[r]) ? source_default.green("installed") : source_default.gray("not installed")}`);
@@ -52933,11 +54330,11 @@ function resolverCommand(sub, stateDir, io = realIO) {
52933
54330
  // src/commands/feeds.ts
52934
54331
  async function loadSet() {
52935
54332
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
52936
- const path2 = (0, import_node_path45.join)(dir, "threat-feeds.json");
54333
+ const path2 = (0, import_node_path51.join)(dir, "threat-feeds.json");
52937
54334
  const set = readFeedCache(path2);
52938
54335
  if (set) return { set, from: path2 };
52939
54336
  }
52940
- const settings = threatFeedSettings(loadConfig((0, import_node_path45.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
54337
+ const settings = threatFeedSettings(loadConfig((0, import_node_path51.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
52941
54338
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
52942
54339
  }
52943
54340
  async function feedsCommand(action, value, opts) {
@@ -52981,21 +54378,21 @@ async function feedsCommand(action, value, opts) {
52981
54378
  }
52982
54379
 
52983
54380
  // src/commands/tor.ts
52984
- var import_node_fs61 = require("fs");
54381
+ var import_node_fs67 = require("fs");
52985
54382
  var import_node_net19 = require("net");
52986
- var import_node_path46 = require("path");
54383
+ var import_node_path52 = require("path");
52987
54384
  init_paths();
52988
54385
  async function torCommand(action, value, opts) {
52989
54386
  let exits = /* @__PURE__ */ new Set();
52990
54387
  let from = "";
52991
54388
  let updated = null;
52992
54389
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
52993
- const path2 = (0, import_node_path46.join)(dir, "tor-exits.txt");
54390
+ const path2 = (0, import_node_path52.join)(dir, "tor-exits.txt");
52994
54391
  try {
52995
- if (!(0, import_node_fs61.existsSync)(path2)) continue;
52996
- exits = parseTorExitList((0, import_node_fs61.readFileSync)(path2, "utf-8"));
54392
+ if (!(0, import_node_fs67.existsSync)(path2)) continue;
54393
+ exits = parseTorExitList((0, import_node_fs67.readFileSync)(path2, "utf-8"));
52997
54394
  from = path2;
52998
- updated = (0, import_node_fs61.statSync)(path2).mtime;
54395
+ updated = (0, import_node_fs67.statSync)(path2).mtime;
52999
54396
  break;
53000
54397
  } catch {
53001
54398
  }
@@ -53011,7 +54408,7 @@ async function torCommand(action, value, opts) {
53011
54408
  } catch {
53012
54409
  }
53013
54410
  }
53014
- const remediation = loadConfig((0, import_node_path46.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).remediation;
54411
+ const remediation = loadConfig((0, import_node_path52.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).remediation;
53015
54412
  const ban = remediation?.block_tor_ssh !== false && remediation?.enabled !== false;
53016
54413
  if (action === "check") {
53017
54414
  if (!value || !(0, import_node_net19.isIP)(value)) {
@@ -53042,14 +54439,14 @@ async function torCommand(action, value, opts) {
53042
54439
  }
53043
54440
 
53044
54441
  // src/commands/reputation.ts
53045
- var import_node_os17 = require("os");
53046
- var import_node_fs62 = require("fs");
53047
- var import_node_path47 = require("path");
54442
+ var import_node_os21 = require("os");
54443
+ var import_node_fs68 = require("fs");
54444
+ var import_node_path53 = require("path");
53048
54445
  var API_URL7 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
53049
- var CONFIG_PATH4 = (0, import_node_path47.join)((0, import_node_os17.homedir)(), ".threatcrush", "config.json");
54446
+ var CONFIG_PATH4 = (0, import_node_path53.join)((0, import_node_os21.homedir)(), ".threatcrush", "config.json");
53050
54447
  function readConfig3() {
53051
54448
  try {
53052
- return JSON.parse((0, import_node_fs62.readFileSync)(CONFIG_PATH4, "utf-8"));
54449
+ return JSON.parse((0, import_node_fs68.readFileSync)(CONFIG_PATH4, "utf-8"));
53053
54450
  } catch {
53054
54451
  return {};
53055
54452
  }
@@ -53237,7 +54634,7 @@ async function reputationSubscribeCommand(opts) {
53237
54634
  }
53238
54635
 
53239
54636
  // src/commands/privileged.ts
53240
- var import_node_fs63 = require("fs");
54637
+ var import_node_fs69 = require("fs");
53241
54638
  init_paths();
53242
54639
  var SEV2 = {
53243
54640
  critical: source_default.red.bold,
@@ -53250,19 +54647,19 @@ async function privilegedCommand(opts) {
53250
54647
  const snapshot = takeSnapshot({
53251
54648
  readFile: (p) => {
53252
54649
  try {
53253
- return (0, import_node_fs63.readFileSync)(p, "utf-8");
54650
+ return (0, import_node_fs69.readFileSync)(p, "utf-8");
53254
54651
  } catch {
53255
54652
  return null;
53256
54653
  }
53257
54654
  },
53258
54655
  readDir: (p) => {
53259
54656
  try {
53260
- return (0, import_node_fs63.readdirSync)(p);
54657
+ return (0, import_node_fs69.readdirSync)(p);
53261
54658
  } catch {
53262
54659
  return null;
53263
54660
  }
53264
54661
  },
53265
- exists: (p) => (0, import_node_fs63.existsSync)(p)
54662
+ exists: (p) => (0, import_node_fs69.existsSync)(p)
53266
54663
  });
53267
54664
  let events = [];
53268
54665
  let ledgerNote = "";
@@ -53304,12 +54701,12 @@ async function privilegedCommand(opts) {
53304
54701
  }
53305
54702
 
53306
54703
  // src/commands/integrity.ts
53307
- var import_node_fs64 = require("fs");
53308
- var import_node_path48 = require("path");
54704
+ var import_node_fs70 = require("fs");
54705
+ var import_node_path54 = require("path");
53309
54706
  init_paths();
53310
54707
  function readState2(path2) {
53311
54708
  try {
53312
- return JSON.parse((0, import_node_fs64.readFileSync)(path2, "utf8"));
54709
+ return JSON.parse((0, import_node_fs70.readFileSync)(path2, "utf8"));
53313
54710
  } catch {
53314
54711
  return null;
53315
54712
  }
@@ -53329,13 +54726,13 @@ function changedCount(baseline, observed) {
53329
54726
  async function integrityCommand(action = "status", opts = {}) {
53330
54727
  const config = loadConfig();
53331
54728
  const settings = fileIntegritySettings(config.file_integrity);
53332
- const systemBaseline = (0, import_node_path48.join)(SYSTEM_PATHS.stateDir, "file-integrity-baseline.json");
53333
- const useSystemState = PATHS.mode === "system" || systemDaemonPresent() || (0, import_node_fs64.existsSync)(systemBaseline);
54729
+ const systemBaseline = (0, import_node_path54.join)(SYSTEM_PATHS.stateDir, "file-integrity-baseline.json");
54730
+ const useSystemState = PATHS.mode === "system" || systemDaemonPresent() || (0, import_node_fs70.existsSync)(systemBaseline);
53334
54731
  const stateDir = useSystemState ? SYSTEM_PATHS.stateDir : PATHS.stateDir;
53335
- const baselinePath = (0, import_node_path48.join)(stateDir, "file-integrity-baseline.json");
53336
- const observedPath = (0, import_node_path48.join)(stateDir, "file-integrity-observed.json");
54732
+ const baselinePath = (0, import_node_path54.join)(stateDir, "file-integrity-baseline.json");
54733
+ const observedPath = (0, import_node_path54.join)(stateDir, "file-integrity-observed.json");
53337
54734
  if (action === "rebaseline") {
53338
- const watch3 = new FileIntegrityWatch({
54735
+ const watch4 = new FileIntegrityWatch({
53339
54736
  bus: { publish: () => void 0 },
53340
54737
  settings,
53341
54738
  baselinePath,
@@ -53346,7 +54743,7 @@ async function integrityCommand(action = "status", opts = {}) {
53346
54743
  });
53347
54744
  let result;
53348
54745
  try {
53349
- result = await watch3.rebaseline();
54746
+ result = await watch4.rebaseline();
53350
54747
  } catch (error2) {
53351
54748
  result = { ok: false, files: 0, reason: error2.message };
53352
54749
  }
@@ -53401,13 +54798,13 @@ async function integrityCommand(action = "status", opts = {}) {
53401
54798
  }
53402
54799
 
53403
54800
  // src/commands/edr.ts
53404
- var import_node_fs66 = require("fs");
54801
+ var import_node_fs72 = require("fs");
53405
54802
  init_paths();
53406
54803
 
53407
54804
  // src/daemon/auditd/rules.ts
53408
- var import_node_fs65 = require("fs");
53409
- var import_node_child_process25 = require("child_process");
53410
- var import_node_path49 = require("path");
54805
+ var import_node_fs71 = require("fs");
54806
+ var import_node_child_process26 = require("child_process");
54807
+ var import_node_path55 = require("path");
53411
54808
  var WEB_TOOLS = ["sh", "bash", "dash", "zsh", "curl", "wget"];
53412
54809
  var MINER_NAMES = ["xmrig", "minerd", "cpuminer", "cpuminer-multi", "kdevtmpfsi", "kinsing", "cryptonight"];
53413
54810
  var CONNECT_KEY2 = "threatcrush_edr_connect";
@@ -53415,10 +54812,10 @@ var LISTEN_KEY2 = "threatcrush_edr_listen";
53415
54812
  function passwdByName() {
53416
54813
  let raw = "";
53417
54814
  try {
53418
- raw = (0, import_node_child_process25.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
54815
+ raw = (0, import_node_child_process26.execFileSync)("getent", ["passwd"], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] });
53419
54816
  } catch {
53420
54817
  try {
53421
- raw = (0, import_node_fs65.readFileSync)("/etc/passwd", "utf8");
54818
+ raw = (0, import_node_fs71.readFileSync)("/etc/passwd", "utf8");
53422
54819
  } catch {
53423
54820
  return /* @__PURE__ */ new Map();
53424
54821
  }
@@ -53437,8 +54834,8 @@ function existingExecutables(names) {
53437
54834
  for (const prefix of ["/bin", "/usr/bin", "/usr/local/bin"]) {
53438
54835
  const candidate = `${prefix}/${name}`;
53439
54836
  try {
53440
- if (!(0, import_node_fs65.existsSync)(candidate) || !(0, import_node_fs65.statSync)(candidate).isFile()) continue;
53441
- paths.add((0, import_node_fs65.realpathSync)(candidate));
54837
+ if (!(0, import_node_fs71.existsSync)(candidate) || !(0, import_node_fs71.statSync)(candidate).isFile()) continue;
54838
+ paths.add((0, import_node_fs71.realpathSync)(candidate));
53442
54839
  } catch {
53443
54840
  }
53444
54841
  }
@@ -53447,9 +54844,9 @@ function existingExecutables(names) {
53447
54844
  }
53448
54845
  function existingDirectories(paths) {
53449
54846
  return [...new Set(paths)].filter((path2) => {
53450
- if (!(0, import_node_path49.isAbsolute)(path2) || /[\s\r\n]/.test(path2)) return false;
54847
+ if (!(0, import_node_path55.isAbsolute)(path2) || /[\s\r\n]/.test(path2)) return false;
53451
54848
  try {
53452
- return (0, import_node_fs65.statSync)(path2).isDirectory();
54849
+ return (0, import_node_fs71.statSync)(path2).isDirectory();
53453
54850
  } catch {
53454
54851
  return false;
53455
54852
  }
@@ -53510,8 +54907,8 @@ async function edrCommand(action = "status", opts = {}) {
53510
54907
  }
53511
54908
  let readable = false;
53512
54909
  try {
53513
- if ((0, import_node_fs66.existsSync)(settings.auditLogPath)) (0, import_node_fs66.accessSync)(settings.auditLogPath, import_node_fs66.constants.R_OK);
53514
- readable = (0, import_node_fs66.existsSync)(settings.auditLogPath);
54910
+ if ((0, import_node_fs72.existsSync)(settings.auditLogPath)) (0, import_node_fs72.accessSync)(settings.auditLogPath, import_node_fs72.constants.R_OK);
54911
+ readable = (0, import_node_fs72.existsSync)(settings.auditLogPath);
53515
54912
  } catch {
53516
54913
  }
53517
54914
  let events = [];
@@ -53697,7 +55094,7 @@ async function allowlistCommand(opts) {
53697
55094
  }
53698
55095
 
53699
55096
  // src/commands/abuse.ts
53700
- var import_node_fs67 = require("fs");
55097
+ var import_node_fs73 = require("fs");
53701
55098
  init_paths();
53702
55099
  function rows(records) {
53703
55100
  if (records.length === 0) {
@@ -53757,7 +55154,7 @@ function abuseRetractCommand(id, opts = {}) {
53757
55154
  );
53758
55155
  }
53759
55156
  function abuseStatusCommand(opts = {}) {
53760
- const config = loadConfig((0, import_node_fs67.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
55157
+ const config = loadConfig((0, import_node_fs73.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
53761
55158
  const cfg = resolveConfig(config.abuse_reporter);
53762
55159
  const hasKey2 = Boolean(cfg.keys.abuseipdb || cfg.keys.stopforumspam);
53763
55160
  const active2 = cfg.enabled && (cfg.dryRun || hasKey2);
@@ -53780,11 +55177,11 @@ function abuseStatusCommand(opts = {}) {
53780
55177
  init_paths();
53781
55178
 
53782
55179
  // src/upgrade.ts
53783
- var import_node_child_process26 = require("child_process");
55180
+ var import_node_child_process27 = require("child_process");
53784
55181
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
53785
55182
  var defaultRunner = (cmd) => {
53786
55183
  try {
53787
- return (0, import_node_child_process26.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
55184
+ return (0, import_node_child_process27.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
53788
55185
  } catch {
53789
55186
  return null;
53790
55187
  }
@@ -53817,9 +55214,9 @@ function globalListCommand(pm, pkgName) {
53817
55214
  };
53818
55215
  return lists[pm] ?? lists.npm;
53819
55216
  }
53820
- function globalHolders(pkgName, run = defaultRunner) {
55217
+ function globalHolders(pkgName, run2 = defaultRunner) {
53821
55218
  return PACKAGE_MANAGERS.filter((pm) => {
53822
- const out = run(globalListCommand(pm, pkgName));
55219
+ const out = run2(globalListCommand(pm, pkgName));
53823
55220
  return typeof out === "string" && out.includes(pkgName);
53824
55221
  });
53825
55222
  }
@@ -53828,11 +55225,11 @@ function parseVersionOutput(output) {
53828
55225
  const match = output.match(/\d+\.\d+\.\d+[^\s]*/);
53829
55226
  return match ? match[0] : null;
53830
55227
  }
53831
- function activeCliVersion(bin = "threatcrush", run = defaultRunner) {
53832
- return parseVersionOutput(run(`${bin} --version`));
55228
+ function activeCliVersion(bin = "threatcrush", run2 = defaultRunner) {
55229
+ return parseVersionOutput(run2(`${bin} --version`));
53833
55230
  }
53834
- function activeCliPath(bin = "threatcrush", run = defaultRunner) {
53835
- const out = run(`command -v ${bin}`);
55231
+ function activeCliPath(bin = "threatcrush", run2 = defaultRunner) {
55232
+ const out = run2(`command -v ${bin}`);
53836
55233
  return out ? out.trim().split("\n")[0] || null : null;
53837
55234
  }
53838
55235
  async function latestPublishedVersion(pkgName, timeoutMs = 8e3) {
@@ -53925,9 +55322,9 @@ function installUserAgent(target = globalThis) {
53925
55322
  }
53926
55323
 
53927
55324
  // src/core/cloud-upload.ts
53928
- var import_node_child_process27 = require("child_process");
53929
- var import_node_os18 = require("os");
53930
- var import_node_path50 = require("path");
55325
+ var import_node_child_process28 = require("child_process");
55326
+ var import_node_os22 = require("os");
55327
+ var import_node_path56 = require("path");
53931
55328
  init_cli_config();
53932
55329
  function uploadDisabled(upload, env3 = process.env) {
53933
55330
  if (upload === false) return true;
@@ -53946,23 +55343,23 @@ function cleanUrl(raw) {
53946
55343
  return raw.split(/[?#]/)[0];
53947
55344
  }
53948
55345
  }
53949
- function repoTarget(path2, run = (args) => (0, import_node_child_process27.execFileSync)("git", args, { cwd: (0, import_node_path50.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
53950
- const abs = (0, import_node_path50.resolve)(path2);
55346
+ function repoTarget(path2, run2 = (args) => (0, import_node_child_process28.execFileSync)("git", args, { cwd: (0, import_node_path56.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
55347
+ const abs = (0, import_node_path56.resolve)(path2);
53951
55348
  try {
53952
- const root = run(["rev-parse", "--show-toplevel"]);
55349
+ const root = run2(["rev-parse", "--show-toplevel"]);
53953
55350
  const sub = abs === root ? "." : abs.slice(root.length + 1);
53954
55351
  let remote = "";
53955
55352
  try {
53956
- remote = run(["remote", "get-url", "origin"]);
55353
+ remote = run2(["remote", "get-url", "origin"]);
53957
55354
  } catch {
53958
55355
  }
53959
55356
  if (remote) {
53960
55357
  const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)[:/](.+?)(?:\.git)?\/?$/i.exec(remote);
53961
55358
  if (m) return { target: `${m[1]}/${m[2]}`, root, sub };
53962
55359
  }
53963
- return { target: `${(0, import_node_os18.hostname)()}:${root}`, root, sub };
55360
+ return { target: `${(0, import_node_os22.hostname)()}:${root}`, root, sub };
53964
55361
  } catch {
53965
- return { target: `${(0, import_node_os18.hostname)()}:${abs}`, root: abs, sub: "." };
55362
+ return { target: `${(0, import_node_os22.hostname)()}:${abs}`, root: abs, sub: "." };
53966
55363
  }
53967
55364
  }
53968
55365
  async function uploadResult(result, opts) {
@@ -54319,25 +55716,25 @@ ${source_default.dim(" C R U S H")}
54319
55716
  var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
54320
55717
  var PKG_NAME2 = "@profullstack/threatcrush";
54321
55718
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
54322
- var INSTALL_CONFIG_PATH = (0, import_node_path51.join)((0, import_node_os19.homedir)(), ".threatcrush", "install.json");
55719
+ var INSTALL_CONFIG_PATH = (0, import_node_path57.join)((0, import_node_os23.homedir)(), ".threatcrush", "install.json");
54323
55720
  function detectPackageManager() {
54324
55721
  try {
54325
- const npmGlobal = (0, import_node_child_process28.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
55722
+ const npmGlobal = (0, import_node_child_process29.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
54326
55723
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
54327
55724
  } catch {
54328
55725
  }
54329
55726
  try {
54330
- (0, import_node_child_process28.execSync)("pnpm --version", { stdio: "pipe" });
55727
+ (0, import_node_child_process29.execSync)("pnpm --version", { stdio: "pipe" });
54331
55728
  return "pnpm";
54332
55729
  } catch {
54333
55730
  }
54334
55731
  try {
54335
- (0, import_node_child_process28.execSync)("yarn --version", { stdio: "pipe" });
55732
+ (0, import_node_child_process29.execSync)("yarn --version", { stdio: "pipe" });
54336
55733
  return "yarn";
54337
55734
  } catch {
54338
55735
  }
54339
55736
  try {
54340
- (0, import_node_child_process28.execSync)("bun --version", { stdio: "pipe" });
55737
+ (0, import_node_child_process29.execSync)("bun --version", { stdio: "pipe" });
54341
55738
  return "bun";
54342
55739
  } catch {
54343
55740
  }
@@ -54345,14 +55742,14 @@ function detectPackageManager() {
54345
55742
  }
54346
55743
  function readInstallConfig() {
54347
55744
  try {
54348
- return JSON.parse((0, import_node_fs68.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
55745
+ return JSON.parse((0, import_node_fs74.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
54349
55746
  } catch {
54350
55747
  return {};
54351
55748
  }
54352
55749
  }
54353
55750
  function packageLooksInstalled(pm, pkgName) {
54354
55751
  try {
54355
- const output = (0, import_node_child_process28.execSync)(globalListCommand(pm, pkgName), {
55752
+ const output = (0, import_node_child_process29.execSync)(globalListCommand(pm, pkgName), {
54356
55753
  encoding: "utf-8",
54357
55754
  stdio: ["pipe", "pipe", "pipe"]
54358
55755
  });
@@ -54455,14 +55852,14 @@ async function promoteUnprivilegedDaemon() {
54455
55852
  function restartSystemdDaemon() {
54456
55853
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
54457
55854
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
54458
- if (!asRoot && (0, import_node_child_process28.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
55855
+ if (!asRoot && (0, import_node_child_process29.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
54459
55856
  const [cmd, ...args] = argv;
54460
- if ((0, import_node_child_process28.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
54461
- return (0, import_node_child_process28.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
55857
+ if ((0, import_node_child_process29.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
55858
+ return (0, import_node_child_process29.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
54462
55859
  }
54463
55860
  function execQuiet(cmd) {
54464
55861
  try {
54465
- return (0, import_node_child_process28.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
55862
+ return (0, import_node_child_process29.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
54466
55863
  } catch {
54467
55864
  return null;
54468
55865
  }
@@ -54623,6 +56020,14 @@ program2.command("scan").description("Scan codebase for vulnerabilities and secr
54623
56020
  await uploadResult(result, { source: "scan", target: repo.target, kind: "repo", scope, upload: opts.upload, machineReadable: format2 !== "text" });
54624
56021
  }
54625
56022
  });
56023
+ var av = program2.command("av").alias("antivirus").description("CrushAV: free open-source antivirus (heuristics + ClamAV + hash reputation), Windows/macOS/Linux");
56024
+ 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("--json", "emit JSON").action(async (paths, opts) => {
56025
+ await avScanCommand(paths, opts);
56026
+ });
56027
+ av.command("watch").description("Real-time protection: scan new and changed files as they land (default: downloads, desktop, temp, startup)").argument("[paths...]", "folders to watch instead of the defaults").option("--quarantine", "quarantine malware the moment it is detected").option("--offline", "do not send file hashes to threatcrush.com").option("--json", "one JSON line per scanned file").action(async (paths, opts) => avWatchCommand(paths, opts));
56028
+ av.command("status").description("Show engines (ClamAV version, rule count), reputation endpoint and quarantine").option("--json", "emit JSON").action(async (opts) => avStatusCommand(opts));
56029
+ av.command("quarantine [action] [id]").description("list | add <file> | restore <id> | delete <id>").option("--to <path>", "restore to this path instead of the original location").option("--json", "emit JSON").action(async (action, id, opts) => avQuarantineCommand(action, id, opts));
56030
+ av.command("test").description("Check the scanner works using the harmless EICAR test file (in memory, nothing written)").action(async () => avTestCommand());
54626
56031
  program2.command("pentest").description("Penetration test URLs and APIs").argument("<url>", "Target URL to pentest").option("--no-upload", "do not save the results to your threatcrush.com org (also THREATCRUSH_UPLOAD=0)").action(async (url, opts) => {
54627
56032
  const result = await pentestCommand(url);
54628
56033
  await uploadResult(result, { source: "pentest", target: cleanUrl(url), kind: "url", upload: opts.upload });
@@ -54768,7 +56173,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
54768
56173
  program2.command("logs").description("Tail daemon logs").action(async () => {
54769
56174
  console.log(LOGO2);
54770
56175
  const logPath2 = PATHS.logFile;
54771
- if (!(0, import_node_fs68.existsSync)(logPath2)) {
56176
+ if (!(0, import_node_fs74.existsSync)(logPath2)) {
54772
56177
  console.log(source_default.yellow(` No log file found at ${logPath2}`));
54773
56178
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
54774
56179
  return;
@@ -54776,7 +56181,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
54776
56181
  console.log(source_default.green(` Tailing ${logPath2}...
54777
56182
  `));
54778
56183
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
54779
- (0, import_node_child_process28.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
56184
+ (0, import_node_child_process29.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
54780
56185
  });
54781
56186
  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) => {
54782
56187
  console.log(LOGO2);
@@ -54788,7 +56193,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
54788
56193
  for (const cmd of commands2) {
54789
56194
  console.log(source_default.green(` \u2192 ${cmd}
54790
56195
  `));
54791
- (0, import_node_child_process28.execSync)(cmd, { stdio: "inherit" });
56196
+ (0, import_node_child_process29.execSync)(cmd, { stdio: "inherit" });
54792
56197
  }
54793
56198
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
54794
56199
  await reportIfStillStale();
@@ -54813,7 +56218,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
54813
56218
  for (const cmd of commands) {
54814
56219
  console.log(source_default.green(` \u2192 ${cmd}
54815
56220
  `));
54816
- (0, import_node_child_process28.execSync)(cmd, { stdio: "inherit" });
56221
+ (0, import_node_child_process29.execSync)(cmd, { stdio: "inherit" });
54817
56222
  }
54818
56223
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
54819
56224
  if (installMode === "desktop") {
@@ -54836,10 +56241,10 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
54836
56241
  program2.command("remove").description("Uninstall ThreatCrush and the installed bundle").alias("uninstall").action(async () => {
54837
56242
  console.log(LOGO2);
54838
56243
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
54839
- const confirm = await new Promise((resolve8) => {
56244
+ const confirm = await new Promise((resolve9) => {
54840
56245
  rl.question(source_default.yellow(" Are you sure you want to uninstall ThreatCrush? (y/N): "), (answer) => {
54841
56246
  rl.close();
54842
- resolve8(answer.trim().toLowerCase());
56247
+ resolve9(answer.trim().toLowerCase());
54843
56248
  });
54844
56249
  });
54845
56250
  if (confirm !== "y" && confirm !== "yes") {
@@ -54864,7 +56269,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
54864
56269
  for (const cmd of commands) {
54865
56270
  console.log(source_default.green(` \u2192 ${cmd}
54866
56271
  `));
54867
- (0, import_node_child_process28.execSync)(cmd, { stdio: "inherit" });
56272
+ (0, import_node_child_process29.execSync)(cmd, { stdio: "inherit" });
54868
56273
  }
54869
56274
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
54870
56275
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -54941,19 +56346,19 @@ storeCmd.command("search <query>").description("Search for modules in the store"
54941
56346
  });
54942
56347
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
54943
56348
  console.log(LOGO2);
54944
- const configPath = (0, import_node_path51.join)((0, import_node_os19.homedir)(), ".threatcrush", "config.json");
56349
+ const configPath = (0, import_node_path57.join)((0, import_node_os23.homedir)(), ".threatcrush", "config.json");
54945
56350
  let email = "";
54946
56351
  try {
54947
- const config = JSON.parse((0, import_node_fs68.readFileSync)(configPath, "utf-8"));
56352
+ const config = JSON.parse((0, import_node_fs74.readFileSync)(configPath, "utf-8"));
54948
56353
  email = config.email || "";
54949
56354
  } catch {
54950
56355
  }
54951
56356
  if (!email) {
54952
56357
  const rl2 = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
54953
- email = await new Promise((resolve8) => {
56358
+ email = await new Promise((resolve9) => {
54954
56359
  rl2.question(source_default.green(" Enter your email: "), (answer) => {
54955
56360
  rl2.close();
54956
- resolve8(answer.trim());
56361
+ resolve9(answer.trim());
54957
56362
  });
54958
56363
  });
54959
56364
  if (!email || !email.includes("@")) {
@@ -54961,9 +56366,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
54961
56366
  return;
54962
56367
  }
54963
56368
  try {
54964
- const dir = (0, import_node_path51.join)((0, import_node_os19.homedir)(), ".threatcrush");
54965
- if (!(0, import_node_fs68.existsSync)(dir)) (0, import_node_fs68.mkdirSync)(dir, { recursive: true });
54966
- (0, import_node_fs68.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
56369
+ const dir = (0, import_node_path57.join)((0, import_node_os23.homedir)(), ".threatcrush");
56370
+ if (!(0, import_node_fs74.existsSync)(dir)) (0, import_node_fs74.mkdirSync)(dir, { recursive: true });
56371
+ (0, import_node_fs74.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
54967
56372
  console.log(source_default.dim(` Saved email to ${configPath}`));
54968
56373
  } catch {
54969
56374
  }
@@ -55007,10 +56412,10 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
55007
56412
  }
55008
56413
  console.log();
55009
56414
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
55010
- const confirm = await new Promise((resolve8) => {
56415
+ const confirm = await new Promise((resolve9) => {
55011
56416
  rl.question(source_default.yellow(" Publish this module? (y/N): "), (answer) => {
55012
56417
  rl.close();
55013
- resolve8(answer.trim().toLowerCase());
56418
+ resolve9(answer.trim().toLowerCase());
55014
56419
  });
55015
56420
  });
55016
56421
  if (confirm !== "y" && confirm !== "yes") {