@profullstack/threatcrush 0.13.52 → 0.13.54

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((resolve6, reject) => {
1659
- setImmediate(parseAsyncNext, index, blocksize, resolve6, reject);
1658
+ return new Promise((resolve7, reject) => {
1659
+ setImmediate(parseAsyncNext, index, blocksize, resolve7, reject);
1660
1660
  });
1661
- function parseAsyncNext(index2, blocksize2, resolve6, reject) {
1661
+ function parseAsyncNext(index2, blocksize2, resolve7, reject) {
1662
1662
  if (index2 >= str3.length) {
1663
1663
  try {
1664
- return resolve6(parser.finish());
1664
+ return resolve7(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, resolve6, reject);
1671
+ setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve7, 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((resolve6, reject) => {
1697
+ return new Promise((resolve7, 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
- resolve6(parser.finish());
1705
+ resolve7(parser.finish());
1706
1706
  } catch (err) {
1707
1707
  reject(err);
1708
1708
  }
@@ -5597,11 +5597,11 @@ function daysInMonth(year, month) {
5597
5597
  function isLeapYear(year) {
5598
5598
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
5599
5599
  }
5600
- function dayOfWeek(year, month, day) {
5600
+ function dayOfWeek(year, month, day2) {
5601
5601
  const offsets = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
5602
5602
  const y = month < 3 ? year - 1 : year;
5603
5603
  const leaps = Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400);
5604
- const value = (y + leaps + offsets[month - 1] + day) % 7;
5604
+ const value = (y + leaps + offsets[month - 1] + day2) % 7;
5605
5605
  return (value % 7 + 7) % 7;
5606
5606
  }
5607
5607
  function drawCalendar(surface, options) {
@@ -5639,20 +5639,20 @@ function drawCalendar(surface, options) {
5639
5639
  }
5640
5640
  const first = (dayOfWeek(year, month, 1) - weekStart + 7) % 7;
5641
5641
  const total = daysInMonth(year, month);
5642
- for (let day = 1; day <= total; day++) {
5643
- const cell = first + day - 1;
5642
+ for (let day2 = 1; day2 <= total; day2++) {
5643
+ const cell = first + day2 - 1;
5644
5644
  const y = row + Math.floor(cell / 7);
5645
5645
  if (y >= surface.height)
5646
5646
  break;
5647
5647
  const x = cell % 7 * DAY_WIDTH;
5648
- const mark = marks.get(day);
5649
- const selected = options.selected === day;
5648
+ const mark = marks.get(day2);
5649
+ const selected = options.selected === day2;
5650
5650
  const style = {
5651
5651
  fg: selected ? theme.background : mark?.color ?? base,
5652
5652
  bg: selected ? theme.accent : mark?.background ?? bg,
5653
5653
  attrs: selected || mark?.bold ? Attr.Bold : 0
5654
5654
  };
5655
- surface.text(x, y, fit(String(day), 2, "right"), style);
5655
+ surface.text(x, y, fit(String(day2), 2, "right"), style);
5656
5656
  }
5657
5657
  }
5658
5658
  function calendarHeight(options) {
@@ -14535,12 +14535,12 @@ function load() {
14535
14535
  if (table)
14536
14536
  return table;
14537
14537
  const byKey = /* @__PURE__ */ new Map();
14538
- for (const [key, short, name, group, keywords] of OPENEMOJI_ROWS) {
14538
+ for (const [key, short2, name, group, keywords] of OPENEMOJI_ROWS) {
14539
14539
  byKey.set(key, {
14540
14540
  key,
14541
14541
  char: charOf(key),
14542
14542
  name,
14543
- shortcode: `oe_${short || slugOf(name)}`,
14543
+ shortcode: `oe_${short2 || slugOf(name)}`,
14544
14544
  group: OPENEMOJI_GROUPS[group] ?? "",
14545
14545
  keywords: keywords ? keywords.split(" ") : []
14546
14546
  });
@@ -16764,8 +16764,8 @@ var init_app = __esm({
16764
16764
  this.frame();
16765
16765
  }, interval);
16766
16766
  this.timer.unref?.();
16767
- await new Promise((resolve6) => {
16768
- this.exitResolve = resolve6;
16767
+ await new Promise((resolve7) => {
16768
+ this.exitResolve = resolve7;
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((resolve6, reject) => {
17241
+ return new Promise((resolve7, reject) => {
17242
17242
  const sock = (0, import_node_net.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
- resolve6();
17254
+ resolve7();
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((resolve6, reject) => {
17270
+ return new Promise((resolve7, 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: resolve6, reject, timer });
17277
+ this.pending.set(id, { resolve: resolve7, reject, timer });
17278
17278
  this.socket.write(JSON.stringify(frame) + "\n", (err) => {
17279
17279
  if (err && this.pending.delete(id)) {
17280
17280
  clearTimeout(timer);
@@ -18276,7 +18276,7 @@ function isPublicAddress(ip) {
18276
18276
  if (v === 6) return !/^(::1?$|f[cd]|fe[89ab]|ff)/i.test(ip);
18277
18277
  return false;
18278
18278
  }
18279
- function localMapData(state, geo, hostname4, now = Date.now()) {
18279
+ function localMapData(state, geo, hostname5, now = Date.now()) {
18280
18280
  const by = /* @__PURE__ */ new Map();
18281
18281
  for (const e of state.events) {
18282
18282
  const ip = e.source_ip;
@@ -18300,7 +18300,7 @@ function localMapData(state, geo, hostname4, now = Date.now()) {
18300
18300
  const o = by.get(t.ip);
18301
18301
  if (o) o.count = Math.max(o.count, t.count);
18302
18302
  }
18303
- const servers = geo.self ? [{ id: "self", name: hostname4, ...geo.self, online: state.connection === "live" }] : [];
18303
+ const servers = geo.self ? [{ id: "self", name: hostname5, ...geo.self, online: state.connection === "live" }] : [];
18304
18304
  return { servers, origins: [...by.values()], windowMinutes: 0, generatedAt: new Date(now).toISOString() };
18305
18305
  }
18306
18306
  function sourceAddresses(state) {
@@ -22084,7 +22084,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
22084
22084
  const negativeNumberArg = (arg) => {
22085
22085
  if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
22086
22086
  return !this._getCommandAndAncestors().some(
22087
- (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
22087
+ (cmd) => cmd.options.map((opt) => opt.short).some((short2) => /^-\d$/.test(short2))
22088
22088
  );
22089
22089
  };
22090
22090
  let activeVariadicOption = null;
@@ -23425,10 +23425,10 @@ var source_default = chalk;
23425
23425
 
23426
23426
  // src/index.ts
23427
23427
  var import_readline = __toESM(require("readline"));
23428
- var import_node_child_process23 = require("child_process");
23429
- var import_node_fs54 = require("fs");
23430
- var import_node_path40 = require("path");
23431
- var import_node_os16 = require("os");
23428
+ var import_node_child_process24 = require("child_process");
23429
+ var import_node_fs55 = require("fs");
23430
+ var import_node_path42 = require("path");
23431
+ var import_node_os17 = require("os");
23432
23432
 
23433
23433
  // src/commands/monitor.ts
23434
23434
  var import_node_fs11 = require("fs");
@@ -31121,20 +31121,20 @@ function groupFindings(records, triage = {}) {
31121
31121
  }
31122
31122
  f.samples.push(r);
31123
31123
  }
31124
- const findings = [];
31124
+ const findings2 = [];
31125
31125
  for (const f of byId.values()) {
31126
31126
  const { _ips, ...rest } = f;
31127
31127
  rest.source_count = _ips.size;
31128
31128
  rest.samples = rest.samples.sort((a, b) => OUTCOME_ORDER.indexOf(a.outcome) - OUTCOME_ORDER.indexOf(b.outcome) || b.at.localeCompare(a.at)).slice(0, SAMPLES_CAP);
31129
- findings.push(rest);
31129
+ findings2.push(rest);
31130
31130
  }
31131
31131
  const triaged = (f) => f.triage.status === "new" ? 0 : 1;
31132
- return findings.sort((a, b) => triaged(a) - triaged(b) || OUTCOME_ORDER.indexOf(a.outcome) - OUTCOME_ORDER.indexOf(b.outcome) || SEVERITY_RANK2[b.severity] - SEVERITY_RANK2[a.severity] || b.count - a.count || b.last_seen.localeCompare(a.last_seen));
31132
+ return findings2.sort((a, b) => triaged(a) - triaged(b) || OUTCOME_ORDER.indexOf(a.outcome) - OUTCOME_ORDER.indexOf(b.outcome) || SEVERITY_RANK2[b.severity] - SEVERITY_RANK2[a.severity] || b.count - a.count || b.last_seen.localeCompare(a.last_seen));
31133
31133
  }
31134
- function findFinding(findings, id) {
31135
- const exact = findings.find((f) => f.id === id);
31134
+ function findFinding(findings2, id) {
31135
+ const exact = findings2.find((f) => f.id === id);
31136
31136
  if (exact) return exact;
31137
- const matches2 = findings.filter((f) => f.id.startsWith(id));
31137
+ const matches2 = findings2.filter((f) => f.id.startsWith(id));
31138
31138
  return matches2.length === 1 ? matches2[0] : null;
31139
31139
  }
31140
31140
  function shellQuote(s) {
@@ -31231,32 +31231,32 @@ function where(f) {
31231
31231
  }
31232
31232
  function watchdogListCommand(opts) {
31233
31233
  const dir = resolveWatchdogDir(opts.dir);
31234
- let findings = load2(dir);
31235
- if (opts.status) findings = findings.filter((f) => f.triage.status === opts.status);
31236
- if (opts.outcome) findings = findings.filter((f) => f.outcome === opts.outcome);
31234
+ let findings2 = load2(dir);
31235
+ if (opts.status) findings2 = findings2.filter((f) => f.triage.status === opts.status);
31236
+ if (opts.outcome) findings2 = findings2.filter((f) => f.outcome === opts.outcome);
31237
31237
  if (!opts.all && !opts.status && !opts.outcome) {
31238
- findings = findings.filter((f) => (f.triage.status === "new" || f.triage.status === "hole") && f.outcome !== "refused");
31238
+ findings2 = findings2.filter((f) => (f.triage.status === "new" || f.triage.status === "hole") && f.outcome !== "refused");
31239
31239
  }
31240
31240
  const limit = opts.limit ? Math.max(1, parseInt(opts.limit, 10) || 50) : 50;
31241
31241
  if (opts.json) {
31242
- console.log(JSON.stringify(findings.slice(0, limit), null, 2));
31242
+ console.log(JSON.stringify(findings2.slice(0, limit), null, 2));
31243
31243
  return;
31244
31244
  }
31245
- if (findings.length === 0) {
31245
+ if (findings2.length === 0) {
31246
31246
  const empty = (0, import_node_fs13.existsSync)((0, import_node_path11.join)(dir, "attacks.jsonl")) ? "Nothing to triage." + (opts.all ? "" : " (refused and triaged findings hidden; --all shows them)") : `No watchdog log at ${dir}. The daemon writes it: threatcrush start (or upgrade + restart an older daemon).`;
31247
31247
  console.log(source_default.dim(empty));
31248
31248
  return;
31249
31249
  }
31250
- console.log(source_default.dim(`${dir} \xB7 ${findings.length} finding(s)
31250
+ console.log(source_default.dim(`${dir} \xB7 ${findings2.length} finding(s)
31251
31251
  `));
31252
- for (const f of findings.slice(0, limit)) {
31252
+ for (const f of findings2.slice(0, limit)) {
31253
31253
  const statuses = Object.keys(f.statuses).join(",") || "\u2014";
31254
31254
  console.log(
31255
31255
  `${source_default.bold(f.id)} ${OUTCOME_COLOR[f.outcome](f.outcome.padEnd(10))} ${TRIAGE_COLOR[f.triage.status](f.triage.status.padEnd(5))} ${f.severity.padEnd(8)} ${String(f.count).padStart(5)}\xD7 ${source_default.dim(statuses.padEnd(9))} ${source_default.cyan(f.attack_type ?? f.rule_id ?? f.module)} ${where(f)}`
31256
31256
  );
31257
31257
  }
31258
- if (findings.length > limit) console.log(source_default.dim(`
31259
- \u2026 ${findings.length - limit} more (--limit)`));
31258
+ if (findings2.length > limit) console.log(source_default.dim(`
31259
+ \u2026 ${findings2.length - limit} more (--limit)`));
31260
31260
  console.log(source_default.dim("\nthreatcrush watchdog show <id> \xB7 brief <id> \xB7 mark <id> hole|fp|fixed"));
31261
31261
  }
31262
31262
  function resolve(dir, id) {
@@ -34773,9 +34773,9 @@ var import_node_os7 = __toESM(require("os"));
34773
34773
  function emptyCounts() {
34774
34774
  return { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
34775
34775
  }
34776
- function summarize(findings) {
34776
+ function summarize(findings2) {
34777
34777
  const counts = emptyCounts();
34778
- for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1;
34778
+ for (const f of findings2) counts[f.severity] = (counts[f.severity] || 0) + 1;
34779
34779
  return counts;
34780
34780
  }
34781
34781
  function workerId() {
@@ -36972,13 +36972,13 @@ function isRiskyLifecycleScript(body) {
36972
36972
  return /\b(?:curl|wget)\b[^\n|]*\|\s*(?:\w*sh|bash|node|python)\b|\b(?:curl|wget)\b[^\n]*(?:https?:|--upload-file)|\b(?:node|python|ruby|perl)\s+-e\b|\b(?:base64|openssl)\b[^\n]*(?:-d|--decode)|\beval\s+|\bchmod\s+(?:\S+\s+)*(?:777|a\+rwx)\b/i.test(body);
36973
36973
  }
36974
36974
  function scanPackageJson(text) {
36975
- const findings = [];
36975
+ const findings2 = [];
36976
36976
  const lines = text.split("\n");
36977
36977
  let parsed;
36978
36978
  try {
36979
36979
  parsed = JSON.parse(text);
36980
36980
  } catch {
36981
- return findings;
36981
+ return findings2;
36982
36982
  }
36983
36983
  const lineOf = (needle) => {
36984
36984
  const index = lines.findIndex((line2) => line2.includes(`"${needle}"`));
@@ -36991,7 +36991,7 @@ function scanPackageJson(text) {
36991
36991
  for (const name of Object.keys(deps)) {
36992
36992
  const line2 = lineOf(name);
36993
36993
  if (INTERNAL_MARKER.test(name)) {
36994
- findings.push({
36994
+ findings2.push({
36995
36995
  ruleId: "manifest-dependency-confusion",
36996
36996
  title: "internal-looking package resolved from a public registry",
36997
36997
  line: line2,
@@ -37005,7 +37005,7 @@ function scanPackageJson(text) {
37005
37005
  }
37006
37006
  const squat = detectTyposquat(name, "npm");
37007
37007
  if (squat) {
37008
- findings.push({
37008
+ findings2.push({
37009
37009
  ruleId: "manifest-typosquat",
37010
37010
  title: "dependency name close to a popular package",
37011
37011
  line: line2,
@@ -37023,7 +37023,7 @@ function scanPackageJson(text) {
37023
37023
  for (const [name, body] of Object.entries(scripts)) {
37024
37024
  if (!LIFECYCLE_SCRIPTS.includes(name)) continue;
37025
37025
  if (!isRiskyLifecycleScript(body)) continue;
37026
- findings.push({
37026
+ findings2.push({
37027
37027
  ruleId: "manifest-risky-install-lifecycle-script",
37028
37028
  title: "risky install-time lifecycle script",
37029
37029
  line: lineOf(name),
@@ -37035,10 +37035,10 @@ function scanPackageJson(text) {
37035
37035
  });
37036
37036
  }
37037
37037
  }
37038
- return findings;
37038
+ return findings2;
37039
37039
  }
37040
37040
  function scanRequirementsTxt(text) {
37041
- const findings = [];
37041
+ const findings2 = [];
37042
37042
  const lines = text.split("\n");
37043
37043
  lines.forEach((raw, index) => {
37044
37044
  const line2 = raw.trim();
@@ -37047,7 +37047,7 @@ function scanRequirementsTxt(text) {
37047
37047
  const name = match?.[1];
37048
37048
  if (!name) return;
37049
37049
  if (INTERNAL_MARKER.test(name)) {
37050
- findings.push({
37050
+ findings2.push({
37051
37051
  ruleId: "manifest-dependency-confusion",
37052
37052
  title: "internal-looking package resolved from a public index",
37053
37053
  line: index + 1,
@@ -37061,7 +37061,7 @@ function scanRequirementsTxt(text) {
37061
37061
  }
37062
37062
  const squat = detectTyposquat(name, "pypi");
37063
37063
  if (squat) {
37064
- findings.push({
37064
+ findings2.push({
37065
37065
  ruleId: "manifest-typosquat",
37066
37066
  title: "dependency name close to a popular package",
37067
37067
  line: index + 1,
@@ -37073,7 +37073,7 @@ function scanRequirementsTxt(text) {
37073
37073
  });
37074
37074
  }
37075
37075
  });
37076
- return findings;
37076
+ return findings2;
37077
37077
  }
37078
37078
 
37079
37079
  // ../../packages/scan/src/secret-rules.ts
@@ -37700,7 +37700,7 @@ var CODE_SOFTENING = {
37700
37700
  "self-describing": "in a value that describes itself"
37701
37701
  };
37702
37702
  function scanText(relativePath, text, language = languageOf(relativePath)) {
37703
- const findings = [];
37703
+ const findings2 = [];
37704
37704
  const lines = text.split("\n");
37705
37705
  const suppressions = collectSuppressions(lines);
37706
37706
  const inTests = isTestPath(relativePath);
@@ -37722,7 +37722,7 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
37722
37722
  placeholder: isPlaceholderAttribute(line2, value),
37723
37723
  "self-describing": rule.keywordShaped === true && describesItsOwnKey(line2, value)
37724
37724
  });
37725
- findings.push({
37725
+ findings2.push({
37726
37726
  ruleId: rule.id,
37727
37727
  title: rule.name,
37728
37728
  file: relativePath,
@@ -37753,7 +37753,7 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
37753
37753
  docs: inDocs,
37754
37754
  suppressed: foreignSecurityMark(lines[index] ?? "")
37755
37755
  });
37756
- findings.push({
37756
+ findings2.push({
37757
37757
  ruleId: rule.id,
37758
37758
  title: rule.title,
37759
37759
  file: relativePath,
@@ -37777,7 +37777,7 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
37777
37777
  docs: inDocs,
37778
37778
  suppressed: foreignSecurityMark(lines[index] ?? "")
37779
37779
  });
37780
- findings.push({
37780
+ findings2.push({
37781
37781
  ruleId: match.rule.id,
37782
37782
  title: match.rule.title,
37783
37783
  file: relativePath,
@@ -37791,7 +37791,7 @@ function scanText(relativePath, text, language = languageOf(relativePath)) {
37791
37791
  category: "code"
37792
37792
  });
37793
37793
  }
37794
- return findings;
37794
+ return findings2;
37795
37795
  }
37796
37796
  function scanManifest(relativePath, filename, text) {
37797
37797
  const manifestFindings = filename === "package.json" ? scanPackageJson(text) : filename === "requirements.txt" ? scanRequirementsTxt(text) : [];
@@ -37809,10 +37809,10 @@ function scanManifest(relativePath, filename, text) {
37809
37809
  category: "manifest"
37810
37810
  }));
37811
37811
  }
37812
- function meetsFailThreshold(findings, threshold) {
37812
+ function meetsFailThreshold(findings2, threshold) {
37813
37813
  if (threshold.length === 0) return false;
37814
37814
  const floor = Math.min(...threshold.map(severityRank));
37815
- return findings.some((finding) => severityRank(finding.severity) >= floor);
37815
+ return findings2.some((finding) => severityRank(finding.severity) >= floor);
37816
37816
  }
37817
37817
 
37818
37818
  // ../../packages/scan/src/node/walk.ts
@@ -37896,7 +37896,7 @@ function readIgnoreFile(root) {
37896
37896
  function scanPath(targetPath, options = {}) {
37897
37897
  const maxFileBytes = options.maxFileBytes ?? 1024 * 1024;
37898
37898
  const allowed = options.categories ? new Set(options.categories) : null;
37899
- const findings = [];
37899
+ const findings2 = [];
37900
37900
  const controls = new ControlAudit();
37901
37901
  const unreadable = [];
37902
37902
  let filesScanned = 0;
@@ -37918,7 +37918,7 @@ function scanPath(targetPath, options = {}) {
37918
37918
  const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env");
37919
37919
  const mayDeclareInterpreter = !scannable && !isManifest && extension === "";
37920
37920
  if (!scannable && !isManifest && !mayDeclareInterpreter) {
37921
- recordSensitiveFile(filename, relativePath, findings, []);
37921
+ recordSensitiveFile(filename, relativePath, findings2, []);
37922
37922
  return;
37923
37923
  }
37924
37924
  let text;
@@ -37956,8 +37956,8 @@ function scanPath(targetPath, options = {}) {
37956
37956
  ...scanText(relativePath, text, declared ?? languageOf(filename)),
37957
37957
  ...isManifest ? scanManifest(relativePath, filename, text) : []
37958
37958
  ];
37959
- findings.push(...fileFindings);
37960
- recordSensitiveFile(filename, relativePath, findings, fileFindings);
37959
+ findings2.push(...fileFindings);
37960
+ recordSensitiveFile(filename, relativePath, findings2, fileFindings);
37961
37961
  };
37962
37962
  const walk = (currentPath) => {
37963
37963
  let entries;
@@ -37994,8 +37994,8 @@ function scanPath(targetPath, options = {}) {
37994
37994
  } else {
37995
37995
  scanFile(targetPath, (0, import_node_path12.basename)(targetPath));
37996
37996
  }
37997
- if (options.missingControls) findings.push(...controls.findings());
37998
- const filtered = allowed ? findings.filter((f) => allowed.has(f.category)) : findings;
37997
+ if (options.missingControls) findings2.push(...controls.findings());
37998
+ const filtered = allowed ? findings2.filter((f) => allowed.has(f.category)) : findings2;
37999
37999
  filtered.sort(
38000
38000
  (a, b) => severityRank(b.severity) - severityRank(a.severity) || a.file.localeCompare(b.file) || a.line - b.line
38001
38001
  );
@@ -38033,7 +38033,7 @@ var import_node_fs15 = require("fs");
38033
38033
  var import_node_path13 = require("path");
38034
38034
  var MAX_DEPS_PER_LOCKFILE = 50;
38035
38035
  async function scanDependencies(targetPath) {
38036
- const findings = [];
38036
+ const findings2 = [];
38037
38037
  for (const { file, ecosystem, parse: parse3 } of LOCKFILES) {
38038
38038
  const lockPath = (0, import_node_path13.join)(targetPath, file);
38039
38039
  if (!(0, import_node_fs15.existsSync)(lockPath)) continue;
@@ -38044,11 +38044,11 @@ async function scanDependencies(targetPath) {
38044
38044
  continue;
38045
38045
  }
38046
38046
  if (deps.length === 0) {
38047
- findings.push(incompleteFinding(file, "No dependencies could be read from this lockfile."));
38047
+ findings2.push(incompleteFinding(file, "No dependencies could be read from this lockfile."));
38048
38048
  continue;
38049
38049
  }
38050
38050
  if (deps.length > MAX_DEPS_PER_LOCKFILE) {
38051
- findings.push(
38051
+ findings2.push(
38052
38052
  incompleteFinding(
38053
38053
  file,
38054
38054
  `Only the first ${MAX_DEPS_PER_LOCKFILE} of ${deps.length} locked packages were checked against OSV.`
@@ -38064,7 +38064,7 @@ async function scanDependencies(targetPath) {
38064
38064
  }
38065
38065
  for (const vuln of vulns) {
38066
38066
  const cvss = vuln.severity?.find((entry) => entry.type === "CVSS_V3")?.score;
38067
- findings.push({
38067
+ findings2.push({
38068
38068
  ruleId: "dependency-known-vulnerability",
38069
38069
  title: "Dependency CVE",
38070
38070
  file,
@@ -38079,7 +38079,7 @@ async function scanDependencies(targetPath) {
38079
38079
  }
38080
38080
  }
38081
38081
  }
38082
- return findings;
38082
+ return findings2;
38083
38083
  }
38084
38084
  function incompleteFinding(file, message) {
38085
38085
  return {
@@ -38301,9 +38301,9 @@ function toArtifactUri(filePath, base, prefix = "", root = base) {
38301
38301
  const trimmed = prefix.replace(/^\/+|\/+$/g, "");
38302
38302
  return trimmed ? `${trimmed}/${posix}` : posix;
38303
38303
  }
38304
- function buildSarif(findings, options) {
38304
+ function buildSarif(findings2, options) {
38305
38305
  const rules = /* @__PURE__ */ new Map();
38306
- for (const finding of findings) {
38306
+ for (const finding of findings2) {
38307
38307
  if (rules.has(finding.ruleId)) continue;
38308
38308
  const tags = ["security"];
38309
38309
  if (finding.cwe) tags.push(`external/cwe/${finding.cwe.toLowerCase()}`);
@@ -38333,7 +38333,7 @@ ${finding.consequence}` : `**${finding.title}**`
38333
38333
  }
38334
38334
  const base = options.base ?? process.cwd();
38335
38335
  const root = options.root ?? base;
38336
- const results = findings.map((finding) => ({
38336
+ const results = findings2.map((finding) => ({
38337
38337
  ruleId: finding.ruleId,
38338
38338
  level: sarifLevel(finding.severity),
38339
38339
  message: { text: finding.message },
@@ -38408,8 +38408,8 @@ function parseFailOn(raw) {
38408
38408
  }
38409
38409
  return requested;
38410
38410
  }
38411
- function toRunResult(targetPath, findings, filesScanned) {
38412
- const structured = findings.map((finding) => ({
38411
+ function toRunResult(targetPath, findings2, filesScanned) {
38412
+ const structured = findings2.map((finding) => ({
38413
38413
  type: finding.title,
38414
38414
  severity: finding.severity,
38415
38415
  message: finding.message,
@@ -38429,7 +38429,7 @@ function toRunResult(targetPath, findings, filesScanned) {
38429
38429
  target: targetPath,
38430
38430
  findings: structured,
38431
38431
  severity_summary: counts,
38432
- summary: findings.length === 0 ? `No issues found across ${filesScanned} files` : `${findings.length} issue(s): ${counts.critical}C ${counts.high}H ${counts.medium}M ${counts.low}L`
38432
+ summary: findings2.length === 0 ? `No issues found across ${filesScanned} files` : `${findings2.length} issue(s): ${counts.critical}C ${counts.high}H ${counts.medium}M ${counts.low}L`
38433
38433
  };
38434
38434
  }
38435
38435
  function failedResult(targetPath, message) {
@@ -38445,8 +38445,8 @@ function failedResult(targetPath, message) {
38445
38445
  async function runScan(targetPath) {
38446
38446
  try {
38447
38447
  const report = scanPath(targetPath);
38448
- const findings = [...report.findings, ...await scanDependencies(targetPath)];
38449
- return toRunResult(targetPath, findings, report.filesScanned);
38448
+ const findings2 = [...report.findings, ...await scanDependencies(targetPath)];
38449
+ return toRunResult(targetPath, findings2, report.filesScanned);
38450
38450
  } catch (err) {
38451
38451
  return failedResult(targetPath, err.message);
38452
38452
  }
@@ -38579,8 +38579,8 @@ function emitMachineReadable(format2, outcome, targetPath, options, say) {
38579
38579
  process.stdout.write(serialized);
38580
38580
  }
38581
38581
  function printHuman(outcome) {
38582
- const { findings, filesScanned } = outcome;
38583
- if (findings.length === 0) {
38582
+ const { findings: findings2, filesScanned } = outcome;
38583
+ if (findings2.length === 0) {
38584
38584
  console.log(source_default.green.bold(" \u2713 No security issues found!"));
38585
38585
  console.log();
38586
38586
  return;
@@ -38593,7 +38593,7 @@ function printHuman(outcome) {
38593
38593
  );
38594
38594
  console.log(source_default.gray(" " + "\u2500".repeat(70)));
38595
38595
  console.log();
38596
- for (const finding of findings) {
38596
+ for (const finding of findings2) {
38597
38597
  const label = finding.severity.toUpperCase();
38598
38598
  const badge = finding.severity === "critical" ? source_default.bgRed.white.bold(` ${label} `) : finding.severity === "high" ? source_default.red(`[${label}]`) : finding.severity === "medium" ? source_default.yellow(`[${label}]`) : source_default.gray(`[${label}]`);
38599
38599
  console.log(` ${badge} ${source_default.white.bold(finding.title)}`);
@@ -38614,7 +38614,7 @@ function printHuman(outcome) {
38614
38614
  }
38615
38615
  console.log(source_default.gray(" " + "\u2500".repeat(70)));
38616
38616
  console.log(
38617
- ` ${source_default.white.bold(`${findings.length} issue(s) found`)} across ${filesScanned} files`
38617
+ ` ${source_default.white.bold(`${findings2.length} issue(s) found`)} across ${filesScanned} files`
38618
38618
  );
38619
38619
  console.log();
38620
38620
  }
@@ -38664,8 +38664,8 @@ function askPiped(question, mask) {
38664
38664
  if (reader.lines.length > 0) return Promise.resolve(settle2(reader.lines.shift()));
38665
38665
  if (reader.ended) return Promise.resolve(settle2(null));
38666
38666
  reader.rl.resume();
38667
- return new Promise((resolve6) => {
38668
- reader.waiting = (line2) => resolve6(settle2(line2));
38667
+ return new Promise((resolve7) => {
38668
+ reader.waiting = (line2) => resolve7(settle2(line2));
38669
38669
  });
38670
38670
  }
38671
38671
  function askTerminal(question, mask) {
@@ -38673,20 +38673,20 @@ function askTerminal(question, mask) {
38673
38673
  cb();
38674
38674
  } }) : process.stdout;
38675
38675
  const rl = import_node_readline.default.createInterface({ input: process.stdin, output, terminal: true });
38676
- return new Promise((resolve6) => {
38676
+ return new Promise((resolve7) => {
38677
38677
  let settled = false;
38678
38678
  rl.on("close", () => {
38679
38679
  if (settled) return;
38680
38680
  settled = true;
38681
38681
  process.stdout.write("\n");
38682
- resolve6(null);
38682
+ resolve7(null);
38683
38683
  });
38684
38684
  if (mask) process.stdout.write(question);
38685
38685
  rl.question(mask ? "" : question, (answer) => {
38686
38686
  settled = true;
38687
38687
  rl.close();
38688
38688
  if (mask) process.stdout.write("\n");
38689
- resolve6(answer);
38689
+ resolve7(answer);
38690
38690
  });
38691
38691
  });
38692
38692
  }
@@ -38724,7 +38724,7 @@ async function startLinkLogin(pkce, deviceName = (0, import_node_os8.hostname)()
38724
38724
  }
38725
38725
  return data;
38726
38726
  }
38727
- var sleep = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
38727
+ var sleep = (ms) => new Promise((resolve7) => setTimeout(resolve7, ms));
38728
38728
  async function waitForApproval(request, pkce, opts = {}) {
38729
38729
  const wait = opts.sleepMs ?? sleep;
38730
38730
  const now = opts.now ?? Date.now;
@@ -40314,7 +40314,7 @@ async function pentestCommand(targetUrl) {
40314
40314
  }
40315
40315
 
40316
40316
  // src/commands/ai-scan.ts
40317
- var import_node_fs22 = require("fs");
40317
+ var import_node_fs23 = require("fs");
40318
40318
 
40319
40319
  // src/aiscan/probes.ts
40320
40320
  function makeCanary() {
@@ -40414,7 +40414,7 @@ async function runAiScan(target, send, opts = {}) {
40414
40414
  opts.onProbe?.(probe, vulnerable);
40415
40415
  if (opts.delayMs && opts.delayMs > 0) await sleep2(opts.delayMs);
40416
40416
  }
40417
- const findings = results.filter((r) => r.vulnerable).map((r) => ({
40417
+ const findings2 = results.filter((r) => r.vulnerable).map((r) => ({
40418
40418
  type: r.probe.id,
40419
40419
  severity: r.probe.severity,
40420
40420
  message: `${r.probe.owasp} ${r.probe.title}`,
@@ -40427,11 +40427,11 @@ async function runAiScan(target, send, opts = {}) {
40427
40427
  evidence: r.response.slice(0, 200)
40428
40428
  }
40429
40429
  }));
40430
- const counts = summarize(findings);
40430
+ const counts = summarize(findings2);
40431
40431
  const tested = results.length;
40432
40432
  const errored = results.filter((r) => r.error).length;
40433
- const summary = findings.length === 0 ? `No guardrail failures across ${tested} probe(s)${errored ? ` (${errored} errored)` : ""}` : `${findings.length}/${tested} probe(s) breached a guardrail: ${counts.critical}C ${counts.high}H ${counts.medium}M ${counts.low}L`;
40434
- return { type: "scan", target, findings, severity_summary: counts, summary };
40433
+ const summary = findings2.length === 0 ? `No guardrail failures across ${tested} probe(s)${errored ? ` (${errored} errored)` : ""}` : `${findings2.length}/${tested} probe(s) breached a guardrail: ${counts.critical}C ${counts.high}H ${counts.medium}M ${counts.low}L`;
40434
+ return { type: "scan", target, findings: findings2, severity_summary: counts, summary };
40435
40435
  }
40436
40436
  function httpSender(cfg) {
40437
40437
  const template = cfg.template ?? '{"input":"{{PROMPT}}"}';
@@ -40530,6 +40530,66 @@ ${stripShebang(source)}
40530
40530
  return { scans };
40531
40531
  }
40532
40532
 
40533
+ // src/core/usage-ping.ts
40534
+ var import_node_crypto6 = require("crypto");
40535
+ var import_node_fs22 = require("fs");
40536
+ var import_node_path19 = require("path");
40537
+ init_cli_config();
40538
+ var STATE_FILE = "usage-ping.json";
40539
+ function usagePingDisabled(env3 = process.env) {
40540
+ const v = (env3.THREATCRUSH_TELEMETRY ?? "").trim().toLowerCase();
40541
+ if (["0", "off", "false", "no"].includes(v)) return true;
40542
+ const dnt = (env3.DO_NOT_TRACK ?? "").trim().toLowerCase();
40543
+ return dnt !== "" && dnt !== "0" && dnt !== "false";
40544
+ }
40545
+ function installId(dir = CLI_CONFIG_DIR) {
40546
+ const file = (0, import_node_path19.join)(dir, STATE_FILE);
40547
+ try {
40548
+ const j = JSON.parse((0, import_node_fs22.readFileSync)(file, "utf-8"));
40549
+ if (j.install_id) return { id: j.install_id, fresh: false };
40550
+ } catch {
40551
+ }
40552
+ const id = (0, import_node_crypto6.randomUUID)();
40553
+ try {
40554
+ if (!(0, import_node_fs22.existsSync)(dir)) (0, import_node_fs22.mkdirSync)(dir, { recursive: true });
40555
+ (0, import_node_fs22.writeFileSync)(file, JSON.stringify({ install_id: id, created_at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n");
40556
+ } catch {
40557
+ }
40558
+ return { id, fresh: true };
40559
+ }
40560
+ function pingBody(p, id, env3 = process.env) {
40561
+ return {
40562
+ ...p,
40563
+ version: PKG_VERSION,
40564
+ platform: process.platform,
40565
+ arch: process.arch,
40566
+ node: process.version,
40567
+ ci: Boolean(env3.CI || env3.GITHUB_ACTIONS),
40568
+ install_id: id
40569
+ };
40570
+ }
40571
+ async function sendUsagePing(p, opts = {}) {
40572
+ const env3 = opts.env ?? process.env;
40573
+ if (usagePingDisabled(env3)) return false;
40574
+ try {
40575
+ const { id, fresh } = installId(opts.dir);
40576
+ if (fresh) {
40577
+ (opts.notice ?? ((s) => process.stderr.write(s + "\n")))(
40578
+ "threatcrush: sends an anonymous usage count per ai-scan run (no targets, no findings text). Turn off with THREATCRUSH_TELEMETRY=0."
40579
+ );
40580
+ }
40581
+ const res = await (opts.fetchImpl ?? fetch)(`${apiUrl()}/api/telemetry`, {
40582
+ method: "POST",
40583
+ headers: { "content-type": "application/json" },
40584
+ body: JSON.stringify(pingBody(p, id, env3)),
40585
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 2e3)
40586
+ });
40587
+ return res.ok;
40588
+ } catch {
40589
+ return false;
40590
+ }
40591
+ }
40592
+
40533
40593
  // src/commands/ai-scan.ts
40534
40594
  function parseHeaders(pairs = []) {
40535
40595
  const out = {};
@@ -40557,6 +40617,7 @@ async function aiScanCommand(url, opts) {
40557
40617
  logger.info(`Probing ${source_default.white(url)} with ${probes.length} check(s)...
40558
40618
  `);
40559
40619
  const spinner = ora({ text: "Running probes...", color: "green" }).start();
40620
+ const t0 = Date.now();
40560
40621
  const result = await runAiScan(url, send, {
40561
40622
  categories,
40562
40623
  delayMs: opts.delay ? Number(opts.delay) : 0,
@@ -40565,6 +40626,14 @@ async function aiScanCommand(url, opts) {
40565
40626
  }
40566
40627
  });
40567
40628
  spinner.stop();
40629
+ await sendUsagePing({
40630
+ event: "ai-scan",
40631
+ probes: probes.length,
40632
+ findings: result.findings.length,
40633
+ severity: result.severity_summary,
40634
+ duration_ms: Date.now() - t0,
40635
+ failed: Boolean(result.error)
40636
+ });
40568
40637
  if (opts.json) {
40569
40638
  console.log(JSON.stringify(result, null, 2));
40570
40639
  return result;
@@ -40591,42 +40660,51 @@ async function aiScanMoshCommand(file, args) {
40591
40660
  console.log();
40592
40661
  let source;
40593
40662
  try {
40594
- source = (0, import_node_fs22.readFileSync)(file, "utf-8");
40663
+ source = (0, import_node_fs23.readFileSync)(file, "utf-8");
40595
40664
  } catch (err) {
40596
40665
  logger.error(`Cannot read ${file}: ${err.message}`);
40597
40666
  process.exitCode = 1;
40598
- return;
40667
+ return [];
40599
40668
  }
40669
+ const t0 = Date.now();
40600
40670
  const res = await runMosh(source, { argv: args, out: (s) => console.log(" " + s) });
40671
+ await sendUsagePing({
40672
+ event: "ai-scan-run",
40673
+ scans: res.scans.length,
40674
+ findings: res.scans.reduce((n, s) => n + s.findings.length, 0),
40675
+ duration_ms: Date.now() - t0,
40676
+ failed: Boolean(res.failed)
40677
+ });
40601
40678
  if (res.failed) {
40602
40679
  console.log();
40603
40680
  console.log(` ${source_default.red("\u2717 script failed:")} ${res.failed}`);
40604
40681
  process.exitCode = 1;
40605
- return;
40682
+ return [];
40606
40683
  }
40607
40684
  const breached = res.scans.reduce((n, s) => n + s.findings.length, 0);
40608
40685
  console.log();
40609
40686
  console.log(` ${breached === 0 ? source_default.green("\u2713") : source_default.red("\u2716")} ${res.scans.length} scan(s), ${breached} guardrail failure(s)`);
40610
40687
  console.log();
40688
+ return res.scans;
40611
40689
  }
40612
40690
 
40613
40691
  // src/commands/orgs.ts
40614
40692
  var import_node_os9 = require("os");
40615
- var import_node_fs23 = require("fs");
40616
- var import_node_path19 = require("path");
40693
+ var import_node_fs24 = require("fs");
40694
+ var import_node_path20 = require("path");
40617
40695
  var API_URL3 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
40618
- var CONFIG_PATH = (0, import_node_path19.join)((0, import_node_os9.homedir)(), ".threatcrush", "config.json");
40696
+ var CONFIG_PATH = (0, import_node_path20.join)((0, import_node_os9.homedir)(), ".threatcrush", "config.json");
40619
40697
  function readConfig() {
40620
40698
  try {
40621
- return JSON.parse((0, import_node_fs23.readFileSync)(CONFIG_PATH, "utf-8"));
40699
+ return JSON.parse((0, import_node_fs24.readFileSync)(CONFIG_PATH, "utf-8"));
40622
40700
  } catch {
40623
40701
  return {};
40624
40702
  }
40625
40703
  }
40626
40704
  function writeConfig(config) {
40627
- const dir = (0, import_node_path19.join)((0, import_node_os9.homedir)(), ".threatcrush");
40628
- if (!(0, import_node_fs23.existsSync)(dir)) (0, import_node_fs23.mkdirSync)(dir, { recursive: true });
40629
- (0, import_node_fs23.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
40705
+ const dir = (0, import_node_path20.join)((0, import_node_os9.homedir)(), ".threatcrush");
40706
+ if (!(0, import_node_fs24.existsSync)(dir)) (0, import_node_fs24.mkdirSync)(dir, { recursive: true });
40707
+ (0, import_node_fs24.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
40630
40708
  }
40631
40709
  function getAuthHeaders() {
40632
40710
  const config = readConfig();
@@ -40762,13 +40840,13 @@ async function useOrganization(slug) {
40762
40840
 
40763
40841
  // src/commands/credits.ts
40764
40842
  var import_node_os10 = require("os");
40765
- var import_node_fs24 = require("fs");
40766
- var import_node_path20 = require("path");
40843
+ var import_node_fs25 = require("fs");
40844
+ var import_node_path21 = require("path");
40767
40845
  var API_URL4 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
40768
- var CONFIG_PATH2 = (0, import_node_path20.join)((0, import_node_os10.homedir)(), ".threatcrush", "config.json");
40846
+ var CONFIG_PATH2 = (0, import_node_path21.join)((0, import_node_os10.homedir)(), ".threatcrush", "config.json");
40769
40847
  function sessionToken() {
40770
40848
  try {
40771
- const cfg = JSON.parse((0, import_node_fs24.readFileSync)(CONFIG_PATH2, "utf-8"));
40849
+ const cfg = JSON.parse((0, import_node_fs25.readFileSync)(CONFIG_PATH2, "utf-8"));
40772
40850
  return cfg.token ?? null;
40773
40851
  } catch {
40774
40852
  return null;
@@ -40910,9 +40988,9 @@ async function fetchOrgs() {
40910
40988
  }
40911
40989
  function askChoice(question) {
40912
40990
  const rl = import_node_readline2.default.createInterface({ input: process.stdin, output: process.stdout });
40913
- return new Promise((resolve6) => rl.question(question, (answer) => {
40991
+ return new Promise((resolve7) => rl.question(question, (answer) => {
40914
40992
  rl.close();
40915
- resolve6(answer.trim());
40993
+ resolve7(answer.trim());
40916
40994
  }));
40917
40995
  }
40918
40996
  async function chooseOrg(orgs, flag, ask2) {
@@ -41055,14 +41133,14 @@ function timeAgo(dateStr) {
41055
41133
 
41056
41134
  // src/commands/connect.ts
41057
41135
  var import_node_os12 = require("os");
41058
- var import_node_fs25 = require("fs");
41059
- var import_node_path21 = require("path");
41136
+ var import_node_fs26 = require("fs");
41137
+ var import_node_path22 = require("path");
41060
41138
  var import_node_child_process5 = require("child_process");
41061
41139
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
41062
- var CONFIG_PATH3 = (0, import_node_path21.join)((0, import_node_os12.homedir)(), ".threatcrush", "config.json");
41140
+ var CONFIG_PATH3 = (0, import_node_path22.join)((0, import_node_os12.homedir)(), ".threatcrush", "config.json");
41063
41141
  function readConfig2() {
41064
41142
  try {
41065
- return JSON.parse((0, import_node_fs25.readFileSync)(CONFIG_PATH3, "utf-8"));
41143
+ return JSON.parse((0, import_node_fs26.readFileSync)(CONFIG_PATH3, "utf-8"));
41066
41144
  } catch {
41067
41145
  return {};
41068
41146
  }
@@ -41184,20 +41262,20 @@ async function resolveServer(nameOrSlug, orgSlug) {
41184
41262
  }
41185
41263
  }
41186
41264
  async function sshConnect(options) {
41187
- const { hostname: hostname4, port, username, identity } = options;
41188
- if (!hostname4) {
41265
+ const { hostname: hostname5, port, username, identity } = options;
41266
+ if (!hostname5) {
41189
41267
  console.log(source_default.red(" No hostname available for this server.\n"));
41190
41268
  return;
41191
41269
  }
41192
41270
  const user = username || "root";
41193
- console.log(source_default.green(` Connecting to ${user}@${hostname4}:${port}...
41271
+ console.log(source_default.green(` Connecting to ${user}@${hostname5}:${port}...
41194
41272
  `));
41195
41273
  console.log(source_default.dim(" (Spawning SSH session \u2014 exit with Ctrl+D or type 'exit')\n"));
41196
41274
  const sshArgs = ["-p", String(port)];
41197
41275
  if (identity) {
41198
41276
  sshArgs.push("-i", identity);
41199
41277
  }
41200
- sshArgs.push(`${user}@${hostname4}`);
41278
+ sshArgs.push(`${user}@${hostname5}`);
41201
41279
  const ssh = (0, import_node_child_process5.spawn)("ssh", sshArgs, { stdio: "inherit" });
41202
41280
  ssh.on("error", (err) => {
41203
41281
  console.log(source_default.red(`
@@ -41217,21 +41295,21 @@ async function sshConnect(options) {
41217
41295
 
41218
41296
  // src/commands/daemon.ts
41219
41297
  var import_node_child_process17 = require("child_process");
41220
- var import_node_fs43 = require("fs");
41221
- var import_node_path33 = require("path");
41222
41298
  var import_node_fs44 = require("fs");
41299
+ var import_node_path34 = require("path");
41300
+ var import_node_fs45 = require("fs");
41223
41301
 
41224
41302
  // src/daemon/index.ts
41225
- var import_node_fs42 = require("fs");
41303
+ var import_node_fs43 = require("fs");
41226
41304
  var import_node_child_process16 = require("child_process");
41227
41305
  var import_node_os13 = require("os");
41228
- var import_node_path32 = require("path");
41306
+ var import_node_path33 = require("path");
41229
41307
  var import_node_util4 = require("util");
41230
41308
  init_paths();
41231
41309
 
41232
41310
  // src/daemon/ipc-server.ts
41233
41311
  var import_node_net3 = require("net");
41234
- var import_node_fs26 = require("fs");
41312
+ var import_node_fs27 = require("fs");
41235
41313
  init_paths();
41236
41314
  init_control_token();
41237
41315
 
@@ -41285,13 +41363,13 @@ var IpcServer = class {
41285
41363
  controlToken = "";
41286
41364
  async start() {
41287
41365
  this.controlToken = issueControlToken();
41288
- if ((0, import_node_fs26.existsSync)(PATHS.socket)) {
41366
+ if ((0, import_node_fs27.existsSync)(PATHS.socket)) {
41289
41367
  try {
41290
- (0, import_node_fs26.unlinkSync)(PATHS.socket);
41368
+ (0, import_node_fs27.unlinkSync)(PATHS.socket);
41291
41369
  } catch {
41292
41370
  }
41293
41371
  }
41294
- return new Promise((resolve6, reject) => {
41372
+ return new Promise((resolve7, reject) => {
41295
41373
  this.server = (0, import_node_net3.createServer)((sock) => this.handleClient(sock));
41296
41374
  this.server.on("error", reject);
41297
41375
  this.server.listen(PATHS.socket, () => {
@@ -41310,7 +41388,7 @@ var IpcServer = class {
41310
41388
  }
41311
41389
  }
41312
41390
  }
41313
- resolve6();
41391
+ resolve7();
41314
41392
  });
41315
41393
  });
41316
41394
  }
@@ -41322,20 +41400,20 @@ var IpcServer = class {
41322
41400
  }
41323
41401
  }
41324
41402
  this.clients.clear();
41325
- return new Promise((resolve6) => {
41403
+ return new Promise((resolve7) => {
41326
41404
  if (!this.server) {
41327
41405
  try {
41328
- if ((0, import_node_fs26.existsSync)(PATHS.socket)) (0, import_node_fs26.unlinkSync)(PATHS.socket);
41406
+ if ((0, import_node_fs27.existsSync)(PATHS.socket)) (0, import_node_fs27.unlinkSync)(PATHS.socket);
41329
41407
  } catch {
41330
41408
  }
41331
- return resolve6();
41409
+ return resolve7();
41332
41410
  }
41333
41411
  this.server.close(() => {
41334
41412
  try {
41335
- if ((0, import_node_fs26.existsSync)(PATHS.socket)) (0, import_node_fs26.unlinkSync)(PATHS.socket);
41413
+ if ((0, import_node_fs27.existsSync)(PATHS.socket)) (0, import_node_fs27.unlinkSync)(PATHS.socket);
41336
41414
  } catch {
41337
41415
  }
41338
- resolve6();
41416
+ resolve7();
41339
41417
  });
41340
41418
  });
41341
41419
  }
@@ -41512,7 +41590,7 @@ var IpcServer = class {
41512
41590
  }
41513
41591
  }
41514
41592
  };
41515
- function admGid(readGroup = () => (0, import_node_fs26.readFileSync)("/etc/group", "utf-8"), statAuthLog = () => (0, import_node_fs26.statSync)("/var/log/auth.log")) {
41593
+ function admGid(readGroup = () => (0, import_node_fs27.readFileSync)("/etc/group", "utf-8"), statAuthLog = () => (0, import_node_fs27.statSync)("/var/log/auth.log")) {
41516
41594
  try {
41517
41595
  for (const line2 of readGroup().split("\n")) {
41518
41596
  const [name, , gid] = line2.split(":");
@@ -41528,14 +41606,14 @@ function admGid(readGroup = () => (0, import_node_fs26.readFileSync)("/etc/group
41528
41606
  }
41529
41607
 
41530
41608
  // src/daemon/module-host.ts
41531
- var import_node_fs32 = require("fs");
41532
- var import_node_path23 = require("path");
41609
+ var import_node_fs33 = require("fs");
41610
+ var import_node_path24 = require("path");
41533
41611
  var import_node_url = require("url");
41534
41612
  var import_toml4 = __toESM(require_toml());
41535
41613
  init_paths();
41536
41614
 
41537
41615
  // src/daemon/watchers/log-watcher.ts
41538
- var import_node_fs27 = require("fs");
41616
+ var import_node_fs28 = require("fs");
41539
41617
  var DEFAULT_SOURCES = [
41540
41618
  { path: "/var/log/auth.log", module: "ssh-guard", category: "auth" },
41541
41619
  { path: "/var/log/secure", module: "ssh-guard", category: "auth" },
@@ -41555,9 +41633,9 @@ var LogWatcher = class {
41555
41633
  start() {
41556
41634
  const started = [];
41557
41635
  for (const src of this.sources) {
41558
- if (!(0, import_node_fs27.existsSync)(src.path)) continue;
41636
+ if (!(0, import_node_fs28.existsSync)(src.path)) continue;
41559
41637
  try {
41560
- (0, import_node_fs27.accessSync)(src.path, import_node_fs27.constants.R_OK);
41638
+ (0, import_node_fs28.accessSync)(src.path, import_node_fs28.constants.R_OK);
41561
41639
  } catch {
41562
41640
  continue;
41563
41641
  }
@@ -41854,7 +41932,7 @@ function realtimeToDate(rt) {
41854
41932
 
41855
41933
  // src/modules/network-monitor/index.ts
41856
41934
  var import_node_child_process7 = require("child_process");
41857
- var import_node_fs28 = require("fs");
41935
+ var import_node_fs29 = require("fs");
41858
41936
  var NetworkMonitor = class {
41859
41937
  constructor(bus2) {
41860
41938
  this.bus = bus2;
@@ -41918,7 +41996,7 @@ var NetworkMonitor = class {
41918
41996
  hasConntrackOrSs() {
41919
41997
  const ss = (0, import_node_child_process7.spawnSync)("ss", ["--version"], { stdio: "pipe" });
41920
41998
  if (ss.status === 0) return true;
41921
- return (0, import_node_fs28.existsSync)("/proc/net/tcp");
41999
+ return (0, import_node_fs29.existsSync)("/proc/net/tcp");
41922
42000
  }
41923
42001
  /**
41924
42002
  * The TCP ports this host actually listens on.
@@ -42105,18 +42183,18 @@ var NetworkMonitor = class {
42105
42183
  };
42106
42184
 
42107
42185
  // src/modules/dns-monitor/index.ts
42108
- var import_node_fs31 = require("fs");
42186
+ var import_node_fs32 = require("fs");
42109
42187
  var import_node_child_process9 = require("child_process");
42110
42188
  var import_node_readline3 = require("readline");
42111
42189
 
42112
42190
  // src/core/threat-feeds/index.ts
42113
- var import_node_fs30 = require("fs");
42114
- var import_node_path22 = require("path");
42191
+ var import_node_fs31 = require("fs");
42192
+ var import_node_path23 = require("path");
42115
42193
  var import_node_net5 = require("net");
42116
42194
 
42117
42195
  // src/daemon/firewall/protected.ts
42118
42196
  var import_node_child_process8 = require("child_process");
42119
- var import_node_fs29 = require("fs");
42197
+ var import_node_fs30 = require("fs");
42120
42198
  var import_node_net4 = require("net");
42121
42199
  var DEFAULT_PROTECTED = [
42122
42200
  "127.0.0.0/8",
@@ -42272,14 +42350,14 @@ function moshClients(procDir = "/proc") {
42272
42350
  const found = /* @__PURE__ */ new Set();
42273
42351
  let pids = [];
42274
42352
  try {
42275
- pids = (0, import_node_fs29.readdirSync)(procDir).filter((p) => /^\d+$/.test(p));
42353
+ pids = (0, import_node_fs30.readdirSync)(procDir).filter((p) => /^\d+$/.test(p));
42276
42354
  } catch {
42277
42355
  return [];
42278
42356
  }
42279
42357
  for (const pid of pids) {
42280
42358
  try {
42281
- if ((0, import_node_fs29.readFileSync)(`${procDir}/${pid}/comm`, "utf-8").trim() !== "mosh-server") continue;
42282
- const ip = sshClientFromEnviron((0, import_node_fs29.readFileSync)(`${procDir}/${pid}/environ`, "latin1"));
42359
+ if ((0, import_node_fs30.readFileSync)(`${procDir}/${pid}/comm`, "utf-8").trim() !== "mosh-server") continue;
42360
+ const ip = sshClientFromEnviron((0, import_node_fs30.readFileSync)(`${procDir}/${pid}/environ`, "latin1"));
42283
42361
  if (ip) found.add(ip);
42284
42362
  } catch {
42285
42363
  }
@@ -42485,17 +42563,17 @@ async function fetchFeeds(settings, fetchImpl = fetch) {
42485
42563
  }
42486
42564
  function readFeedCache(path2) {
42487
42565
  try {
42488
- const set = JSON.parse((0, import_node_fs30.readFileSync)(path2, "utf-8"));
42566
+ const set = JSON.parse((0, import_node_fs31.readFileSync)(path2, "utf-8"));
42489
42567
  return set && typeof set.ips === "object" && typeof set.domains === "object" ? set : null;
42490
42568
  } catch {
42491
42569
  return null;
42492
42570
  }
42493
42571
  }
42494
42572
  function writeFeedCache(path2, set) {
42495
- (0, import_node_fs30.mkdirSync)((0, import_node_path22.dirname)(path2), { recursive: true });
42573
+ (0, import_node_fs31.mkdirSync)((0, import_node_path23.dirname)(path2), { recursive: true });
42496
42574
  const tmp = `${path2}.tmp`;
42497
- (0, import_node_fs30.writeFileSync)(tmp, JSON.stringify(set));
42498
- (0, import_node_fs30.renameSync)(tmp, path2);
42575
+ (0, import_node_fs31.writeFileSync)(tmp, JSON.stringify(set));
42576
+ (0, import_node_fs31.renameSync)(tmp, path2);
42499
42577
  }
42500
42578
  var RESOLVER_FILES = {
42501
42579
  hosts: "blocked-domains.hosts",
@@ -42620,9 +42698,9 @@ var DnsMonitor = class {
42620
42698
  }
42621
42699
  start() {
42622
42700
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
42623
- if (!(0, import_node_fs31.existsSync)(p)) return false;
42701
+ if (!(0, import_node_fs32.existsSync)(p)) return false;
42624
42702
  try {
42625
- (0, import_node_fs31.accessSync)(p, import_node_fs31.constants.R_OK);
42703
+ (0, import_node_fs32.accessSync)(p, import_node_fs32.constants.R_OK);
42626
42704
  return true;
42627
42705
  } catch {
42628
42706
  return false;
@@ -42979,15 +43057,15 @@ var ModuleHost = class {
42979
43057
  }
42980
43058
  }
42981
43059
  async discoverAndStartInstalled() {
42982
- if (!(0, import_node_fs32.existsSync)(PATHS.moduleDir)) return;
43060
+ if (!(0, import_node_fs33.existsSync)(PATHS.moduleDir)) return;
42983
43061
  const configs = loadModuleConfigs(PATHS.confD);
42984
- const entries = (0, import_node_fs32.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
43062
+ const entries = (0, import_node_fs33.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
42985
43063
  for (const entry of entries) {
42986
43064
  if (!entry.isDirectory()) continue;
42987
- const manifestPath = (0, import_node_path23.join)(PATHS.moduleDir, entry.name, "mod.toml");
42988
- if (!(0, import_node_fs32.existsSync)(manifestPath)) continue;
43065
+ const manifestPath = (0, import_node_path24.join)(PATHS.moduleDir, entry.name, "mod.toml");
43066
+ if (!(0, import_node_fs33.existsSync)(manifestPath)) continue;
42989
43067
  try {
42990
- const manifest = import_toml4.default.parse((0, import_node_fs32.readFileSync)(manifestPath, "utf-8"));
43068
+ const manifest = import_toml4.default.parse((0, import_node_fs33.readFileSync)(manifestPath, "utf-8"));
42991
43069
  const name = manifest.module?.name || entry.name;
42992
43070
  const defaults = manifest.module?.config?.defaults || {};
42993
43071
  const config = {
@@ -43001,7 +43079,7 @@ var ModuleHost = class {
43001
43079
  source: "installed",
43002
43080
  status: config.enabled === false ? "disabled" : "loaded",
43003
43081
  events: 0,
43004
- path: (0, import_node_path23.join)(PATHS.moduleDir, entry.name),
43082
+ path: (0, import_node_path24.join)(PATHS.moduleDir, entry.name),
43005
43083
  config
43006
43084
  };
43007
43085
  this.modules.set(name, hosted);
@@ -43016,7 +43094,7 @@ var ModuleHost = class {
43016
43094
  status: "error",
43017
43095
  events: 0,
43018
43096
  detail: `manifest load failed: ${String(err.message || err)}`,
43019
- path: (0, import_node_path23.join)(PATHS.moduleDir, entry.name)
43097
+ path: (0, import_node_path24.join)(PATHS.moduleDir, entry.name)
43020
43098
  });
43021
43099
  }
43022
43100
  }
@@ -43055,17 +43133,17 @@ var ModuleHost = class {
43055
43133
  }
43056
43134
  }
43057
43135
  installedEntrypoint(modulePath) {
43058
- const packageJson = (0, import_node_path23.join)(modulePath, "package.json");
43136
+ const packageJson = (0, import_node_path24.join)(modulePath, "package.json");
43059
43137
  const candidates = [];
43060
- if ((0, import_node_fs32.existsSync)(packageJson)) {
43138
+ if ((0, import_node_fs33.existsSync)(packageJson)) {
43061
43139
  try {
43062
- const pkg = JSON.parse((0, import_node_fs32.readFileSync)(packageJson, "utf-8"));
43063
- if (pkg.main) candidates.push((0, import_node_path23.join)(modulePath, pkg.main));
43140
+ const pkg = JSON.parse((0, import_node_fs33.readFileSync)(packageJson, "utf-8"));
43141
+ if (pkg.main) candidates.push((0, import_node_path24.join)(modulePath, pkg.main));
43064
43142
  } catch {
43065
43143
  }
43066
43144
  }
43067
- candidates.push((0, import_node_path23.join)(modulePath, "dist", "index.js"), (0, import_node_path23.join)(modulePath, "index.js"));
43068
- return candidates.find((candidate) => (0, import_node_fs32.existsSync)(candidate)) || null;
43145
+ candidates.push((0, import_node_path24.join)(modulePath, "dist", "index.js"), (0, import_node_path24.join)(modulePath, "index.js"));
43146
+ return candidates.find((candidate) => (0, import_node_fs33.existsSync)(candidate)) || null;
43069
43147
  }
43070
43148
  isThreatCrushModule(value) {
43071
43149
  return Boolean(
@@ -43473,7 +43551,7 @@ var RunsWorker = class {
43473
43551
  init_cli_config();
43474
43552
 
43475
43553
  // src/core/cloud-events.ts
43476
- var import_node_crypto6 = require("crypto");
43554
+ var import_node_crypto7 = require("crypto");
43477
43555
  var import_node_net6 = require("net");
43478
43556
  init_cli_config();
43479
43557
  function currentLink() {
@@ -43547,7 +43625,7 @@ function remediationEvent(serverId, event) {
43547
43625
  return {
43548
43626
  type: "remediation",
43549
43627
  server_id: serverId,
43550
- event_id: (0, import_node_crypto6.randomUUID)(),
43628
+ event_id: (0, import_node_crypto7.randomUUID)(),
43551
43629
  action_type: d.action,
43552
43630
  target_value: event.source_ip,
43553
43631
  status: d.failed === true ? "failed" : "executed",
@@ -43574,16 +43652,16 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
43574
43652
  }
43575
43653
 
43576
43654
  // src/daemon/workers/cloud-spool.ts
43577
- var import_node_fs33 = require("fs");
43655
+ var import_node_fs34 = require("fs");
43578
43656
  var import_promises = require("fs/promises");
43579
- var import_node_path24 = require("path");
43657
+ var import_node_path25 = require("path");
43580
43658
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
43581
43659
  var CloudSpool = class {
43582
43660
  constructor(path2, limits = DEFAULT_SPOOL_LIMITS) {
43583
43661
  this.path = path2;
43584
43662
  this.limits = limits;
43585
43663
  try {
43586
- (0, import_node_fs33.mkdirSync)((0, import_node_path24.dirname)(path2), { recursive: true });
43664
+ (0, import_node_fs34.mkdirSync)((0, import_node_path25.dirname)(path2), { recursive: true });
43587
43665
  } catch {
43588
43666
  }
43589
43667
  this.load();
@@ -43652,7 +43730,7 @@ var CloudSpool = class {
43652
43730
  load() {
43653
43731
  let raw;
43654
43732
  try {
43655
- raw = (0, import_node_fs33.readFileSync)(this.path, "utf-8");
43733
+ raw = (0, import_node_fs34.readFileSync)(this.path, "utf-8");
43656
43734
  } catch {
43657
43735
  return;
43658
43736
  }
@@ -43890,7 +43968,7 @@ var CloudSync = class {
43890
43968
  };
43891
43969
 
43892
43970
  // src/daemon/workers/abuse-reporter.ts
43893
- var import_node_crypto7 = require("crypto");
43971
+ var import_node_crypto8 = require("crypto");
43894
43972
 
43895
43973
  // src/daemon/workers/abuse-evidence.ts
43896
43974
  var import_node_net7 = require("net");
@@ -44119,32 +44197,32 @@ function resolveConfig(section) {
44119
44197
  }
44120
44198
 
44121
44199
  // src/core/abuse-report-log.ts
44122
- var import_node_fs34 = require("fs");
44123
- var import_node_path25 = require("path");
44200
+ var import_node_fs35 = require("fs");
44201
+ var import_node_path26 = require("path");
44124
44202
  init_paths();
44125
44203
  var ABUSE_DIRNAME = "abuse-reports";
44126
44204
  var LOG_FILE2 = "reports.jsonl";
44127
44205
  function resolveAbuseDir(dir) {
44128
44206
  if (dir) return dir;
44129
44207
  if (process.env.THREATCRUSH_ABUSE_DIR) return process.env.THREATCRUSH_ABUSE_DIR;
44130
- const system = (0, import_node_path25.join)("/var/lib/threatcrush", ABUSE_DIRNAME);
44131
- if ((0, import_node_fs34.existsSync)(system)) return system;
44132
- return (0, import_node_path25.join)(PATHS.stateDir, ABUSE_DIRNAME);
44208
+ const system = (0, import_node_path26.join)("/var/lib/threatcrush", ABUSE_DIRNAME);
44209
+ if ((0, import_node_fs35.existsSync)(system)) return system;
44210
+ return (0, import_node_path26.join)(PATHS.stateDir, ABUSE_DIRNAME);
44133
44211
  }
44134
44212
  function logPath(dir) {
44135
- return (0, import_node_path25.join)(resolveAbuseDir(dir), LOG_FILE2);
44213
+ return (0, import_node_path26.join)(resolveAbuseDir(dir), LOG_FILE2);
44136
44214
  }
44137
44215
  function appendReport(record, dir) {
44138
44216
  const path2 = logPath(dir);
44139
- (0, import_node_fs34.mkdirSync)(resolveAbuseDir(dir), { recursive: true, mode: 493 });
44140
- (0, import_node_fs34.appendFileSync)(path2, `${JSON.stringify(record)}
44217
+ (0, import_node_fs35.mkdirSync)(resolveAbuseDir(dir), { recursive: true, mode: 493 });
44218
+ (0, import_node_fs35.appendFileSync)(path2, `${JSON.stringify(record)}
44141
44219
  `, { mode: 420 });
44142
44220
  }
44143
44221
  function readReports(dir) {
44144
44222
  const path2 = logPath(dir);
44145
44223
  let raw;
44146
44224
  try {
44147
- raw = (0, import_node_fs34.readFileSync)(path2, "utf-8");
44225
+ raw = (0, import_node_fs35.readFileSync)(path2, "utf-8");
44148
44226
  } catch {
44149
44227
  return [];
44150
44228
  }
@@ -44283,7 +44361,7 @@ var AbuseReporter = class {
44283
44361
  const payload = buildPayload(ip, evidence);
44284
44362
  const results = this.cfg.dryRun ? [] : await dispatch(payload, this.cfg.destinations, this.cfg.keys);
44285
44363
  const record = {
44286
- id: (0, import_node_crypto7.randomUUID)().slice(0, 8),
44364
+ id: (0, import_node_crypto8.randomUUID)().slice(0, 8),
44287
44365
  ip,
44288
44366
  reported_at: new Date(now).toISOString(),
44289
44367
  mode: this.cfg.dryRun ? "dry_run" : "live",
@@ -44541,8 +44619,8 @@ var RemediationConsumer = class {
44541
44619
 
44542
44620
  // src/daemon/workers/auto-update.ts
44543
44621
  var import_node_child_process10 = require("child_process");
44544
- var import_node_fs35 = require("fs");
44545
- var import_node_path26 = require("path");
44622
+ var import_node_fs36 = require("fs");
44623
+ var import_node_path27 = require("path");
44546
44624
  init_backoff();
44547
44625
  var PKG_NAME = "@profullstack/threatcrush";
44548
44626
  var REGISTRY = `https://registry.npmjs.org/${PKG_NAME}`;
@@ -44586,12 +44664,12 @@ function pickUpdate(doc, current, opts) {
44586
44664
  return { version: null, reason: `${latest} is younger than min_age, and nothing older is newer than ${current}; waiting` };
44587
44665
  }
44588
44666
  function installPlan(opts) {
44589
- const expected = `${import_node_path26.sep}lib${import_node_path26.sep}node_modules${import_node_path26.sep}@profullstack${import_node_path26.sep}threatcrush`;
44667
+ const expected = `${import_node_path27.sep}lib${import_node_path27.sep}node_modules${import_node_path27.sep}@profullstack${import_node_path27.sep}threatcrush`;
44590
44668
  if (!opts.pkgRoot.endsWith(expected)) {
44591
44669
  return { kind: "unsupported", reason: `not an npm global install (${opts.pkgRoot}); run \`threatcrush update\`` };
44592
44670
  }
44593
- const nodeBin = (0, import_node_path26.dirname)(opts.execPath);
44594
- const npm = (0, import_node_path26.join)(nodeBin, "npm");
44671
+ const nodeBin = (0, import_node_path27.dirname)(opts.execPath);
44672
+ const npm = (0, import_node_path27.join)(nodeBin, "npm");
44595
44673
  if (!opts.npmExists(npm)) return { kind: "unsupported", reason: `no npm beside ${opts.execPath}` };
44596
44674
  if (!opts.owner) return { kind: "unsupported", reason: `cannot tell who owns ${opts.pkgRoot}` };
44597
44675
  const npmArgs = [npm, "i", "-g", `${PKG_NAME}@${opts.version}`, "--no-fund", "--no-audit"];
@@ -44623,10 +44701,10 @@ function installPlan(opts) {
44623
44701
  }
44624
44702
  function ownerOf(path2, passwd = "/etc/passwd") {
44625
44703
  try {
44626
- const st = (0, import_node_fs35.statSync)(path2);
44704
+ const st = (0, import_node_fs36.statSync)(path2);
44627
44705
  let home = st.uid === 0 ? "/root" : "";
44628
44706
  try {
44629
- for (const line2 of (0, import_node_fs35.readFileSync)(passwd, "utf8").split("\n")) {
44707
+ for (const line2 of (0, import_node_fs36.readFileSync)(passwd, "utf8").split("\n")) {
44630
44708
  const f = line2.split(":");
44631
44709
  if (Number(f[2]) === st.uid && f[5]) home = f[5];
44632
44710
  }
@@ -44648,7 +44726,7 @@ function updateSettings(section, env3 = process.env) {
44648
44726
  };
44649
44727
  }
44650
44728
  function defaultRun(argv, env3) {
44651
- return new Promise((resolve6) => {
44729
+ return new Promise((resolve7) => {
44652
44730
  const child = (0, import_node_child_process10.spawn)(argv[0], argv.slice(1), {
44653
44731
  env: { ...process.env, ...env3 },
44654
44732
  stdio: ["ignore", "pipe", "pipe"]
@@ -44659,8 +44737,8 @@ function defaultRun(argv, env3) {
44659
44737
  };
44660
44738
  child.stdout?.on("data", keep);
44661
44739
  child.stderr?.on("data", keep);
44662
- child.on("error", (err) => resolve6({ code: -1, output: err.message }));
44663
- child.on("close", (code) => resolve6({ code: code ?? -1, output }));
44740
+ child.on("error", (err) => resolve7({ code: -1, output: err.message }));
44741
+ child.on("close", (code) => resolve7({ code: code ?? -1, output }));
44664
44742
  });
44665
44743
  }
44666
44744
  var AutoUpdate = class {
@@ -44731,7 +44809,7 @@ var AutoUpdate = class {
44731
44809
  uid: process.getuid?.() ?? -1,
44732
44810
  owner: ownerOf(this.opts.pkgRoot),
44733
44811
  underSystemd: this.opts.underSystemd ?? Boolean(process.env.INVOCATION_ID),
44734
- npmExists: import_node_fs35.existsSync
44812
+ npmExists: import_node_fs36.existsSync
44735
44813
  });
44736
44814
  if (plan.kind === "unsupported") return this.note(`${target} is available but cannot self-install: ${plan.reason}`);
44737
44815
  this.recordAttempt(target);
@@ -44766,7 +44844,7 @@ var AutoUpdate = class {
44766
44844
  }
44767
44845
  lastAttempt() {
44768
44846
  try {
44769
- const v = JSON.parse((0, import_node_fs35.readFileSync)(this.opts.statePath, "utf8"));
44847
+ const v = JSON.parse((0, import_node_fs36.readFileSync)(this.opts.statePath, "utf8"));
44770
44848
  return v.version && typeof v.at === "number" ? { version: v.version, at: v.at } : null;
44771
44849
  } catch {
44772
44850
  return null;
@@ -44774,7 +44852,7 @@ var AutoUpdate = class {
44774
44852
  }
44775
44853
  recordAttempt(version) {
44776
44854
  try {
44777
- (0, import_node_fs35.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
44855
+ (0, import_node_fs36.writeFileSync)(this.opts.statePath, JSON.stringify({ version, at: this.now() }));
44778
44856
  } catch (err) {
44779
44857
  this.opts.log(`[update] could not record attempt: ${err.message}`);
44780
44858
  }
@@ -44783,8 +44861,8 @@ var AutoUpdate = class {
44783
44861
 
44784
44862
  // src/daemon/workers/threat-feeds.ts
44785
44863
  var import_node_child_process11 = require("child_process");
44786
- var import_node_fs36 = require("fs");
44787
- var import_node_path27 = require("path");
44864
+ var import_node_fs37 = require("fs");
44865
+ var import_node_path28 = require("path");
44788
44866
  var import_node_net10 = require("net");
44789
44867
  init_backoff();
44790
44868
  var EGRESS_TABLE = "threatcrush_egress";
@@ -44956,14 +45034,14 @@ var ThreatFeeds = class {
44956
45034
  */
44957
45035
  writeResolverFiles(set) {
44958
45036
  const domains = this.wantsDomainBlock ? Object.keys(set.domains).sort() : [];
44959
- const dir = this.opts.resolverDir ?? (0, import_node_path27.dirname)(this.opts.cachePath);
45037
+ const dir = this.opts.resolverDir ?? (0, import_node_path28.dirname)(this.opts.cachePath);
44960
45038
  const hooks = this.opts.resolverHooks ?? RESOLVER_HOOKS;
44961
45039
  const write = (name, content) => {
44962
- const path2 = (0, import_node_path27.join)(dir, name);
45040
+ const path2 = (0, import_node_path28.join)(dir, name);
44963
45041
  if (this.resolverWritten.get(name) === content) return false;
44964
45042
  try {
44965
- (0, import_node_fs36.writeFileSync)(`${path2}.tmp`, content);
44966
- (0, import_node_fs36.renameSync)(`${path2}.tmp`, path2);
45043
+ (0, import_node_fs37.writeFileSync)(`${path2}.tmp`, content);
45044
+ (0, import_node_fs37.renameSync)(`${path2}.tmp`, path2);
44967
45045
  this.resolverWritten.set(name, content);
44968
45046
  return true;
44969
45047
  } catch (err) {
@@ -44974,11 +45052,11 @@ var ThreatFeeds = class {
44974
45052
  const hostsChanged = write(RESOLVER_FILES.hosts, hostsBlocklist(domains));
44975
45053
  const unboundChanged = write(RESOLVER_FILES.unbound, unboundBlocklist(domains));
44976
45054
  const via = [];
44977
- if ((0, import_node_fs36.existsSync)(hooks.dnsmasq)) {
45055
+ if ((0, import_node_fs37.existsSync)(hooks.dnsmasq)) {
44978
45056
  via.push("dnsmasq");
44979
45057
  if (hostsChanged) this.run("systemctl", ["kill", "-s", "HUP", "dnsmasq.service"]);
44980
45058
  }
44981
- if ((0, import_node_fs36.existsSync)(hooks.unbound)) {
45059
+ if ((0, import_node_fs37.existsSync)(hooks.unbound)) {
44982
45060
  via.push("unbound");
44983
45061
  if (unboundChanged && this.run("unbound-control", ["reload"]) === null) {
44984
45062
  this.run("systemctl", ["reload", "unbound.service"]);
@@ -45039,12 +45117,12 @@ var ThreatFeeds = class {
45039
45117
  };
45040
45118
 
45041
45119
  // src/daemon/workers/privilege-watch.ts
45042
- var import_node_fs37 = require("fs");
45043
- var import_node_path28 = require("path");
45120
+ var import_node_fs38 = require("fs");
45121
+ var import_node_path29 = require("path");
45044
45122
  var import_node_child_process12 = require("child_process");
45045
45123
 
45046
45124
  // src/core/privileges/index.ts
45047
- var import_node_crypto8 = require("crypto");
45125
+ var import_node_crypto9 = require("crypto");
45048
45126
  var ADMIN_GROUPS = ["sudo", "wheel", "admin"];
45049
45127
  function parseUsers(text) {
45050
45128
  const out = [];
@@ -45085,7 +45163,7 @@ function sudoReadsIncluded(name) {
45085
45163
  }
45086
45164
  function keyFingerprint(blobBase64) {
45087
45165
  if (!/^[A-Za-z0-9+/]+=*$/.test(blobBase64)) return null;
45088
- const digest = (0, import_node_crypto8.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
45166
+ const digest = (0, import_node_crypto9.createHash)("sha256").update(Buffer.from(blobBase64, "base64")).digest("base64");
45089
45167
  return `SHA256:${digest.replace(/=+$/, "")}`;
45090
45168
  }
45091
45169
  function parseAuthorizedKeys(text) {
@@ -45231,31 +45309,31 @@ function countryName(code) {
45231
45309
  var fsIO = {
45232
45310
  readFile: (p) => {
45233
45311
  try {
45234
- return (0, import_node_fs37.readFileSync)(p, "utf-8");
45312
+ return (0, import_node_fs38.readFileSync)(p, "utf-8");
45235
45313
  } catch {
45236
45314
  return null;
45237
45315
  }
45238
45316
  },
45239
45317
  readDir: (p) => {
45240
45318
  try {
45241
- return (0, import_node_fs37.readdirSync)(p);
45319
+ return (0, import_node_fs38.readdirSync)(p);
45242
45320
  } catch {
45243
45321
  return null;
45244
45322
  }
45245
45323
  },
45246
- exists: (p) => (0, import_node_fs37.existsSync)(p)
45324
+ exists: (p) => (0, import_node_fs38.existsSync)(p)
45247
45325
  };
45248
45326
  function readJson(path2) {
45249
45327
  try {
45250
- return JSON.parse((0, import_node_fs37.readFileSync)(path2, "utf-8"));
45328
+ return JSON.parse((0, import_node_fs38.readFileSync)(path2, "utf-8"));
45251
45329
  } catch {
45252
45330
  return null;
45253
45331
  }
45254
45332
  }
45255
45333
  function writeJson(path2, value) {
45256
- (0, import_node_fs37.mkdirSync)((0, import_node_path28.dirname)(path2), { recursive: true });
45257
- (0, import_node_fs37.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
45258
- (0, import_node_fs37.renameSync)(`${path2}.tmp`, path2);
45334
+ (0, import_node_fs38.mkdirSync)((0, import_node_path29.dirname)(path2), { recursive: true });
45335
+ (0, import_node_fs38.writeFileSync)(`${path2}.tmp`, JSON.stringify(value));
45336
+ (0, import_node_fs38.renameSync)(`${path2}.tmp`, path2);
45259
45337
  }
45260
45338
  function defaultRun3(cmd, args) {
45261
45339
  const res = (0, import_node_child_process12.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 2e4, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
@@ -45411,7 +45489,7 @@ var PrivilegeWatch = class {
45411
45489
  * raised a "new country" alert on its first run; on dev2 it did, at once.
45412
45490
  */
45413
45491
  async backfillLogins() {
45414
- if ((0, import_node_fs37.existsSync)(this.opts.loginsPath)) return;
45492
+ if ((0, import_node_fs38.existsSync)(this.opts.loginsPath)) return;
45415
45493
  const out = this.run("journalctl", ["_COMM=sshd", "_COMM=sshd-session", "--since=-30d", "-o", "cat", "--no-pager"]);
45416
45494
  const byUser = parseAcceptedLogins(out ?? "");
45417
45495
  const ips = [...new Set([...byUser.values()].flatMap((s) => [...s]))];
@@ -45424,7 +45502,7 @@ var PrivilegeWatch = class {
45424
45502
  return;
45425
45503
  }
45426
45504
  }
45427
- if ((0, import_node_fs37.existsSync)(this.opts.loginsPath)) return;
45505
+ if ((0, import_node_fs38.existsSync)(this.opts.loginsPath)) return;
45428
45506
  const at = this.now().toISOString();
45429
45507
  const history = {};
45430
45508
  for (const [user, userIps] of byUser) {
@@ -45636,8 +45714,8 @@ var RuleEngine = class {
45636
45714
  };
45637
45715
 
45638
45716
  // src/daemon/rules/loader.ts
45639
- var import_node_fs38 = require("fs");
45640
- var import_node_path29 = require("path");
45717
+ var import_node_fs39 = require("fs");
45718
+ var import_node_path30 = require("path");
45641
45719
 
45642
45720
  // src/daemon/rules/default-rules.ts
45643
45721
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -46107,11 +46185,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
46107
46185
  function loadAllRules(customDir) {
46108
46186
  const rules = [...DEFAULT_RULES];
46109
46187
  const dir = customDir || RULES_DIR;
46110
- if ((0, import_node_fs38.existsSync)(dir)) {
46111
- const files = (0, import_node_fs38.readdirSync)(dir).filter((f) => f.endsWith(".json"));
46188
+ if ((0, import_node_fs39.existsSync)(dir)) {
46189
+ const files = (0, import_node_fs39.readdirSync)(dir).filter((f) => f.endsWith(".json"));
46112
46190
  for (const file of files) {
46113
46191
  try {
46114
- const raw = (0, import_node_fs38.readFileSync)((0, import_node_path29.join)(dir, file), "utf-8");
46192
+ const raw = (0, import_node_fs39.readFileSync)((0, import_node_path30.join)(dir, file), "utf-8");
46115
46193
  const parsed = JSON.parse(raw);
46116
46194
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
46117
46195
  for (const rule of customRules) {
@@ -46143,8 +46221,8 @@ function loadAllRules(customDir) {
46143
46221
 
46144
46222
  // src/daemon/firewall/adapters.ts
46145
46223
  var import_node_child_process13 = require("child_process");
46146
- var import_node_fs39 = require("fs");
46147
- var import_node_path30 = require("path");
46224
+ var import_node_fs40 = require("fs");
46225
+ var import_node_path31 = require("path");
46148
46226
  var import_node_net11 = require("net");
46149
46227
  function assertValidFirewallIp(ip) {
46150
46228
  if ((0, import_node_net11.isIP)(ip) !== 4) {
@@ -46157,9 +46235,9 @@ function assertBannableIp(ip) {
46157
46235
  }
46158
46236
  }
46159
46237
  function writeIfAbsent(path2, contents) {
46160
- (0, import_node_fs39.mkdirSync)((0, import_node_path30.dirname)(path2), { recursive: true });
46238
+ (0, import_node_fs40.mkdirSync)((0, import_node_path31.dirname)(path2), { recursive: true });
46161
46239
  try {
46162
- (0, import_node_fs39.writeFileSync)(path2, contents, { flag: "wx" });
46240
+ (0, import_node_fs40.writeFileSync)(path2, contents, { flag: "wx" });
46163
46241
  } catch (err) {
46164
46242
  if (err.code !== "EEXIST") throw err;
46165
46243
  }
@@ -46418,7 +46496,7 @@ function detectFirewallAdapter(backend = "auto") {
46418
46496
  }
46419
46497
 
46420
46498
  // src/daemon/firewall/remediation.ts
46421
- var import_node_fs40 = require("fs");
46499
+ var import_node_fs41 = require("fs");
46422
46500
  var import_node_child_process14 = require("child_process");
46423
46501
  var import_node_net12 = require("net");
46424
46502
  init_paths();
@@ -46489,19 +46567,19 @@ var defaultDiscovery = {
46489
46567
  const snapshot = takeSnapshot({
46490
46568
  readFile: (p) => {
46491
46569
  try {
46492
- return (0, import_node_fs40.readFileSync)(p, "utf-8");
46570
+ return (0, import_node_fs41.readFileSync)(p, "utf-8");
46493
46571
  } catch {
46494
46572
  return null;
46495
46573
  }
46496
46574
  },
46497
46575
  readDir: (p) => {
46498
46576
  try {
46499
- return (0, import_node_fs40.readdirSync)(p);
46577
+ return (0, import_node_fs41.readdirSync)(p);
46500
46578
  } catch {
46501
46579
  return null;
46502
46580
  }
46503
46581
  },
46504
- exists: (p) => (0, import_node_fs40.existsSync)(p)
46582
+ exists: (p) => (0, import_node_fs41.existsSync)(p)
46505
46583
  });
46506
46584
  const out = /* @__PURE__ */ new Set();
46507
46585
  for (const keys of Object.values(snapshot.keys)) {
@@ -46509,12 +46587,12 @@ var defaultDiscovery = {
46509
46587
  }
46510
46588
  return out;
46511
46589
  },
46512
- keyLoginJournal: (sinceSeconds) => new Promise((resolve6) => {
46590
+ keyLoginJournal: (sinceSeconds) => new Promise((resolve7) => {
46513
46591
  (0, import_node_child_process14.execFile)(
46514
46592
  "journalctl",
46515
46593
  ["_COMM=sshd", "_COMM=sshd-session", `--since=-${Math.ceil(sinceSeconds / 86400)}d`, "-o", "short-unix", "--no-pager", "--grep", "Accepted publickey"],
46516
46594
  { maxBuffer: 32 * 1024 * 1024, timeout: 6e4 },
46517
- (_err, stdout) => resolve6(stdout ?? "")
46595
+ (_err, stdout) => resolve7(stdout ?? "")
46518
46596
  );
46519
46597
  })
46520
46598
  };
@@ -46942,7 +47020,7 @@ var RemediationManager = class {
46942
47020
  }
46943
47021
  logLine(line2) {
46944
47022
  try {
46945
- (0, import_node_fs40.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
47023
+ (0, import_node_fs41.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
46946
47024
  `);
46947
47025
  } catch {
46948
47026
  }
@@ -46985,19 +47063,19 @@ function remediationSettings(section) {
46985
47063
  init_backoff();
46986
47064
 
46987
47065
  // src/daemon/watchdog-service.ts
46988
- var import_node_fs41 = require("fs");
46989
- var import_node_path31 = require("path");
47066
+ var import_node_fs42 = require("fs");
47067
+ var import_node_path32 = require("path");
46990
47068
  function defaultShareGid() {
46991
47069
  const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
46992
47070
  if (!isRoot4) return void 0;
46993
47071
  try {
46994
- return (0, import_node_fs41.statSync)("/var/log/auth.log").gid;
47072
+ return (0, import_node_fs42.statSync)("/var/log/auth.log").gid;
46995
47073
  } catch {
46996
47074
  return void 0;
46997
47075
  }
46998
47076
  }
46999
47077
  function startWatchdog(opts) {
47000
- const dir = opts.config?.dir ?? (0, import_node_path31.join)(opts.stateDir, WATCHDOG_DIRNAME);
47078
+ const dir = opts.config?.dir ?? (0, import_node_path32.join)(opts.stateDir, WATCHDOG_DIRNAME);
47001
47079
  const base = { dir, logged: 0, answered: 0, errored: 0 };
47002
47080
  if (opts.config?.enabled === false) {
47003
47081
  opts.log("[watchdog] off ([watchdog] enabled = false)");
@@ -47112,7 +47190,7 @@ function versionOfNode(path2) {
47112
47190
  // src/daemon/index.ts
47113
47191
  function readVersion2() {
47114
47192
  try {
47115
- const pkg = JSON.parse((0, import_node_fs42.readFileSync)((0, import_node_path32.join)(__dirname, "..", "package.json"), "utf-8"));
47193
+ const pkg = JSON.parse((0, import_node_fs43.readFileSync)((0, import_node_path33.join)(__dirname, "..", "package.json"), "utf-8"));
47116
47194
  return pkg.version || "0.0.0";
47117
47195
  } catch {
47118
47196
  return "0.0.0";
@@ -47121,21 +47199,21 @@ function readVersion2() {
47121
47199
  async function runHardeningChecks() {
47122
47200
  const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process16.execFile)(
47123
47201
  process.execPath,
47124
- [(0, import_node_path32.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
47202
+ [(0, import_node_path33.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
47125
47203
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
47126
47204
  );
47127
47205
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
47128
- const findings = Array.isArray(parsed.findings) ? parsed.findings : [];
47206
+ const findings2 = Array.isArray(parsed.findings) ? parsed.findings : [];
47129
47207
  const patches = await runPatchCheck().catch((err) => {
47130
47208
  logLine(`[cloud] patch check failed: ${err.message.split("\n")[0]}`);
47131
47209
  return null;
47132
47210
  });
47133
- return patches ? [...findings, patches] : findings;
47211
+ return patches ? [...findings2, patches] : findings2;
47134
47212
  }
47135
47213
  async function runPatchCheck() {
47136
47214
  const { stdout } = await (0, import_node_util4.promisify)(import_node_child_process16.execFile)(
47137
47215
  process.execPath,
47138
- [(0, import_node_path32.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
47216
+ [(0, import_node_path33.join)(__dirname, "index.js"), "patches", "--json", "--no-upload"],
47139
47217
  { timeout: 3e5, maxBuffer: 16 * 1024 * 1024 }
47140
47218
  );
47141
47219
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -47143,7 +47221,7 @@ async function runPatchCheck() {
47143
47221
  }
47144
47222
  function logLine(line2) {
47145
47223
  try {
47146
- (0, import_node_fs42.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
47224
+ (0, import_node_fs43.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line2}
47147
47225
  `);
47148
47226
  } catch {
47149
47227
  }
@@ -47185,7 +47263,7 @@ async function runDaemon() {
47185
47263
  } catch (err) {
47186
47264
  logLine(`[daemon] state db unavailable: ${err.message}`);
47187
47265
  }
47188
- const config = loadConfig((0, import_node_fs42.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
47266
+ const config = loadConfig((0, import_node_fs43.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
47189
47267
  configureAttackDetection(config.detection);
47190
47268
  const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
47191
47269
  const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
@@ -47249,7 +47327,7 @@ async function runDaemon() {
47249
47327
  const threatFeeds = new ThreatFeeds({
47250
47328
  settings: { ...feedSettings, allow: [...feedSettings.allow, ...remediation.getAllowlist()] },
47251
47329
  enforcing: !remediationStatus.dry_run && firewallAdapter.enforces !== false,
47252
- cachePath: (0, import_node_path32.join)(PATHS.stateDir, "threat-feeds.json"),
47330
+ cachePath: (0, import_node_path33.join)(PATHS.stateDir, "threat-feeds.json"),
47253
47331
  bus,
47254
47332
  log: logLine
47255
47333
  });
@@ -47257,9 +47335,9 @@ async function runDaemon() {
47257
47335
  const privilegeWatch = new PrivilegeWatch({
47258
47336
  settings: privilegeSettings(config.privileged),
47259
47337
  bus,
47260
- snapshotPath: (0, import_node_path32.join)(PATHS.stateDir, "privileges.json"),
47261
- loginsPath: (0, import_node_path32.join)(PATHS.stateDir, "login-countries.json"),
47262
- cursorPath: (0, import_node_path32.join)(PATHS.stateDir, "sudo-cursor.json"),
47338
+ snapshotPath: (0, import_node_path33.join)(PATHS.stateDir, "privileges.json"),
47339
+ loginsPath: (0, import_node_path33.join)(PATHS.stateDir, "login-countries.json"),
47340
+ cursorPath: (0, import_node_path33.join)(PATHS.stateDir, "sudo-cursor.json"),
47263
47341
  log: logLine
47264
47342
  });
47265
47343
  privilegeWatch.start();
@@ -47282,7 +47360,7 @@ async function runDaemon() {
47282
47360
  version,
47283
47361
  hostname: (0, import_node_os13.hostname)(),
47284
47362
  minSeverity,
47285
- spoolPath: (0, import_node_path32.join)(PATHS.stateDir, "cloud-spool.jsonl"),
47363
+ spoolPath: (0, import_node_path33.join)(PATHS.stateDir, "cloud-spool.jsonl"),
47286
47364
  log: logLine,
47287
47365
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
47288
47366
  runHardening: runHardeningChecks
@@ -47301,8 +47379,8 @@ async function runDaemon() {
47301
47379
  const autoUpdate = new AutoUpdate({
47302
47380
  version,
47303
47381
  settings: updateSettings(config.update),
47304
- pkgRoot: (0, import_node_path32.join)(__dirname, ".."),
47305
- statePath: (0, import_node_path32.join)(PATHS.stateDir, "auto-update.json"),
47382
+ pkgRoot: (0, import_node_path33.join)(__dirname, ".."),
47383
+ statePath: (0, import_node_path33.join)(PATHS.stateDir, "auto-update.json"),
47306
47384
  bus,
47307
47385
  log: logLine,
47308
47386
  restartDaemon
@@ -47392,7 +47470,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
47392
47470
  function isRoot2() {
47393
47471
  return typeof process.getuid === "function" && process.getuid() === 0;
47394
47472
  }
47395
- var DAEMON_ENTRY = (0, import_node_path33.join)(__dirname, "daemon.js");
47473
+ var DAEMON_ENTRY = (0, import_node_path34.join)(__dirname, "daemon.js");
47396
47474
  async function daemonForeground() {
47397
47475
  await runDaemon();
47398
47476
  }
@@ -47413,7 +47491,7 @@ async function daemonStart() {
47413
47491
  return;
47414
47492
  }
47415
47493
  ensureRuntimeDirs();
47416
- if (!(0, import_node_fs43.existsSync)(DAEMON_ENTRY)) {
47494
+ if (!(0, import_node_fs44.existsSync)(DAEMON_ENTRY)) {
47417
47495
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
47418
47496
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
47419
47497
  return;
@@ -47421,8 +47499,8 @@ async function daemonStart() {
47421
47499
  let out;
47422
47500
  let err;
47423
47501
  try {
47424
- out = (0, import_node_fs44.openSync)(PATHS.logFile, "a");
47425
- err = (0, import_node_fs44.openSync)(PATHS.logFile, "a");
47502
+ out = (0, import_node_fs45.openSync)(PATHS.logFile, "a");
47503
+ err = (0, import_node_fs45.openSync)(PATHS.logFile, "a");
47426
47504
  } catch (e) {
47427
47505
  const code = e.code;
47428
47506
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -47510,12 +47588,12 @@ async function waitForExit(pid, timeoutMs) {
47510
47588
  }
47511
47589
  async function releaseStaleSocket() {
47512
47590
  const deadline = Date.now() + 2e3;
47513
- while ((0, import_node_fs43.existsSync)(PATHS.socket) && Date.now() < deadline) {
47591
+ while ((0, import_node_fs44.existsSync)(PATHS.socket) && Date.now() < deadline) {
47514
47592
  await new Promise((r) => setTimeout(r, 50));
47515
47593
  }
47516
- if ((0, import_node_fs43.existsSync)(PATHS.socket)) {
47594
+ if ((0, import_node_fs44.existsSync)(PATHS.socket)) {
47517
47595
  try {
47518
- (0, import_node_fs43.unlinkSync)(PATHS.socket);
47596
+ (0, import_node_fs44.unlinkSync)(PATHS.socket);
47519
47597
  } catch {
47520
47598
  }
47521
47599
  }
@@ -47523,26 +47601,26 @@ async function releaseStaleSocket() {
47523
47601
 
47524
47602
  // src/commands/service.ts
47525
47603
  var import_node_child_process18 = require("child_process");
47526
- var import_node_fs45 = require("fs");
47527
- var import_node_path34 = require("path");
47604
+ var import_node_fs46 = require("fs");
47605
+ var import_node_path35 = require("path");
47528
47606
  var import_node_os14 = require("os");
47529
47607
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
47530
47608
  var DAEMON_UNIT_NAME = "threatcrushd.service";
47531
47609
  function resolveTemplate() {
47532
- const templatePath = (0, import_node_path34.join)(__dirname, "systemd", "threatcrushd.service");
47533
- if (!(0, import_node_fs45.existsSync)(templatePath)) {
47610
+ const templatePath = (0, import_node_path35.join)(__dirname, "systemd", "threatcrushd.service");
47611
+ if (!(0, import_node_fs46.existsSync)(templatePath)) {
47534
47612
  throw new Error(`systemd unit template not found at ${templatePath}`);
47535
47613
  }
47536
- return (0, import_node_fs45.readFileSync)(templatePath, "utf-8");
47614
+ return (0, import_node_fs46.readFileSync)(templatePath, "utf-8");
47537
47615
  }
47538
47616
  function stableBinPath(binPath) {
47539
47617
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
47540
47618
  if (stable === binPath) return binPath;
47541
- return (0, import_node_fs45.existsSync)(stable) ? stable : binPath;
47619
+ return (0, import_node_fs46.existsSync)(stable) ? stable : binPath;
47542
47620
  }
47543
47621
  function resolveBinPath() {
47544
47622
  const arg = process.argv[1];
47545
- if (arg && (0, import_node_fs45.existsSync)(arg)) return stableBinPath(arg);
47623
+ if (arg && (0, import_node_fs46.existsSync)(arg)) return stableBinPath(arg);
47546
47624
  try {
47547
47625
  return (0, import_node_child_process18.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
47548
47626
  } catch {
@@ -47552,11 +47630,11 @@ function resolveBinPath() {
47552
47630
  function stableNodePath(execPath) {
47553
47631
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
47554
47632
  if (stable === execPath) return execPath;
47555
- return (0, import_node_fs45.existsSync)(stable) ? stable : execPath;
47633
+ return (0, import_node_fs46.existsSync)(stable) ? stable : execPath;
47556
47634
  }
47557
47635
  function looksLikeNodeScript(path2) {
47558
47636
  try {
47559
- const head = (0, import_node_fs45.readFileSync)(path2, "utf-8").slice(0, 120);
47637
+ const head = (0, import_node_fs46.readFileSync)(path2, "utf-8").slice(0, 120);
47560
47638
  return /^#!.*\bnode\b/.test(head);
47561
47639
  } catch {
47562
47640
  return false;
@@ -47596,7 +47674,7 @@ function callerHome() {
47596
47674
  try {
47597
47675
  const line2 = (0, import_node_child_process18.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
47598
47676
  const home = line2.split(":")[5];
47599
- return home && (0, import_node_fs45.existsSync)(home) ? home : null;
47677
+ return home && (0, import_node_fs46.existsSync)(home) ? home : null;
47600
47678
  } catch {
47601
47679
  return null;
47602
47680
  }
@@ -47604,13 +47682,13 @@ function callerHome() {
47604
47682
  function stopUserModeDaemon() {
47605
47683
  const home = callerHome();
47606
47684
  if (!home) return;
47607
- const runDir = (0, import_node_path34.join)(home, ".threatcrush", "run");
47608
- const pidFile = (0, import_node_path34.join)(runDir, "threatcrushd.pid");
47609
- const socket = (0, import_node_path34.join)(runDir, "threatcrushd.sock");
47610
- if (!(0, import_node_fs45.existsSync)(pidFile) && !(0, import_node_fs45.existsSync)(socket)) return;
47685
+ const runDir = (0, import_node_path35.join)(home, ".threatcrush", "run");
47686
+ const pidFile = (0, import_node_path35.join)(runDir, "threatcrushd.pid");
47687
+ const socket = (0, import_node_path35.join)(runDir, "threatcrushd.sock");
47688
+ if (!(0, import_node_fs46.existsSync)(pidFile) && !(0, import_node_fs46.existsSync)(socket)) return;
47611
47689
  let pid = null;
47612
47690
  try {
47613
- pid = Number.parseInt((0, import_node_fs45.readFileSync)(pidFile, "utf-8").trim(), 10);
47691
+ pid = Number.parseInt((0, import_node_fs46.readFileSync)(pidFile, "utf-8").trim(), 10);
47614
47692
  } catch {
47615
47693
  pid = null;
47616
47694
  }
@@ -47623,7 +47701,7 @@ function stopUserModeDaemon() {
47623
47701
  }
47624
47702
  for (const path2 of [socket, pidFile]) {
47625
47703
  try {
47626
- if ((0, import_node_fs45.existsSync)(path2)) (0, import_node_fs45.rmSync)(path2);
47704
+ if ((0, import_node_fs46.existsSync)(path2)) (0, import_node_fs46.rmSync)(path2);
47627
47705
  } catch {
47628
47706
  }
47629
47707
  }
@@ -47641,7 +47719,7 @@ async function installServiceCommand() {
47641
47719
  }
47642
47720
  const noSystemd = systemdUnavailableReason({
47643
47721
  hasSystemctl: (0, import_node_child_process18.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
47644
- booted: (0, import_node_fs45.existsSync)("/run/systemd/system")
47722
+ booted: (0, import_node_fs46.existsSync)("/run/systemd/system")
47645
47723
  });
47646
47724
  if (noSystemd) {
47647
47725
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -47663,7 +47741,7 @@ async function installServiceCommand() {
47663
47741
  const isNodeScript = looksLikeNodeScript(binPath);
47664
47742
  let nodePath = stableNodePath(process.execPath);
47665
47743
  if (isNodeScript && nodeVersionDir(binPath)) {
47666
- binPath = (0, import_node_fs45.realpathSync)(binPath);
47744
+ binPath = (0, import_node_fs46.realpathSync)(binPath);
47667
47745
  nodePath = process.execPath;
47668
47746
  }
47669
47747
  if (isNodeScript) {
@@ -47676,9 +47754,9 @@ async function installServiceCommand() {
47676
47754
  }
47677
47755
  }
47678
47756
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
47679
- const configDir = (0, import_node_path34.join)((0, import_node_os14.homedir)(), ".threatcrush");
47757
+ const configDir = (0, import_node_path35.join)((0, import_node_os14.homedir)(), ".threatcrush");
47680
47758
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
47681
- (0, import_node_fs45.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
47759
+ (0, import_node_fs46.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
47682
47760
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
47683
47761
  console.log(source_default.dim(` ExecStart=${exec}`));
47684
47762
  const nodeDir = nodeVersionDir(nodePath);
@@ -47731,9 +47809,9 @@ function renderLogrotate(logDir = "/var/log/threatcrush") {
47731
47809
  ].join("\n");
47732
47810
  }
47733
47811
  function installLogrotate() {
47734
- if (!(0, import_node_fs45.existsSync)((0, import_node_path34.dirname)(LOGROTATE_PATH))) return;
47812
+ if (!(0, import_node_fs46.existsSync)((0, import_node_path35.dirname)(LOGROTATE_PATH))) return;
47735
47813
  try {
47736
- (0, import_node_fs45.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
47814
+ (0, import_node_fs46.writeFileSync)(LOGROTATE_PATH, renderLogrotate(), { mode: 420 });
47737
47815
  console.log(source_default.green(` \u2713 Log rotation: ${LOGROTATE_PATH} (daily or 200M, keeps 7)`));
47738
47816
  } catch (err) {
47739
47817
  console.log(source_default.yellow(` ! Could not install log rotation: ${err.message}`));
@@ -47755,20 +47833,20 @@ function ensureSystemDirs(configDir) {
47755
47833
  ];
47756
47834
  let admGid2 = null;
47757
47835
  try {
47758
- admGid2 = (0, import_node_fs45.statSync)("/var/log/auth.log").gid;
47836
+ admGid2 = (0, import_node_fs46.statSync)("/var/log/auth.log").gid;
47759
47837
  } catch {
47760
47838
  }
47761
47839
  for (const { path: path2, groupWritable, sticky } of dirs) {
47762
47840
  try {
47763
- (0, import_node_fs45.mkdirSync)(path2, { recursive: true });
47841
+ (0, import_node_fs46.mkdirSync)(path2, { recursive: true });
47764
47842
  } catch {
47765
47843
  }
47766
47844
  try {
47767
47845
  if (groupWritable && admGid2 !== null) {
47768
- (0, import_node_fs45.chmodSync)(path2, sticky ? 1533 : 509);
47846
+ (0, import_node_fs46.chmodSync)(path2, sticky ? 1533 : 509);
47769
47847
  (0, import_node_child_process18.execSync)(`chgrp adm ${path2}`, { stdio: "ignore" });
47770
47848
  } else {
47771
- (0, import_node_fs45.chmodSync)(path2, 493);
47849
+ (0, import_node_fs46.chmodSync)(path2, 493);
47772
47850
  }
47773
47851
  } catch {
47774
47852
  }
@@ -47796,7 +47874,7 @@ async function uninstallServiceCommand() {
47796
47874
  } catch {
47797
47875
  }
47798
47876
  try {
47799
- if ((0, import_node_fs45.existsSync)(UNIT_PATH)) {
47877
+ if ((0, import_node_fs46.existsSync)(UNIT_PATH)) {
47800
47878
  (0, import_node_child_process18.execSync)(`rm -f ${UNIT_PATH}`);
47801
47879
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
47802
47880
  }
@@ -47810,7 +47888,7 @@ async function uninstallServiceCommand() {
47810
47888
  }
47811
47889
 
47812
47890
  // src/commands/save.ts
47813
- var import_node_fs46 = require("fs");
47891
+ var import_node_fs47 = require("fs");
47814
47892
  var import_toml5 = __toESM(require_toml());
47815
47893
  init_cli_config();
47816
47894
  init_paths();
@@ -47849,9 +47927,9 @@ async function saveCommand(opts = {}) {
47849
47927
  }
47850
47928
  const path2 = opts.config ?? PATHS.configFile;
47851
47929
  let config = {};
47852
- if ((0, import_node_fs46.existsSync)(path2)) {
47930
+ if ((0, import_node_fs47.existsSync)(path2)) {
47853
47931
  try {
47854
- config = import_toml5.default.parse((0, import_node_fs46.readFileSync)(path2, "utf-8"));
47932
+ config = import_toml5.default.parse((0, import_node_fs47.readFileSync)(path2, "utf-8"));
47855
47933
  } catch (err) {
47856
47934
  console.log(source_default.red(` \u2717 ${path2} is not valid TOML: ${err.message}
47857
47935
  `));
@@ -47964,17 +48042,17 @@ function welcomeCommand() {
47964
48042
  }
47965
48043
 
47966
48044
  // src/commands/properties.ts
47967
- var import_node_fs47 = require("fs");
47968
- var import_node_path35 = require("path");
48045
+ var import_node_fs48 = require("fs");
48046
+ var import_node_path36 = require("path");
47969
48047
  var import_node_readline4 = __toESM(require("readline"));
47970
48048
  init_cli_config();
47971
48049
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
47972
48050
  var KINDS = ["url", "api", "domain", "ip", "repo"];
47973
48051
  function prompt(question) {
47974
48052
  const rl = import_node_readline4.default.createInterface({ input: process.stdin, output: process.stdout });
47975
- return new Promise((resolve6) => rl.question(question, (answer) => {
48053
+ return new Promise((resolve7) => rl.question(question, (answer) => {
47976
48054
  rl.close();
47977
- resolve6(answer.trim());
48055
+ resolve7(answer.trim());
47978
48056
  }));
47979
48057
  }
47980
48058
  async function requireAuth() {
@@ -48295,8 +48373,8 @@ async function propertiesRunsCommand(opts) {
48295
48373
  }
48296
48374
  }
48297
48375
  function parseImportFile(path2) {
48298
- const ext = (0, import_node_path35.extname)(path2).toLowerCase();
48299
- const raw = (0, import_node_fs47.readFileSync)(path2, "utf-8");
48376
+ const ext = (0, import_node_path36.extname)(path2).toLowerCase();
48377
+ const raw = (0, import_node_fs48.readFileSync)(path2, "utf-8");
48300
48378
  if (ext === ".json") {
48301
48379
  const parsed = JSON.parse(raw);
48302
48380
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -48491,7 +48569,7 @@ async function rulesCommand(opts) {
48491
48569
  }
48492
48570
 
48493
48571
  // src/commands/harden.ts
48494
- var import_node_fs48 = require("fs");
48572
+ var import_node_fs49 = require("fs");
48495
48573
  var import_node_child_process19 = require("child_process");
48496
48574
  init_cli_config();
48497
48575
  function tryExec(cmd) {
@@ -48503,7 +48581,7 @@ function tryExec(cmd) {
48503
48581
  }
48504
48582
  function tryRead(path2) {
48505
48583
  try {
48506
- return (0, import_node_fs48.readFileSync)(path2, "utf-8");
48584
+ return (0, import_node_fs49.readFileSync)(path2, "utf-8");
48507
48585
  } catch {
48508
48586
  return null;
48509
48587
  }
@@ -48607,8 +48685,8 @@ function checkSshWeakConfig() {
48607
48685
  };
48608
48686
  }
48609
48687
  function checkAutoUpdates() {
48610
- const unattended = (0, import_node_fs48.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs48.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
48611
- const dnfAuto = (0, import_node_fs48.existsSync)("/etc/dnf/automatic.conf");
48688
+ const unattended = (0, import_node_fs49.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs49.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
48689
+ const dnfAuto = (0, import_node_fs49.existsSync)("/etc/dnf/automatic.conf");
48612
48690
  if (unattended || dnfAuto) {
48613
48691
  return {
48614
48692
  key: "auto-updates",
@@ -48734,7 +48812,7 @@ function checkFail2ban() {
48734
48812
  explanation: "fail2ban is installed and running."
48735
48813
  };
48736
48814
  }
48737
- if ((0, import_node_fs48.existsSync)("/etc/fail2ban/fail2ban.conf")) {
48815
+ if ((0, import_node_fs49.existsSync)("/etc/fail2ban/fail2ban.conf")) {
48738
48816
  return {
48739
48817
  key: checkKey,
48740
48818
  status: "warn",
@@ -48920,8 +48998,8 @@ async function hardenCommand(opts) {
48920
48998
  }
48921
48999
 
48922
49000
  // src/core/patches/index.ts
48923
- var import_node_fs49 = require("fs");
48924
- var import_node_path36 = require("path");
49001
+ var import_node_fs50 = require("fs");
49002
+ var import_node_path37 = require("path");
48925
49003
  var import_node_child_process20 = require("child_process");
48926
49004
  var import_node_util5 = require("util");
48927
49005
 
@@ -49081,9 +49159,9 @@ async function osvRecords(doFetch, ecosystem, source, version) {
49081
49159
  function newestReleaseMtime(dir) {
49082
49160
  try {
49083
49161
  let newest = 0;
49084
- for (const name of (0, import_node_fs49.readdirSync)(dir)) {
49162
+ for (const name of (0, import_node_fs50.readdirSync)(dir)) {
49085
49163
  if (!/Release$/.test(name)) continue;
49086
- newest = Math.max(newest, (0, import_node_fs49.statSync)((0, import_node_path36.join)(dir, name)).mtimeMs);
49164
+ newest = Math.max(newest, (0, import_node_fs50.statSync)((0, import_node_path37.join)(dir, name)).mtimeMs);
49087
49165
  }
49088
49166
  return newest > 0 ? new Date(newest) : null;
49089
49167
  } catch {
@@ -49100,7 +49178,7 @@ async function checkPatches(opts = {}) {
49100
49178
  let osText = opts.osRelease;
49101
49179
  if (osText === void 0) {
49102
49180
  try {
49103
- osText = (0, import_node_fs49.readFileSync)("/etc/os-release", "utf-8");
49181
+ osText = (0, import_node_fs50.readFileSync)("/etc/os-release", "utf-8");
49104
49182
  } catch {
49105
49183
  osText = "";
49106
49184
  }
@@ -49327,24 +49405,24 @@ async function patchesCommand(opts) {
49327
49405
 
49328
49406
  // src/commands/feeds.ts
49329
49407
  var import_node_net13 = require("net");
49330
- var import_node_path38 = require("path");
49408
+ var import_node_path39 = require("path");
49331
49409
  init_paths();
49332
49410
 
49333
49411
  // src/commands/feeds-resolver.ts
49334
49412
  var import_node_child_process21 = require("child_process");
49335
- var import_node_fs50 = require("fs");
49336
- var import_node_path37 = require("path");
49413
+ var import_node_fs51 = require("fs");
49414
+ var import_node_path38 = require("path");
49337
49415
  var realIO = {
49338
- exists: (p) => (0, import_node_fs50.existsSync)(p),
49416
+ exists: (p) => (0, import_node_fs51.existsSync)(p),
49339
49417
  read: (p) => {
49340
49418
  try {
49341
- return (0, import_node_fs50.readFileSync)(p, "utf-8");
49419
+ return (0, import_node_fs51.readFileSync)(p, "utf-8");
49342
49420
  } catch {
49343
49421
  return null;
49344
49422
  }
49345
49423
  },
49346
- write: (p, c) => (0, import_node_fs50.writeFileSync)(p, c),
49347
- remove: (p) => (0, import_node_fs50.rmSync)(p, { force: true }),
49424
+ write: (p, c) => (0, import_node_fs51.writeFileSync)(p, c),
49425
+ remove: (p) => (0, import_node_fs51.rmSync)(p, { force: true }),
49348
49426
  run: (cmd, args) => {
49349
49427
  const r = (0, import_node_child_process21.spawnSync)(cmd, args, { encoding: "utf-8", timeout: 3e4 });
49350
49428
  return { code: r.status ?? 1, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() };
@@ -49354,17 +49432,17 @@ var APPARMOR_LOCAL = "/etc/apparmor.d/local/usr.sbin.unbound";
49354
49432
  var APPARMOR_PROFILE = "/etc/apparmor.d/usr.sbin.unbound";
49355
49433
  function hookContent(resolver, stateDir) {
49356
49434
  const head = "# Installed by `threatcrush feeds resolver install`; `threatcrush feeds resolver remove` takes it out.\n";
49357
- return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path37.join)(stateDir, RESOLVER_FILES.hosts)}
49358
- ` : `${head}include: "${(0, import_node_path37.join)(stateDir, RESOLVER_FILES.unbound)}"
49435
+ return resolver === "dnsmasq" ? `${head}addn-hosts=${(0, import_node_path38.join)(stateDir, RESOLVER_FILES.hosts)}
49436
+ ` : `${head}include: "${(0, import_node_path38.join)(stateDir, RESOLVER_FILES.unbound)}"
49359
49437
  `;
49360
49438
  }
49361
49439
  function apparmorRule(stateDir) {
49362
- return ` ${(0, import_node_path37.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
49440
+ return ` ${(0, import_node_path38.join)(stateDir, RESOLVER_FILES.unbound)} r, # threatcrush`;
49363
49441
  }
49364
49442
  function detectResolvers(io = realIO) {
49365
49443
  const found = [];
49366
- if (io.exists((0, import_node_path37.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
49367
- if (io.exists((0, import_node_path37.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
49444
+ if (io.exists((0, import_node_path38.dirname)(RESOLVER_HOOKS.dnsmasq)) && io.run("dnsmasq", ["--version"]).code === 0) found.push("dnsmasq");
49445
+ if (io.exists((0, import_node_path38.dirname)(RESOLVER_HOOKS.unbound)) && io.run("unbound-checkconf", ["-h"]).code !== 127) found.push("unbound");
49368
49446
  return found;
49369
49447
  }
49370
49448
  function check(resolver, io) {
@@ -49377,7 +49455,7 @@ function restartIfActive(resolver, io) {
49377
49455
  }
49378
49456
  function installHook(resolver, stateDir, io = realIO) {
49379
49457
  const hook = RESOLVER_HOOKS[resolver];
49380
- const file = (0, import_node_path37.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
49458
+ const file = (0, import_node_path38.join)(stateDir, resolver === "dnsmasq" ? RESOLVER_FILES.hosts : RESOLVER_FILES.unbound);
49381
49459
  if (!io.exists(file)) io.write(file, resolver === "dnsmasq" ? hostsBlocklist([]) : unboundBlocklist([]));
49382
49460
  io.write(hook, hookContent(resolver, stateDir));
49383
49461
  if (resolver === "unbound" && io.exists(APPARMOR_LOCAL)) {
@@ -49438,8 +49516,8 @@ function resolverCommand(sub, stateDir, io = realIO) {
49438
49516
  }
49439
49517
  return failed ? 1 : 0;
49440
49518
  }
49441
- const hosts = io.read((0, import_node_path37.join)(stateDir, RESOLVER_FILES.hosts));
49442
- const unbound = io.read((0, import_node_path37.join)(stateDir, RESOLVER_FILES.unbound));
49519
+ const hosts = io.read((0, import_node_path38.join)(stateDir, RESOLVER_FILES.hosts));
49520
+ const unbound = io.read((0, import_node_path38.join)(stateDir, RESOLVER_FILES.unbound));
49443
49521
  console.log(` resolvers here: ${found.join(", ") || "none that can block (systemd-resolved only?)"}`);
49444
49522
  for (const r of ["dnsmasq", "unbound"]) {
49445
49523
  console.log(` ${r.padEnd(8)} hook ${io.exists(RESOLVER_HOOKS[r]) ? source_default.green("installed") : source_default.gray("not installed")}`);
@@ -49451,11 +49529,11 @@ function resolverCommand(sub, stateDir, io = realIO) {
49451
49529
  // src/commands/feeds.ts
49452
49530
  async function loadSet() {
49453
49531
  for (const dir of [SYSTEM_PATHS.stateDir, USER_PATHS.stateDir]) {
49454
- const path2 = (0, import_node_path38.join)(dir, "threat-feeds.json");
49532
+ const path2 = (0, import_node_path39.join)(dir, "threat-feeds.json");
49455
49533
  const set = readFeedCache(path2);
49456
49534
  if (set) return { set, from: path2 };
49457
49535
  }
49458
- const settings = threatFeedSettings(loadConfig((0, import_node_path38.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
49536
+ const settings = threatFeedSettings(loadConfig((0, import_node_path39.join)(SYSTEM_PATHS.configDir, "threatcrushd.conf")).threat_feeds);
49459
49537
  return { set: await fetchFeeds(settings), from: "abuse.ch (live; no daemon cache readable)" };
49460
49538
  }
49461
49539
  async function feedsCommand(action, value, opts) {
@@ -49500,13 +49578,13 @@ async function feedsCommand(action, value, opts) {
49500
49578
 
49501
49579
  // src/commands/reputation.ts
49502
49580
  var import_node_os15 = require("os");
49503
- var import_node_fs51 = require("fs");
49504
- var import_node_path39 = require("path");
49581
+ var import_node_fs52 = require("fs");
49582
+ var import_node_path40 = require("path");
49505
49583
  var API_URL7 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
49506
- var CONFIG_PATH4 = (0, import_node_path39.join)((0, import_node_os15.homedir)(), ".threatcrush", "config.json");
49584
+ var CONFIG_PATH4 = (0, import_node_path40.join)((0, import_node_os15.homedir)(), ".threatcrush", "config.json");
49507
49585
  function readConfig3() {
49508
49586
  try {
49509
- return JSON.parse((0, import_node_fs51.readFileSync)(CONFIG_PATH4, "utf-8"));
49587
+ return JSON.parse((0, import_node_fs52.readFileSync)(CONFIG_PATH4, "utf-8"));
49510
49588
  } catch {
49511
49589
  return {};
49512
49590
  }
@@ -49694,7 +49772,7 @@ async function reputationSubscribeCommand(opts) {
49694
49772
  }
49695
49773
 
49696
49774
  // src/commands/privileged.ts
49697
- var import_node_fs52 = require("fs");
49775
+ var import_node_fs53 = require("fs");
49698
49776
  init_paths();
49699
49777
  var SEV2 = {
49700
49778
  critical: source_default.red.bold,
@@ -49707,19 +49785,19 @@ async function privilegedCommand(opts) {
49707
49785
  const snapshot = takeSnapshot({
49708
49786
  readFile: (p) => {
49709
49787
  try {
49710
- return (0, import_node_fs52.readFileSync)(p, "utf-8");
49788
+ return (0, import_node_fs53.readFileSync)(p, "utf-8");
49711
49789
  } catch {
49712
49790
  return null;
49713
49791
  }
49714
49792
  },
49715
49793
  readDir: (p) => {
49716
49794
  try {
49717
- return (0, import_node_fs52.readdirSync)(p);
49795
+ return (0, import_node_fs53.readdirSync)(p);
49718
49796
  } catch {
49719
49797
  return null;
49720
49798
  }
49721
49799
  },
49722
- exists: (p) => (0, import_node_fs52.existsSync)(p)
49800
+ exists: (p) => (0, import_node_fs53.existsSync)(p)
49723
49801
  });
49724
49802
  let events = [];
49725
49803
  let ledgerNote = "";
@@ -49901,7 +49979,7 @@ async function allowlistCommand(opts) {
49901
49979
  }
49902
49980
 
49903
49981
  // src/commands/abuse.ts
49904
- var import_node_fs53 = require("fs");
49982
+ var import_node_fs54 = require("fs");
49905
49983
  init_paths();
49906
49984
  function rows(records) {
49907
49985
  if (records.length === 0) {
@@ -49961,7 +50039,7 @@ function abuseRetractCommand(id, opts = {}) {
49961
50039
  );
49962
50040
  }
49963
50041
  function abuseStatusCommand(opts = {}) {
49964
- const config = loadConfig((0, import_node_fs53.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
50042
+ const config = loadConfig((0, import_node_fs54.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
49965
50043
  const cfg = resolveConfig(config.abuse_reporter);
49966
50044
  const hasKey2 = Boolean(cfg.keys.abuseipdb || cfg.keys.stopforumspam);
49967
50045
  const active2 = cfg.enabled && (cfg.dryRun || hasKey2);
@@ -50095,7 +50173,7 @@ init_ipc_client();
50095
50173
  // src/core/user-agent.ts
50096
50174
  init_cli_config();
50097
50175
  var USER_AGENT = `threatcrush/${PKG_VERSION} (node ${process.version}; ${process.platform})`;
50098
- function isOurHost(url, api2 = apiUrl()) {
50176
+ function isOurHost(url, api3 = apiUrl()) {
50099
50177
  let host;
50100
50178
  try {
50101
50179
  host = new URL(url).hostname.toLowerCase();
@@ -50104,7 +50182,7 @@ function isOurHost(url, api2 = apiUrl()) {
50104
50182
  }
50105
50183
  let apiHost = "";
50106
50184
  try {
50107
- apiHost = new URL(api2).hostname.toLowerCase();
50185
+ apiHost = new URL(api3).hostname.toLowerCase();
50108
50186
  } catch {
50109
50187
  }
50110
50188
  return host === apiHost || host === "threatcrush.com" || host.endsWith(".threatcrush.com");
@@ -50128,6 +50206,248 @@ function installUserAgent(target = globalThis) {
50128
50206
  target.fetch = wrapped;
50129
50207
  }
50130
50208
 
50209
+ // src/core/cloud-upload.ts
50210
+ var import_node_child_process23 = require("child_process");
50211
+ var import_node_os16 = require("os");
50212
+ var import_node_path41 = require("path");
50213
+ init_cli_config();
50214
+ function uploadDisabled(upload, env3 = process.env) {
50215
+ if (upload === false) return true;
50216
+ const v = (env3.THREATCRUSH_UPLOAD ?? "").trim().toLowerCase();
50217
+ return ["0", "off", "false", "no"].includes(v);
50218
+ }
50219
+ function cleanUrl(raw) {
50220
+ try {
50221
+ const u = new URL(raw);
50222
+ u.username = "";
50223
+ u.password = "";
50224
+ u.search = "";
50225
+ u.hash = "";
50226
+ return u.toString();
50227
+ } catch {
50228
+ return raw.split(/[?#]/)[0];
50229
+ }
50230
+ }
50231
+ function repoTarget(path2, run = (args) => (0, import_node_child_process23.execFileSync)("git", args, { cwd: (0, import_node_path41.resolve)(path2), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5e3 }).trim()) {
50232
+ const abs = (0, import_node_path41.resolve)(path2);
50233
+ try {
50234
+ const root = run(["rev-parse", "--show-toplevel"]);
50235
+ const sub = abs === root ? "." : abs.slice(root.length + 1);
50236
+ let remote = "";
50237
+ try {
50238
+ remote = run(["remote", "get-url", "origin"]);
50239
+ } catch {
50240
+ }
50241
+ if (remote) {
50242
+ const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)[:/](.+?)(?:\.git)?\/?$/i.exec(remote);
50243
+ if (m) return { target: `${m[1]}/${m[2]}`, root, sub };
50244
+ }
50245
+ return { target: `${(0, import_node_os16.hostname)()}:${root}`, root, sub };
50246
+ } catch {
50247
+ return { target: `${(0, import_node_os16.hostname)()}:${abs}`, root: abs, sub: "." };
50248
+ }
50249
+ }
50250
+ async function uploadResult(result, opts) {
50251
+ const say = (line2) => (opts.machineReadable ? process.stderr : process.stdout).write(`${line2}
50252
+ `);
50253
+ if (uploadDisabled(opts.upload, opts.env)) return { uploaded: false, reason: "disabled" };
50254
+ if (!hasSession()) {
50255
+ if (!opts.machineReadable && process.stdout.isTTY) {
50256
+ say(source_default.dim(` Sign in with ${source_default.white("threatcrush login")} to track these findings in the cloud and triage them anywhere.
50257
+ `));
50258
+ }
50259
+ return { uploaded: false, reason: "signed-out" };
50260
+ }
50261
+ const cfg = readCliConfig();
50262
+ if (!cfg.current_org_id) {
50263
+ say(source_default.yellow(` Not saved to the cloud: no current org. Pick one with ${source_default.white("threatcrush orgs use <slug>")}.
50264
+ `));
50265
+ return { uploaded: false, reason: "no-org" };
50266
+ }
50267
+ try {
50268
+ const res = await cloudFetch(`/api/orgs/${cfg.current_org_id}/scan-findings/report`, {
50269
+ method: "POST",
50270
+ timeoutMs: 3e4,
50271
+ body: JSON.stringify({
50272
+ source: opts.source,
50273
+ target: opts.target,
50274
+ kind: opts.kind,
50275
+ scope: opts.scope ?? "",
50276
+ worker_id: workerId(),
50277
+ result: {
50278
+ findings: result.findings,
50279
+ severity_summary: result.severity_summary,
50280
+ summary: result.summary,
50281
+ error: result.error
50282
+ }
50283
+ })
50284
+ });
50285
+ const data = await res.json().catch(() => ({}));
50286
+ if (!res.ok || !data.sync) {
50287
+ say(source_default.yellow(` Not saved to the cloud: ${data.error || `HTTP ${res.status}`}.
50288
+ `));
50289
+ return { uploaded: false, reason: "error" };
50290
+ }
50291
+ const s = data.sync;
50292
+ const org = cfg.current_org_slug || "your org";
50293
+ const parts = [`${s.new} new`, `${s.seen + s.reopened} still open${s.reopened ? ` (${s.reopened} back after a fix)` : ""}`, `${s.fixed} fixed`];
50294
+ say(source_default.cyan(` \u2601 Saved to ${org}: ${parts.join(" \xB7 ")}. Triage with ${source_default.white("threatcrush findings")} or on threatcrush.com/org/${org}/findings
50295
+ `));
50296
+ return { uploaded: true, sync: s, propertyName: data.property_name };
50297
+ } catch (err) {
50298
+ say(source_default.yellow(` Not saved to the cloud: ${err.message}.
50299
+ `));
50300
+ return { uploaded: false, reason: "error" };
50301
+ }
50302
+ }
50303
+
50304
+ // src/commands/findings.ts
50305
+ init_cli_config();
50306
+ var TRIAGE = {
50307
+ ack: "acknowledged",
50308
+ fix: "fixed",
50309
+ fp: "false_positive",
50310
+ ignore: "ignored",
50311
+ reopen: "open"
50312
+ };
50313
+ var SEV_COLOR = {
50314
+ critical: source_default.bgRed.white,
50315
+ high: source_default.red,
50316
+ medium: source_default.yellow,
50317
+ low: source_default.blue,
50318
+ info: source_default.gray
50319
+ };
50320
+ var STATUS_LABEL = {
50321
+ open: "open",
50322
+ acknowledged: "ack",
50323
+ fixed: "fixed",
50324
+ false_positive: "false+",
50325
+ ignored: "ignored"
50326
+ };
50327
+ function orgOrExplain() {
50328
+ if (!hasSession()) {
50329
+ console.log(source_default.red(` Not signed in. Run ${source_default.white("threatcrush login")} first.
50330
+ `));
50331
+ process.exitCode = 1;
50332
+ return null;
50333
+ }
50334
+ const org = readCliConfig().current_org_id;
50335
+ if (!org) {
50336
+ console.log(source_default.red(` No current org. Run ${source_default.white("threatcrush orgs use <slug>")}.
50337
+ `));
50338
+ process.exitCode = 1;
50339
+ return null;
50340
+ }
50341
+ return org;
50342
+ }
50343
+ async function api2(path2, init) {
50344
+ const res = await cloudFetch(path2, init);
50345
+ const data = await res.json().catch(() => ({}));
50346
+ if (!res.ok) {
50347
+ console.log(source_default.red(` ${data.error || `HTTP ${res.status}`}${res.status === 401 ? ` \u2014 run ${source_default.white("threatcrush login")}` : ""}
50348
+ `));
50349
+ process.exitCode = 1;
50350
+ return null;
50351
+ }
50352
+ return data;
50353
+ }
50354
+ var short = (id) => id.slice(0, 8);
50355
+ var day = (iso) => iso.slice(0, 10);
50356
+ async function findingsListCommand(opts) {
50357
+ const org = orgOrExplain();
50358
+ if (!org) return;
50359
+ const qs = new URLSearchParams();
50360
+ if (opts.status) qs.set("status", opts.status);
50361
+ if (opts.severity) qs.set("severity", opts.severity);
50362
+ if (opts.source) qs.set("source", opts.source);
50363
+ qs.set("limit", String(Math.min(500, Number(opts.limit) || 100)));
50364
+ const data = await api2(`/api/orgs/${org}/scan-findings?${qs}`);
50365
+ if (!data) return;
50366
+ if (opts.json) {
50367
+ console.log(JSON.stringify(data, null, 2));
50368
+ return;
50369
+ }
50370
+ const slug = readCliConfig().current_org_slug || org;
50371
+ const c = data.counts;
50372
+ console.log(source_default.bold(`
50373
+ Findings in ${slug}`) + source_default.dim(` open ${c.open ?? 0} \xB7 ack ${c.acknowledged ?? 0} \xB7 fixed ${c.fixed ?? 0} \xB7 false+ ${c.false_positive ?? 0} \xB7 ignored ${c.ignored ?? 0}
50374
+ `));
50375
+ if (!data.findings.length) {
50376
+ console.log(source_default.green(" Nothing matches. ") + source_default.dim(opts.status ? "" : "Showing open + acknowledged; use --status all for everything.") + "\n");
50377
+ return;
50378
+ }
50379
+ for (const f of data.findings) {
50380
+ const sev = (SEV_COLOR[f.severity] ?? source_default.white)(f.severity.toUpperCase().padEnd(8));
50381
+ console.log(` ${source_default.gray(short(f.id))} ${sev} ${source_default.dim((STATUS_LABEL[f.status] ?? f.status).padEnd(7))} ${f.message}`);
50382
+ console.log(source_default.dim(` ${f.source} \xB7 ${f.properties?.name ?? "?"}${f.location ? ` \xB7 ${f.location}` : ""} \xB7 seen ${f.times_seen}x, last ${day(f.last_seen_at)}`));
50383
+ }
50384
+ if (data.total > data.findings.length) console.log(source_default.dim(`
50385
+ ${data.findings.length} of ${data.total} shown; --limit for more.`));
50386
+ console.log(source_default.dim(`
50387
+ Triage: threatcrush findings ack|fix|fp|ignore|reopen <id...> [--note "why"] \xB7 details: threatcrush findings show <id>
50388
+ `));
50389
+ }
50390
+ async function resolveIds(org, prefixes) {
50391
+ const full = prefixes.filter((p) => /^[0-9a-f-]{36}$/i.test(p));
50392
+ const partial = prefixes.filter((p) => !full.includes(p));
50393
+ if (!partial.length) return full;
50394
+ const data = await api2(`/api/orgs/${org}/scan-findings?status=all&limit=500`);
50395
+ if (!data) return null;
50396
+ for (const p of partial) {
50397
+ const hits = data.findings.filter((f) => f.id.startsWith(p.toLowerCase()));
50398
+ if (hits.length !== 1) {
50399
+ console.log(source_default.red(` ${p}: ${hits.length ? "matches more than one finding, use more characters" : "no such finding"}
50400
+ `));
50401
+ process.exitCode = 1;
50402
+ return null;
50403
+ }
50404
+ full.push(hits[0].id);
50405
+ }
50406
+ return full;
50407
+ }
50408
+ async function findingsShowCommand(id, opts) {
50409
+ const org = orgOrExplain();
50410
+ if (!org) return;
50411
+ const [full] = await resolveIds(org, [id]) ?? [];
50412
+ if (!full) return;
50413
+ const data = await api2(`/api/orgs/${org}/scan-findings/${full}`);
50414
+ if (!data) return;
50415
+ if (opts.json) {
50416
+ console.log(JSON.stringify(data.finding, null, 2));
50417
+ return;
50418
+ }
50419
+ const f = data.finding;
50420
+ const d = f.details ?? {};
50421
+ console.log(`
50422
+ ${(SEV_COLOR[f.severity] ?? source_default.white)(f.severity.toUpperCase())} ${source_default.bold(f.message)}`);
50423
+ console.log(source_default.dim(` ${f.id} \xB7 ${f.status} \xB7 ${f.source} \xB7 ${f.type}`));
50424
+ console.log(` ${source_default.gray("Property:")} ${f.properties?.name ?? "?"} ${source_default.dim(f.properties?.target ?? "")}`);
50425
+ if (f.location) console.log(` ${source_default.gray("Where:")} ${f.location}`);
50426
+ if (typeof d.snippet === "string") console.log(` ${source_default.gray("Code:")} ${d.snippet}`);
50427
+ if (typeof d.remediation === "string") console.log(` ${source_default.gray("Fix:")} ${d.remediation}`);
50428
+ console.log(` ${source_default.gray("Seen:")} ${f.times_seen}x, first ${day(f.first_seen_at)}, last ${day(f.last_seen_at)}`);
50429
+ if (f.note) console.log(` ${source_default.gray("Note:")} ${f.note}`);
50430
+ console.log();
50431
+ }
50432
+ async function findingsTriageCommand(verb, ids, opts) {
50433
+ const org = orgOrExplain();
50434
+ if (!org) return;
50435
+ if (!ids.length) {
50436
+ console.log(source_default.red(` Give at least one finding id (see threatcrush findings).
50437
+ `));
50438
+ process.exitCode = 1;
50439
+ return;
50440
+ }
50441
+ const full = await resolveIds(org, ids);
50442
+ if (!full) return;
50443
+ const body = { ids: full, status: TRIAGE[verb] };
50444
+ if (opts.note !== void 0) body.note = opts.note;
50445
+ const data = await api2(`/api/orgs/${org}/scan-findings`, { method: "PATCH", body: JSON.stringify(body) });
50446
+ if (!data) return;
50447
+ console.log(source_default.green(` \u2713 ${data.updated.length} finding(s) \u2192 ${TRIAGE[verb].replace("_", " ")}
50448
+ `));
50449
+ }
50450
+
50131
50451
  // src/index.ts
50132
50452
  installUserAgent();
50133
50453
  var LOGO2 = `
@@ -50142,25 +50462,25 @@ ${source_default.dim(" C R U S H")}
50142
50462
  var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
50143
50463
  var PKG_NAME2 = "@profullstack/threatcrush";
50144
50464
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
50145
- var INSTALL_CONFIG_PATH = (0, import_node_path40.join)((0, import_node_os16.homedir)(), ".threatcrush", "install.json");
50465
+ var INSTALL_CONFIG_PATH = (0, import_node_path42.join)((0, import_node_os17.homedir)(), ".threatcrush", "install.json");
50146
50466
  function detectPackageManager() {
50147
50467
  try {
50148
- const npmGlobal = (0, import_node_child_process23.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
50468
+ const npmGlobal = (0, import_node_child_process24.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
50149
50469
  if (npmGlobal.includes(PKG_NAME2)) return "npm";
50150
50470
  } catch {
50151
50471
  }
50152
50472
  try {
50153
- (0, import_node_child_process23.execSync)("pnpm --version", { stdio: "pipe" });
50473
+ (0, import_node_child_process24.execSync)("pnpm --version", { stdio: "pipe" });
50154
50474
  return "pnpm";
50155
50475
  } catch {
50156
50476
  }
50157
50477
  try {
50158
- (0, import_node_child_process23.execSync)("yarn --version", { stdio: "pipe" });
50478
+ (0, import_node_child_process24.execSync)("yarn --version", { stdio: "pipe" });
50159
50479
  return "yarn";
50160
50480
  } catch {
50161
50481
  }
50162
50482
  try {
50163
- (0, import_node_child_process23.execSync)("bun --version", { stdio: "pipe" });
50483
+ (0, import_node_child_process24.execSync)("bun --version", { stdio: "pipe" });
50164
50484
  return "bun";
50165
50485
  } catch {
50166
50486
  }
@@ -50168,14 +50488,14 @@ function detectPackageManager() {
50168
50488
  }
50169
50489
  function readInstallConfig() {
50170
50490
  try {
50171
- return JSON.parse((0, import_node_fs54.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
50491
+ return JSON.parse((0, import_node_fs55.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
50172
50492
  } catch {
50173
50493
  return {};
50174
50494
  }
50175
50495
  }
50176
50496
  function packageLooksInstalled(pm, pkgName) {
50177
50497
  try {
50178
- const output = (0, import_node_child_process23.execSync)(globalListCommand(pm, pkgName), {
50498
+ const output = (0, import_node_child_process24.execSync)(globalListCommand(pm, pkgName), {
50179
50499
  encoding: "utf-8",
50180
50500
  stdio: ["pipe", "pipe", "pipe"]
50181
50501
  });
@@ -50278,14 +50598,14 @@ async function promoteUnprivilegedDaemon() {
50278
50598
  function restartSystemdDaemon() {
50279
50599
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
50280
50600
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
50281
- if (!asRoot && (0, import_node_child_process23.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
50601
+ if (!asRoot && (0, import_node_child_process24.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
50282
50602
  const [cmd, ...args] = argv;
50283
- if ((0, import_node_child_process23.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
50284
- return (0, import_node_child_process23.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
50603
+ if ((0, import_node_child_process24.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
50604
+ return (0, import_node_child_process24.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
50285
50605
  }
50286
50606
  function execQuiet(cmd) {
50287
50607
  try {
50288
- return (0, import_node_child_process23.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
50608
+ return (0, import_node_child_process24.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
50289
50609
  } catch {
50290
50610
  return null;
50291
50611
  }
@@ -50408,7 +50728,7 @@ program2.command("scan").description("Scan codebase for vulnerabilities and secr
50408
50728
  ).option(
50409
50729
  "--missing-controls",
50410
50730
  "also report security controls the tree shows no evidence of (headers, CSRF, rate limiting, body size limits)"
50411
- ).option("-v, --verbose", "list the paths that could not be read").action(async (targetPath, opts) => {
50731
+ ).option("-v, --verbose", "list the paths that could not be read").option("--no-upload", "do not save the results to your threatcrush.com org (also THREATCRUSH_UPLOAD=0)").action(async (targetPath, opts) => {
50412
50732
  const format2 = (opts.format ?? "text").toLowerCase();
50413
50733
  if (!["text", "json", "sarif"].includes(format2)) {
50414
50734
  console.error(source_default.red(`Unknown --format "${opts.format}" (expected text, json, or sarif)`));
@@ -50421,7 +50741,7 @@ program2.command("scan").description("Scan codebase for vulnerabilities and secr
50421
50741
  console.error(source_default.red(err.message));
50422
50742
  process.exit(2);
50423
50743
  }
50424
- await scanCommand(targetPath, {
50744
+ const result = await scanCommand(targetPath, {
50425
50745
  format: format2,
50426
50746
  output: opts.output,
50427
50747
  failOn,
@@ -50431,16 +50751,59 @@ program2.command("scan").description("Scan codebase for vulnerabilities and secr
50431
50751
  missingControls: opts.missingControls,
50432
50752
  verbose: opts.verbose
50433
50753
  });
50754
+ if (!result.error) {
50755
+ const repo = repoTarget(targetPath);
50756
+ const scope = [
50757
+ `path=${repo.sub}`,
50758
+ opts.deps ? "deps" : "",
50759
+ opts.missingControls ? "missing-controls" : "",
50760
+ ...(opts.exclude ?? []).map((g) => `exclude=${g}`)
50761
+ ].filter(Boolean).join(";");
50762
+ await uploadResult(result, { source: "scan", target: repo.target, kind: "repo", scope, upload: opts.upload, machineReadable: format2 !== "text" });
50763
+ }
50434
50764
  });
50435
- program2.command("pentest").description("Penetration test URLs and APIs").argument("<url>", "Target URL to pentest").action(async (url) => {
50436
- await pentestCommand(url);
50765
+ 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) => {
50766
+ const result = await pentestCommand(url);
50767
+ await uploadResult(result, { source: "pentest", target: cleanUrl(url), kind: "url", upload: opts.upload });
50437
50768
  });
50438
- program2.command("ai-scan").description("Red-team an AI/LLM endpoint you own for OWASP LLM Top 10 guardrail gaps").argument("<url>", "Target AI endpoint URL").option("--categories <list>", "comma list: prompt-injection,system-prompt-leak,sensitive-disclosure,excessive-agency,output-handling").option("--template <json>", 'request body with {{PROMPT}} marker (default {"input":"{{PROMPT}}"})').option("--header <k:v...>", "extra request header (repeatable)").option("--response-path <path>", 'dotted JSON path to the reply text, or "text"').option("--delay <ms>", "delay between probes").option("--json", "emit JSON").action(async (url, opts) => {
50439
- await aiScanCommand(url, opts);
50769
+ program2.command("ai-scan").description("Red-team an AI/LLM endpoint you own for OWASP LLM Top 10 guardrail gaps").argument("<url>", "Target AI endpoint URL").option("--categories <list>", "comma list: prompt-injection,system-prompt-leak,sensitive-disclosure,excessive-agency,output-handling").option("--template <json>", 'request body with {{PROMPT}} marker (default {"input":"{{PROMPT}}"})').option("--header <k:v...>", "extra request header (repeatable)").option("--response-path <path>", 'dotted JSON path to the reply text, or "text"').option("--delay <ms>", "delay between probes").option("--json", "emit JSON").option("--no-upload", "do not save the results to your threatcrush.com org (also THREATCRUSH_UPLOAD=0)").action(async (url, opts) => {
50770
+ const result = await aiScanCommand(url, opts);
50771
+ const categories = String(opts.categories ?? "").split(",").map((c) => c.trim()).filter(Boolean).sort();
50772
+ await uploadResult(result, {
50773
+ source: "ai-scan",
50774
+ target: cleanUrl(url),
50775
+ kind: "api",
50776
+ scope: categories.length ? `categories=${categories.join(",")}` : "",
50777
+ upload: opts.upload,
50778
+ machineReadable: Boolean(opts.json)
50779
+ });
50780
+ });
50781
+ program2.command("ai-scan-run").description("Drive the AI red-team scanner from a .mosh script").argument("<file>", "Path to a .mosh script").argument("[args...]", "Arguments passed to the script as argv").option("--no-upload", "do not save the results to your threatcrush.com org (also THREATCRUSH_UPLOAD=0)").action(async (file, args, opts) => {
50782
+ const scans = await aiScanMoshCommand(file, args ?? []);
50783
+ for (const r of scans) await uploadResult(r, { source: "ai-scan", target: cleanUrl(r.target), kind: "api", scope: `mosh=${file.split("/").pop()}`, upload: opts.upload });
50784
+ });
50785
+ var listOpts = (c) => c.option("--status <list>", "open,acknowledged,fixed,false_positive,ignored or all (default: open,acknowledged)").option("--severity <list>", "critical,high,medium,low,info").option("--source <list>", "scan,pentest,ai-scan").option("--limit <n>", "how many to show (max 500)").option("--json", "emit JSON");
50786
+ var findings = listOpts(program2.command("findings").description("List and triage your org's tracked findings (also on the web and desktop apps)")).action(async (opts) => {
50787
+ await findingsListCommand(opts);
50788
+ });
50789
+ listOpts(findings.command("list").description("List findings (default: open + acknowledged)")).action(async (opts) => {
50790
+ await findingsListCommand(opts);
50440
50791
  });
50441
- program2.command("ai-scan-run").description("Drive the AI red-team scanner from a .mosh script").argument("<file>", "Path to a .mosh script").argument("[args...]", "Arguments passed to the script as argv").action(async (file, args) => {
50442
- await aiScanMoshCommand(file, args ?? []);
50792
+ findings.command("show <id>").description("Details of one finding (id or the 8-char prefix from the list)").option("--json", "emit JSON").action(async (id, opts) => {
50793
+ await findingsShowCommand(id, opts);
50443
50794
  });
50795
+ var VERB_HELP = {
50796
+ ack: "acknowledge: seen it, working on it",
50797
+ fix: "mark fixed (a later run reopens it if it is still there)",
50798
+ fp: "mark a false positive (runs never reopen it)",
50799
+ ignore: "ignore: accepted risk (runs never reopen it)",
50800
+ reopen: "set back to open"
50801
+ };
50802
+ for (const verb of Object.keys(TRIAGE)) {
50803
+ findings.command(`${verb} <ids...>`).description(VERB_HELP[verb]).option("--note <text>", "why (shown everywhere the finding is)").action(async (ids, opts) => {
50804
+ await findingsTriageCommand(verb, ids, opts);
50805
+ });
50806
+ }
50444
50807
  program2.command("status").description("Show daemon status and loaded modules").action(async () => {
50445
50808
  await statusCommand();
50446
50809
  });
@@ -50508,7 +50871,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
50508
50871
  program2.command("logs").description("Tail daemon logs").action(async () => {
50509
50872
  console.log(LOGO2);
50510
50873
  const logPath2 = PATHS.logFile;
50511
- if (!(0, import_node_fs54.existsSync)(logPath2)) {
50874
+ if (!(0, import_node_fs55.existsSync)(logPath2)) {
50512
50875
  console.log(source_default.yellow(` No log file found at ${logPath2}`));
50513
50876
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
50514
50877
  return;
@@ -50516,7 +50879,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
50516
50879
  console.log(source_default.green(` Tailing ${logPath2}...
50517
50880
  `));
50518
50881
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
50519
- (0, import_node_child_process23.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
50882
+ (0, import_node_child_process24.execSync)(`tail -f ${logPath2}`, { stdio: "inherit" });
50520
50883
  });
50521
50884
  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) => {
50522
50885
  console.log(LOGO2);
@@ -50528,7 +50891,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
50528
50891
  for (const cmd of commands2) {
50529
50892
  console.log(source_default.green(` \u2192 ${cmd}
50530
50893
  `));
50531
- (0, import_node_child_process23.execSync)(cmd, { stdio: "inherit" });
50894
+ (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
50532
50895
  }
50533
50896
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
50534
50897
  await reportIfStillStale();
@@ -50553,7 +50916,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
50553
50916
  for (const cmd of commands) {
50554
50917
  console.log(source_default.green(` \u2192 ${cmd}
50555
50918
  `));
50556
- (0, import_node_child_process23.execSync)(cmd, { stdio: "inherit" });
50919
+ (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
50557
50920
  }
50558
50921
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
50559
50922
  if (installMode === "desktop") {
@@ -50576,10 +50939,10 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
50576
50939
  program2.command("remove").description("Uninstall ThreatCrush and the installed bundle").alias("uninstall").action(async () => {
50577
50940
  console.log(LOGO2);
50578
50941
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
50579
- const confirm = await new Promise((resolve6) => {
50942
+ const confirm = await new Promise((resolve7) => {
50580
50943
  rl.question(source_default.yellow(" Are you sure you want to uninstall ThreatCrush? (y/N): "), (answer) => {
50581
50944
  rl.close();
50582
- resolve6(answer.trim().toLowerCase());
50945
+ resolve7(answer.trim().toLowerCase());
50583
50946
  });
50584
50947
  });
50585
50948
  if (confirm !== "y" && confirm !== "yes") {
@@ -50604,7 +50967,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
50604
50967
  for (const cmd of commands) {
50605
50968
  console.log(source_default.green(` \u2192 ${cmd}
50606
50969
  `));
50607
- (0, import_node_child_process23.execSync)(cmd, { stdio: "inherit" });
50970
+ (0, import_node_child_process24.execSync)(cmd, { stdio: "inherit" });
50608
50971
  }
50609
50972
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
50610
50973
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -50681,19 +51044,19 @@ storeCmd.command("search <query>").description("Search for modules in the store"
50681
51044
  });
50682
51045
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
50683
51046
  console.log(LOGO2);
50684
- const configPath = (0, import_node_path40.join)((0, import_node_os16.homedir)(), ".threatcrush", "config.json");
51047
+ const configPath = (0, import_node_path42.join)((0, import_node_os17.homedir)(), ".threatcrush", "config.json");
50685
51048
  let email = "";
50686
51049
  try {
50687
- const config = JSON.parse((0, import_node_fs54.readFileSync)(configPath, "utf-8"));
51050
+ const config = JSON.parse((0, import_node_fs55.readFileSync)(configPath, "utf-8"));
50688
51051
  email = config.email || "";
50689
51052
  } catch {
50690
51053
  }
50691
51054
  if (!email) {
50692
51055
  const rl2 = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
50693
- email = await new Promise((resolve6) => {
51056
+ email = await new Promise((resolve7) => {
50694
51057
  rl2.question(source_default.green(" Enter your email: "), (answer) => {
50695
51058
  rl2.close();
50696
- resolve6(answer.trim());
51059
+ resolve7(answer.trim());
50697
51060
  });
50698
51061
  });
50699
51062
  if (!email || !email.includes("@")) {
@@ -50701,9 +51064,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
50701
51064
  return;
50702
51065
  }
50703
51066
  try {
50704
- const dir = (0, import_node_path40.join)((0, import_node_os16.homedir)(), ".threatcrush");
50705
- if (!(0, import_node_fs54.existsSync)(dir)) (0, import_node_fs54.mkdirSync)(dir, { recursive: true });
50706
- (0, import_node_fs54.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
51067
+ const dir = (0, import_node_path42.join)((0, import_node_os17.homedir)(), ".threatcrush");
51068
+ if (!(0, import_node_fs55.existsSync)(dir)) (0, import_node_fs55.mkdirSync)(dir, { recursive: true });
51069
+ (0, import_node_fs55.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
50707
51070
  console.log(source_default.dim(` Saved email to ${configPath}`));
50708
51071
  } catch {
50709
51072
  }
@@ -50747,10 +51110,10 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
50747
51110
  }
50748
51111
  console.log();
50749
51112
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
50750
- const confirm = await new Promise((resolve6) => {
51113
+ const confirm = await new Promise((resolve7) => {
50751
51114
  rl.question(source_default.yellow(" Publish this module? (y/N): "), (answer) => {
50752
51115
  rl.close();
50753
- resolve6(answer.trim().toLowerCase());
51116
+ resolve7(answer.trim().toLowerCase());
50754
51117
  });
50755
51118
  });
50756
51119
  if (confirm !== "y" && confirm !== "yes") {