@profullstack/threatcrush 0.13.20 → 0.13.22

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
@@ -598,8 +598,8 @@ var require_help = __commonJS({
598
598
  * @param {string} str
599
599
  * @returns {number}
600
600
  */
601
- displayWidth(str2) {
602
- return stripColor(str2).length;
601
+ displayWidth(str3) {
602
+ return stripColor(str3).length;
603
603
  }
604
604
  /**
605
605
  * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
@@ -607,11 +607,11 @@ var require_help = __commonJS({
607
607
  * @param {string} str
608
608
  * @returns {string}
609
609
  */
610
- styleTitle(str2) {
611
- return str2;
610
+ styleTitle(str3) {
611
+ return str3;
612
612
  }
613
- styleUsage(str2) {
614
- return str2.split(" ").map((word) => {
613
+ styleUsage(str3) {
614
+ return str3.split(" ").map((word) => {
615
615
  if (word === "[options]") return this.styleOptionText(word);
616
616
  if (word === "[command]") return this.styleSubcommandText(word);
617
617
  if (word[0] === "[" || word[0] === "<")
@@ -619,46 +619,46 @@ var require_help = __commonJS({
619
619
  return this.styleCommandText(word);
620
620
  }).join(" ");
621
621
  }
622
- styleCommandDescription(str2) {
623
- return this.styleDescriptionText(str2);
622
+ styleCommandDescription(str3) {
623
+ return this.styleDescriptionText(str3);
624
624
  }
625
- styleOptionDescription(str2) {
626
- return this.styleDescriptionText(str2);
625
+ styleOptionDescription(str3) {
626
+ return this.styleDescriptionText(str3);
627
627
  }
628
- styleSubcommandDescription(str2) {
629
- return this.styleDescriptionText(str2);
628
+ styleSubcommandDescription(str3) {
629
+ return this.styleDescriptionText(str3);
630
630
  }
631
- styleArgumentDescription(str2) {
632
- return this.styleDescriptionText(str2);
631
+ styleArgumentDescription(str3) {
632
+ return this.styleDescriptionText(str3);
633
633
  }
634
- styleDescriptionText(str2) {
635
- return str2;
634
+ styleDescriptionText(str3) {
635
+ return str3;
636
636
  }
637
- styleOptionTerm(str2) {
638
- return this.styleOptionText(str2);
637
+ styleOptionTerm(str3) {
638
+ return this.styleOptionText(str3);
639
639
  }
640
- styleSubcommandTerm(str2) {
641
- return str2.split(" ").map((word) => {
640
+ styleSubcommandTerm(str3) {
641
+ return str3.split(" ").map((word) => {
642
642
  if (word === "[options]") return this.styleOptionText(word);
643
643
  if (word[0] === "[" || word[0] === "<")
644
644
  return this.styleArgumentText(word);
645
645
  return this.styleSubcommandText(word);
646
646
  }).join(" ");
647
647
  }
648
- styleArgumentTerm(str2) {
649
- return this.styleArgumentText(str2);
648
+ styleArgumentTerm(str3) {
649
+ return this.styleArgumentText(str3);
650
650
  }
651
- styleOptionText(str2) {
652
- return str2;
651
+ styleOptionText(str3) {
652
+ return str3;
653
653
  }
654
- styleArgumentText(str2) {
655
- return str2;
654
+ styleArgumentText(str3) {
655
+ return str3;
656
656
  }
657
- styleSubcommandText(str2) {
658
- return str2;
657
+ styleSubcommandText(str3) {
658
+ return str3;
659
659
  }
660
- styleCommandText(str2) {
661
- return str2;
660
+ styleCommandText(str3) {
661
+ return str3;
662
662
  }
663
663
  /**
664
664
  * Calculate the pad width from the maximum term length.
@@ -681,8 +681,8 @@ var require_help = __commonJS({
681
681
  * @param {string} str
682
682
  * @returns {boolean}
683
683
  */
684
- preformatted(str2) {
685
- return /\n[^\S\r\n]/.test(str2);
684
+ preformatted(str3) {
685
+ return /\n[^\S\r\n]/.test(str3);
686
686
  }
687
687
  /**
688
688
  * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
@@ -728,9 +728,9 @@ ${itemIndentStr}`);
728
728
  * @param {number} width
729
729
  * @returns {string}
730
730
  */
731
- boxWrap(str2, width) {
732
- if (width < this.minWidthToWrap) return str2;
733
- const rawLines = str2.split(/\r\n|\n/);
731
+ boxWrap(str3, width) {
732
+ if (width < this.minWidthToWrap) return str3;
733
+ const rawLines = str3.split(/\r\n|\n/);
734
734
  const chunkPattern = /[\s]*[^\s]+/g;
735
735
  const wrappedLines = [];
736
736
  rawLines.forEach((line) => {
@@ -758,9 +758,9 @@ ${itemIndentStr}`);
758
758
  return wrappedLines.join("\n");
759
759
  }
760
760
  };
761
- function stripColor(str2) {
761
+ function stripColor(str3) {
762
762
  const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
763
- return str2.replace(sgrPattern, "");
763
+ return str3.replace(sgrPattern, "");
764
764
  }
765
765
  exports2.Help = Help2;
766
766
  exports2.stripColor = stripColor;
@@ -1020,9 +1020,9 @@ var require_option = __commonJS({
1020
1020
  return option.negate === (negativeValue === value);
1021
1021
  }
1022
1022
  };
1023
- function camelcase(str2) {
1024
- return str2.split("-").reduce((str3, word) => {
1025
- return str3 + word[0].toUpperCase() + word.slice(1);
1023
+ function camelcase(str3) {
1024
+ return str3.split("-").reduce((str4, word) => {
1025
+ return str4 + word[0].toUpperCase() + word.slice(1);
1026
1026
  });
1027
1027
  }
1028
1028
  function splitOptionFlags(flags) {
@@ -1205,14 +1205,14 @@ var require_command = __commonJS({
1205
1205
  this._showSuggestionAfterError = true;
1206
1206
  this._savedState = null;
1207
1207
  this._outputConfiguration = {
1208
- writeOut: (str2) => process10.stdout.write(str2),
1209
- writeErr: (str2) => process10.stderr.write(str2),
1210
- outputError: (str2, write) => write(str2),
1208
+ writeOut: (str3) => process10.stdout.write(str3),
1209
+ writeErr: (str3) => process10.stderr.write(str3),
1210
+ outputError: (str3, write) => write(str3),
1211
1211
  getOutHelpWidth: () => process10.stdout.isTTY ? process10.stdout.columns : void 0,
1212
1212
  getErrHelpWidth: () => process10.stderr.isTTY ? process10.stderr.columns : void 0,
1213
1213
  getOutHasColors: () => useColor() ?? (process10.stdout.isTTY && process10.stdout.hasColors?.()),
1214
1214
  getErrHasColors: () => useColor() ?? (process10.stderr.isTTY && process10.stderr.hasColors?.()),
1215
- stripColor: (str2) => stripColor(str2)
1215
+ stripColor: (str3) => stripColor(str3)
1216
1216
  };
1217
1217
  this._hidden = false;
1218
1218
  this._helpOption = void 0;
@@ -2918,18 +2918,18 @@ Expecting one of '${allowedValues.join("', '")}'`);
2918
2918
  * @param {string} [description]
2919
2919
  * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2920
2920
  */
2921
- version(str2, flags, description) {
2922
- if (str2 === void 0) return this._version;
2923
- this._version = str2;
2921
+ version(str3, flags, description) {
2922
+ if (str3 === void 0) return this._version;
2923
+ this._version = str3;
2924
2924
  flags = flags || "-V, --version";
2925
2925
  description = description || "output the version number";
2926
2926
  const versionOption = this.createOption(flags, description);
2927
2927
  this._versionOptionName = versionOption.attributeName();
2928
2928
  this._registerOption(versionOption);
2929
2929
  this.on("option:" + versionOption.name(), () => {
2930
- this._outputConfiguration.writeOut(`${str2}
2930
+ this._outputConfiguration.writeOut(`${str3}
2931
2931
  `);
2932
- this._exit(0, "commander.version", str2);
2932
+ this._exit(0, "commander.version", str3);
2933
2933
  });
2934
2934
  return this;
2935
2935
  }
@@ -2940,10 +2940,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
2940
2940
  * @param {object} [argsDescription]
2941
2941
  * @return {(string|Command)}
2942
2942
  */
2943
- description(str2, argsDescription) {
2944
- if (str2 === void 0 && argsDescription === void 0)
2943
+ description(str3, argsDescription) {
2944
+ if (str3 === void 0 && argsDescription === void 0)
2945
2945
  return this._description;
2946
- this._description = str2;
2946
+ this._description = str3;
2947
2947
  if (argsDescription) {
2948
2948
  this._argsDescription = argsDescription;
2949
2949
  }
@@ -2955,9 +2955,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2955
2955
  * @param {string} [str]
2956
2956
  * @return {(string|Command)}
2957
2957
  */
2958
- summary(str2) {
2959
- if (str2 === void 0) return this._summary;
2960
- this._summary = str2;
2958
+ summary(str3) {
2959
+ if (str3 === void 0) return this._summary;
2960
+ this._summary = str3;
2961
2961
  return this;
2962
2962
  }
2963
2963
  /**
@@ -3005,8 +3005,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
3005
3005
  * @param {string} [str]
3006
3006
  * @return {(string|Command)}
3007
3007
  */
3008
- usage(str2) {
3009
- if (str2 === void 0) {
3008
+ usage(str3) {
3009
+ if (str3 === void 0) {
3010
3010
  if (this._usage) return this._usage;
3011
3011
  const args = this.registeredArguments.map((arg) => {
3012
3012
  return humanReadableArgName(arg);
@@ -3017,7 +3017,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3017
3017
  this.registeredArguments.length ? args : []
3018
3018
  ).join(" ");
3019
3019
  }
3020
- this._usage = str2;
3020
+ this._usage = str3;
3021
3021
  return this;
3022
3022
  }
3023
3023
  /**
@@ -3026,9 +3026,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3026
3026
  * @param {string} [str]
3027
3027
  * @return {(string|Command)}
3028
3028
  */
3029
- name(str2) {
3030
- if (str2 === void 0) return this._name;
3031
- this._name = str2;
3029
+ name(str3) {
3030
+ if (str3 === void 0) return this._name;
3031
+ this._name = str3;
3032
3032
  return this;
3033
3033
  }
3034
3034
  /**
@@ -3099,17 +3099,17 @@ Expecting one of '${allowedValues.join("', '")}'`);
3099
3099
  let hasColors;
3100
3100
  let helpWidth;
3101
3101
  if (error) {
3102
- baseWrite = (str2) => this._outputConfiguration.writeErr(str2);
3102
+ baseWrite = (str3) => this._outputConfiguration.writeErr(str3);
3103
3103
  hasColors = this._outputConfiguration.getErrHasColors();
3104
3104
  helpWidth = this._outputConfiguration.getErrHelpWidth();
3105
3105
  } else {
3106
- baseWrite = (str2) => this._outputConfiguration.writeOut(str2);
3106
+ baseWrite = (str3) => this._outputConfiguration.writeOut(str3);
3107
3107
  hasColors = this._outputConfiguration.getOutHasColors();
3108
3108
  helpWidth = this._outputConfiguration.getOutHelpWidth();
3109
3109
  }
3110
- const write = (str2) => {
3111
- if (!hasColors) str2 = this._outputConfiguration.stripColor(str2);
3112
- return baseWrite(str2);
3110
+ const write = (str3) => {
3111
+ if (!hasColors) str3 = this._outputConfiguration.stripColor(str3);
3112
+ return baseWrite(str3);
3113
3113
  };
3114
3114
  return { error, write, hasColors, helpWidth };
3115
3115
  }
@@ -3370,9 +3370,9 @@ var require_parser = __commonJS({
3370
3370
  this.ii = 0;
3371
3371
  this.state = new State(this.parseStart);
3372
3372
  }
3373
- parse(str2) {
3374
- if (str2.length === 0 || str2.length == null) return;
3375
- this._buf = String(str2);
3373
+ parse(str3) {
3374
+ if (str3.length === 0 || str3.length == null) return;
3375
+ this._buf = String(str3);
3376
3376
  this.ii = -1;
3377
3377
  this.char = -1;
3378
3378
  let getNext;
@@ -4919,16 +4919,16 @@ var require_parse_string = __commonJS({
4919
4919
  module2.exports = parseString;
4920
4920
  var TOMLParser = require_toml_parser();
4921
4921
  var prettyError = require_parse_pretty_error();
4922
- function parseString(str2) {
4923
- if (global.Buffer && global.Buffer.isBuffer(str2)) {
4924
- str2 = str2.toString("utf8");
4922
+ function parseString(str3) {
4923
+ if (global.Buffer && global.Buffer.isBuffer(str3)) {
4924
+ str3 = str3.toString("utf8");
4925
4925
  }
4926
4926
  const parser = new TOMLParser();
4927
4927
  try {
4928
- parser.parse(str2);
4928
+ parser.parse(str3);
4929
4929
  return parser.finish();
4930
4930
  } catch (err) {
4931
- throw prettyError(err, str2);
4931
+ throw prettyError(err, str3);
4932
4932
  }
4933
4933
  }
4934
4934
  }
@@ -4941,27 +4941,27 @@ var require_parse_async = __commonJS({
4941
4941
  module2.exports = parseAsync;
4942
4942
  var TOMLParser = require_toml_parser();
4943
4943
  var prettyError = require_parse_pretty_error();
4944
- function parseAsync(str2, opts) {
4944
+ function parseAsync(str3, opts) {
4945
4945
  if (!opts) opts = {};
4946
4946
  const index = 0;
4947
4947
  const blocksize = opts.blocksize || 40960;
4948
4948
  const parser = new TOMLParser();
4949
- return new Promise((resolve5, reject) => {
4950
- setImmediate(parseAsyncNext, index, blocksize, resolve5, reject);
4949
+ return new Promise((resolve6, reject) => {
4950
+ setImmediate(parseAsyncNext, index, blocksize, resolve6, reject);
4951
4951
  });
4952
- function parseAsyncNext(index2, blocksize2, resolve5, reject) {
4953
- if (index2 >= str2.length) {
4952
+ function parseAsyncNext(index2, blocksize2, resolve6, reject) {
4953
+ if (index2 >= str3.length) {
4954
4954
  try {
4955
- return resolve5(parser.finish());
4955
+ return resolve6(parser.finish());
4956
4956
  } catch (err) {
4957
- return reject(prettyError(err, str2));
4957
+ return reject(prettyError(err, str3));
4958
4958
  }
4959
4959
  }
4960
4960
  try {
4961
- parser.parse(str2.slice(index2, index2 + blocksize2));
4962
- setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve5, reject);
4961
+ parser.parse(str3.slice(index2, index2 + blocksize2));
4962
+ setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve6, reject);
4963
4963
  } catch (err) {
4964
- reject(prettyError(err, str2));
4964
+ reject(prettyError(err, str3));
4965
4965
  }
4966
4966
  }
4967
4967
  }
@@ -4985,7 +4985,7 @@ var require_parse_stream = __commonJS({
4985
4985
  function parseReadable(stm) {
4986
4986
  const parser = new TOMLParser();
4987
4987
  stm.setEncoding("utf8");
4988
- return new Promise((resolve5, reject) => {
4988
+ return new Promise((resolve6, reject) => {
4989
4989
  let readable;
4990
4990
  let ended = false;
4991
4991
  let errored = false;
@@ -4993,7 +4993,7 @@ var require_parse_stream = __commonJS({
4993
4993
  ended = true;
4994
4994
  if (readable) return;
4995
4995
  try {
4996
- resolve5(parser.finish());
4996
+ resolve6(parser.finish());
4997
4997
  } catch (err) {
4998
4998
  reject(err);
4999
4999
  }
@@ -5167,22 +5167,22 @@ var require_stringify = __commonJS({
5167
5167
  return stringifyBasicString(keyStr);
5168
5168
  }
5169
5169
  }
5170
- function stringifyBasicString(str2) {
5171
- return '"' + escapeString(str2).replace(/"/g, '\\"') + '"';
5170
+ function stringifyBasicString(str3) {
5171
+ return '"' + escapeString(str3).replace(/"/g, '\\"') + '"';
5172
5172
  }
5173
- function stringifyLiteralString(str2) {
5174
- return "'" + str2 + "'";
5173
+ function stringifyLiteralString(str3) {
5174
+ return "'" + str3 + "'";
5175
5175
  }
5176
- function numpad(num, str2) {
5177
- while (str2.length < num) str2 = "0" + str2;
5178
- return str2;
5176
+ function numpad(num, str3) {
5177
+ while (str3.length < num) str3 = "0" + str3;
5178
+ return str3;
5179
5179
  }
5180
- function escapeString(str2) {
5181
- return str2.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c) => "\\u" + numpad(4, c.codePointAt(0).toString(16)));
5180
+ function escapeString(str3) {
5181
+ return str3.replace(/\\/g, "\\\\").replace(/[\b]/g, "\\b").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\f/g, "\\f").replace(/\r/g, "\\r").replace(/([\u0000-\u001f\u007f])/, (c) => "\\u" + numpad(4, c.codePointAt(0).toString(16)));
5182
5182
  }
5183
- function stringifyMultilineString(str2) {
5184
- let escaped = str2.split(/\n/).map((str3) => {
5185
- return escapeString(str3).replace(/"(?="")/g, '\\"');
5183
+ function stringifyMultilineString(str3) {
5184
+ let escaped = str3.split(/\n/).map((str4) => {
5185
+ return escapeString(str4).replace(/"(?="")/g, '\\"');
5186
5186
  }).join("\n");
5187
5187
  if (escaped.slice(-1) === '"') escaped += "\\\n";
5188
5188
  return '"""\n' + escaped + '"""';
@@ -12546,8 +12546,8 @@ var init_app = __esm({
12546
12546
  this.frame();
12547
12547
  }, interval);
12548
12548
  this.timer.unref?.();
12549
- await new Promise((resolve5) => {
12550
- this.exitResolve = resolve5;
12549
+ await new Promise((resolve6) => {
12550
+ this.exitResolve = resolve6;
12551
12551
  });
12552
12552
  }
12553
12553
  targetFps() {
@@ -12772,6 +12772,7 @@ var init_dist = __esm({
12772
12772
  "../../node_modules/.pnpm/@profullstack+hqtui@0.7.0/node_modules/@profullstack/hqtui/dist/index.js"() {
12773
12773
  "use strict";
12774
12774
  init_app();
12775
+ init_markdown();
12775
12776
  init_color();
12776
12777
  init_theme();
12777
12778
  init_widgets();
@@ -12785,26 +12786,26 @@ function isRoot() {
12785
12786
  function resolveClientSocket() {
12786
12787
  const override = process.env.THREATCRUSH_SOCKET;
12787
12788
  if (override) return override;
12788
- if ((0, import_node_fs4.existsSync)(SYSTEM_PATHS.socket)) return SYSTEM_PATHS.socket;
12789
- if ((0, import_node_fs4.existsSync)(USER_PATHS.socket)) return USER_PATHS.socket;
12789
+ if ((0, import_node_fs5.existsSync)(SYSTEM_PATHS.socket)) return SYSTEM_PATHS.socket;
12790
+ if ((0, import_node_fs5.existsSync)(USER_PATHS.socket)) return USER_PATHS.socket;
12790
12791
  return PATHS.socket;
12791
12792
  }
12792
12793
  function systemDaemonPresent() {
12793
- return (0, import_node_fs4.existsSync)(SYSTEM_PATHS.socket) || (0, import_node_fs4.existsSync)(SYSTEM_PATHS.pidFile);
12794
+ return (0, import_node_fs5.existsSync)(SYSTEM_PATHS.socket) || (0, import_node_fs5.existsSync)(SYSTEM_PATHS.pidFile);
12794
12795
  }
12795
12796
  function ensureRuntimeDirs() {
12796
12797
  for (const dir of [PATHS.configDir, PATHS.confD, PATHS.moduleDir, PATHS.logDir, PATHS.stateDir, PATHS.runDir]) {
12797
12798
  try {
12798
- (0, import_node_fs4.mkdirSync)(dir, { recursive: true });
12799
+ (0, import_node_fs5.mkdirSync)(dir, { recursive: true });
12799
12800
  } catch {
12800
12801
  }
12801
12802
  }
12802
12803
  }
12803
- var import_node_fs4, import_node_os2, import_node_path4, userBase, SYSTEM_PATHS, USER_PATHS, PATHS;
12804
+ var import_node_fs5, import_node_os2, import_node_path4, userBase, SYSTEM_PATHS, USER_PATHS, PATHS;
12804
12805
  var init_paths = __esm({
12805
12806
  "src/daemon/paths.ts"() {
12806
12807
  "use strict";
12807
- import_node_fs4 = require("fs");
12808
+ import_node_fs5 = require("fs");
12808
12809
  import_node_os2 = require("os");
12809
12810
  import_node_path4 = require("path");
12810
12811
  userBase = (0, import_node_path4.join)((0, import_node_os2.homedir)(), ".threatcrush");
@@ -12843,17 +12844,17 @@ var init_paths = __esm({
12843
12844
  // src/daemon/control-token.ts
12844
12845
  function issueControlToken() {
12845
12846
  const token = (0, import_node_crypto.randomBytes)(32).toString("hex");
12846
- (0, import_node_fs5.writeFileSync)(CONTROL_TOKEN_FILE, token, { mode: 384 });
12847
+ (0, import_node_fs6.writeFileSync)(CONTROL_TOKEN_FILE, token, { mode: 384 });
12847
12848
  try {
12848
- (0, import_node_fs5.chmodSync)(CONTROL_TOKEN_FILE, 384);
12849
+ (0, import_node_fs6.chmodSync)(CONTROL_TOKEN_FILE, 384);
12849
12850
  } catch {
12850
12851
  }
12851
12852
  return token;
12852
12853
  }
12853
12854
  function readControlToken() {
12854
- if (!(0, import_node_fs5.existsSync)(CONTROL_TOKEN_FILE)) return null;
12855
+ if (!(0, import_node_fs6.existsSync)(CONTROL_TOKEN_FILE)) return null;
12855
12856
  try {
12856
- const token = (0, import_node_fs5.readFileSync)(CONTROL_TOKEN_FILE, "utf-8").trim();
12857
+ const token = (0, import_node_fs6.readFileSync)(CONTROL_TOKEN_FILE, "utf-8").trim();
12857
12858
  return token || null;
12858
12859
  } catch {
12859
12860
  return null;
@@ -12865,12 +12866,12 @@ function tokensMatch(expected, provided) {
12865
12866
  const b = Buffer.from(provided);
12866
12867
  return a.length === b.length && (0, import_node_crypto.timingSafeEqual)(a, b);
12867
12868
  }
12868
- var import_node_crypto, import_node_fs5, import_node_path5, CONTROL_TOKEN_FILE;
12869
+ var import_node_crypto, import_node_fs6, import_node_path5, CONTROL_TOKEN_FILE;
12869
12870
  var init_control_token = __esm({
12870
12871
  "src/daemon/control-token.ts"() {
12871
12872
  "use strict";
12872
12873
  import_node_crypto = require("crypto");
12873
- import_node_fs5 = require("fs");
12874
+ import_node_fs6 = require("fs");
12874
12875
  import_node_path5 = require("path");
12875
12876
  init_paths();
12876
12877
  CONTROL_TOKEN_FILE = (0, import_node_path5.join)(PATHS.runDir, "control.token");
@@ -12884,12 +12885,12 @@ function daemonError(error) {
12884
12885
  }
12885
12886
  return new Error(error || "ipc error");
12886
12887
  }
12887
- var import_node_net, import_node_fs6, REQUEST_TIMEOUT_MS, IpcClient;
12888
+ var import_node_net, import_node_fs7, REQUEST_TIMEOUT_MS, IpcClient;
12888
12889
  var init_ipc_client = __esm({
12889
12890
  "src/core/ipc-client.ts"() {
12890
12891
  "use strict";
12891
12892
  import_node_net = require("net");
12892
- import_node_fs6 = require("fs");
12893
+ import_node_fs7 = require("fs");
12893
12894
  init_paths();
12894
12895
  init_control_token();
12895
12896
  REQUEST_TIMEOUT_MS = 1e4;
@@ -12905,13 +12906,13 @@ var init_ipc_client = __esm({
12905
12906
  pending = /* @__PURE__ */ new Map();
12906
12907
  socketPath;
12907
12908
  static isDaemonRunning(socketPath = resolveClientSocket()) {
12908
- return (0, import_node_fs6.existsSync)(socketPath);
12909
+ return (0, import_node_fs7.existsSync)(socketPath);
12909
12910
  }
12910
12911
  async connect(timeoutMs = 2e3) {
12911
- if (!(0, import_node_fs6.existsSync)(this.socketPath)) {
12912
+ if (!(0, import_node_fs7.existsSync)(this.socketPath)) {
12912
12913
  throw new Error(`threatcrushd socket not found at ${this.socketPath}`);
12913
12914
  }
12914
- return new Promise((resolve5, reject) => {
12915
+ return new Promise((resolve6, reject) => {
12915
12916
  const sock = (0, import_node_net.createConnection)(this.socketPath);
12916
12917
  const timer = setTimeout(() => {
12917
12918
  sock.destroy();
@@ -12924,7 +12925,7 @@ var init_ipc_client = __esm({
12924
12925
  sock.on("data", (chunk) => this.onData(chunk.toString()));
12925
12926
  sock.on("close", () => this.onClose());
12926
12927
  sock.on("error", () => this.onClose());
12927
- resolve5();
12928
+ resolve6();
12928
12929
  });
12929
12930
  sock.once("error", (err) => {
12930
12931
  clearTimeout(timer);
@@ -12940,14 +12941,14 @@ var init_ipc_client = __esm({
12940
12941
  if (!this.socket) throw new Error("not connected");
12941
12942
  const id = this.nextId++;
12942
12943
  const frame = params ? { id, method, params } : { id, method };
12943
- return new Promise((resolve5, reject) => {
12944
+ return new Promise((resolve6, reject) => {
12944
12945
  const timer = setTimeout(() => {
12945
12946
  this.pending.delete(id);
12946
12947
  reject(new Error(
12947
12948
  `threatcrushd did not answer "${method}" within ${REQUEST_TIMEOUT_MS / 1e3}s; if it is older than this CLI, update it`
12948
12949
  ));
12949
12950
  }, REQUEST_TIMEOUT_MS);
12950
- this.pending.set(id, { resolve: resolve5, reject, timer });
12951
+ this.pending.set(id, { resolve: resolve6, reject, timer });
12951
12952
  this.socket.write(JSON.stringify(frame) + "\n", (err) => {
12952
12953
  if (err && this.pending.delete(id)) {
12953
12954
  clearTimeout(timer);
@@ -13030,6 +13031,11 @@ var init_ipc_client = __esm({
13030
13031
  });
13031
13032
 
13032
13033
  // src/tui/state.ts
13034
+ function watchdogView(status) {
13035
+ const wd = status.watchdog;
13036
+ if (!wd) return OFF_WATCHDOG;
13037
+ return { on: wd.enabled, logged: wd.logged, answered: wd.answered, errored: wd.errored };
13038
+ }
13033
13039
  function initialState(now = Date.now()) {
13034
13040
  return {
13035
13041
  connection: "searching",
@@ -13053,12 +13059,14 @@ function initialState(now = Date.now()) {
13053
13059
  threatIndex: 0,
13054
13060
  banIndex: 0,
13055
13061
  notice: null,
13062
+ lastError: null,
13056
13063
  busy: false,
13057
13064
  moduleIndex: 0,
13058
13065
  moduleFilter: null,
13059
13066
  sourceFilter: null,
13060
13067
  showNoise: false,
13061
- muteCron: false
13068
+ muteCron: false,
13069
+ watchdog: OFF_WATCHDOG
13062
13070
  };
13063
13071
  }
13064
13072
  function isCronLine(event) {
@@ -13118,6 +13126,7 @@ function reducer(state, action) {
13118
13126
  connectionLabel: action.label,
13119
13127
  daemon: action.status,
13120
13128
  modules: action.status.modules,
13129
+ watchdog: watchdogView(action.status),
13121
13130
  counters: {
13122
13131
  events: action.status.counters.events,
13123
13132
  threats: action.status.counters.threats,
@@ -13125,7 +13134,14 @@ function reducer(state, action) {
13125
13134
  }
13126
13135
  };
13127
13136
  case "connection_lost":
13128
- return { ...state, connection: "lost", connectionLabel: action.label, daemon: null };
13137
+ return {
13138
+ ...state,
13139
+ connection: "lost",
13140
+ connectionLabel: action.label,
13141
+ daemon: null,
13142
+ watchdog: OFF_WATCHDOG,
13143
+ lastError: action.label.startsWith("demo mode") ? state.lastError : action.label
13144
+ };
13129
13145
  case "event": {
13130
13146
  if (state.paused) {
13131
13147
  return { ...state, parked: [...state.parked, action.event].slice(-FEED_LIMIT) };
@@ -13206,8 +13222,9 @@ function reducer(state, action) {
13206
13222
  notice: {
13207
13223
  text: action.text,
13208
13224
  tone: action.tone,
13209
- until: (action.now ?? Date.now()) + NOTICE_MS
13210
- }
13225
+ until: (action.now ?? Date.now()) + (action.tone === "error" ? ERROR_NOTICE_MS : NOTICE_MS)
13226
+ },
13227
+ lastError: action.tone === "error" ? action.text : state.lastError
13211
13228
  };
13212
13229
  case "busy":
13213
13230
  return { ...state, busy: action.busy };
@@ -13267,7 +13284,9 @@ function reducer(state, action) {
13267
13284
  sourceFilter: state.sourceFilter,
13268
13285
  moduleIndex: state.moduleIndex,
13269
13286
  showNoise: state.showNoise,
13270
- muteCron: state.muteCron
13287
+ muteCron: state.muteCron,
13288
+ // Reset clears the view; the watchdog log on disk is not the view.
13289
+ watchdog: state.watchdog
13271
13290
  };
13272
13291
  }
13273
13292
  }
@@ -13296,12 +13315,14 @@ function formatCount(n) {
13296
13315
  if (n < 1e6) return `${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}k`;
13297
13316
  return `${(n / 1e6).toFixed(1)}M`;
13298
13317
  }
13299
- var FOCUS_ORDER, NOTICE_MS, TIMELINE_SLOTS, FEED_LIMIT, SEVERITIES;
13318
+ var FOCUS_ORDER, NOTICE_MS, ERROR_NOTICE_MS, OFF_WATCHDOG, TIMELINE_SLOTS, FEED_LIMIT, SEVERITIES;
13300
13319
  var init_state = __esm({
13301
13320
  "src/tui/state.ts"() {
13302
13321
  "use strict";
13303
13322
  FOCUS_ORDER = ["feed", "modules", "threats", "bans"];
13304
13323
  NOTICE_MS = 6e3;
13324
+ ERROR_NOTICE_MS = 3e4;
13325
+ OFF_WATCHDOG = { on: false, logged: 0, answered: 0, errored: 0 };
13305
13326
  TIMELINE_SLOTS = 60;
13306
13327
  FEED_LIMIT = 500;
13307
13328
  SEVERITIES = ["info", "low", "medium", "high", "critical"];
@@ -13430,6 +13451,15 @@ function connectionBadge(state, demo) {
13430
13451
  }
13431
13452
  return { glyph: "\u25CB", label: "OFFLINE", color: severityColors.high };
13432
13453
  }
13454
+ function watchdogBadge(state) {
13455
+ const wd = state.watchdog;
13456
+ if (!wd.on) return null;
13457
+ const hot = wd.answered + wd.errored;
13458
+ const parts = [`\u25C9 WATCHDOG ${formatCount(wd.logged)}`];
13459
+ if (wd.answered) parts.push(`${formatCount(wd.answered)} answered`);
13460
+ if (wd.errored) parts.push(`${formatCount(wd.errored)} 5xx`);
13461
+ return { label: parts.join(" \xB7 "), color: hot > 0 ? severityColors.high : severityColors.medium };
13462
+ }
13433
13463
  function header(ui, state, theme, demo) {
13434
13464
  const badge = connectionBadge(state, demo);
13435
13465
  const uptime = state.daemon ? formatUptime(state.daemon.uptimeSeconds) : "\u2014";
@@ -13439,6 +13469,8 @@ function header(ui, state, theme, demo) {
13439
13469
  row.text(`${badge.glyph} ${badge.label}`, { fg: badge.color, bold: true, size: 12 });
13440
13470
  row.text(state.connectionLabel, { fg: theme.muted, size: "fill" });
13441
13471
  if (state.paused) row.text("\u23F8 PAUSED", { fg: severityColors.medium, bold: true, size: 10 });
13472
+ const wd = watchdogBadge(state);
13473
+ if (wd) row.text(wd.label, { fg: wd.color, bold: true, size: wd.label.length + 1 });
13442
13474
  row.text(`uptime ${uptime}`, { fg: theme.muted, size: 16, align: "right" });
13443
13475
  });
13444
13476
  });
@@ -13791,8 +13823,10 @@ function throughputPanel(parent, state, theme) {
13791
13823
  }
13792
13824
  );
13793
13825
  }
13794
- function footer(ui, state, theme) {
13826
+ function footer(ui, state, theme, options = {}) {
13795
13827
  const onFeed = state.focus === "feed";
13828
+ const notice = state.notice;
13829
+ const copyNotice = notice && options.onCopy ? () => options.onCopy?.(notice.text) : void 0;
13796
13830
  ui.statusBar({
13797
13831
  size: 1,
13798
13832
  items: [
@@ -13805,12 +13839,18 @@ function footer(ui, state, theme) {
13805
13839
  { key: "n", label: state.showNoise ? "hide 4xx" : "show 4xx" },
13806
13840
  // Only offer the cron toggle once a cron line has actually shown up, or
13807
13841
  // while it is muting, so the hint never advertises a key with nothing to act on.
13808
- ...state.muteCron || state.events.some(isCronLine) ? [{ key: "c", label: state.muteCron ? "show cron" : "mute cron" }] : []
13842
+ ...state.muteCron || state.events.some(isCronLine) ? [{ key: "c", label: state.muteCron ? "show cron" : "mute cron" }] : [],
13843
+ ...state.lastError ? [{ key: "y", label: "copy error" }] : []
13809
13844
  ],
13810
13845
  right: [
13811
13846
  // The notice is the answer to "did my keypress do anything", so it takes
13812
13847
  // the slot for as long as it lives.
13813
- { label: state.notice?.text ?? "", color: state.notice?.tone === "error" ? severityColors.high : theme.success },
13848
+ // Click it to copy the text: an error is something to paste somewhere.
13849
+ {
13850
+ label: notice ? notice.tone === "error" && copyNotice ? `${notice.text} \u29C9` : notice.text : "",
13851
+ color: notice?.tone === "error" ? severityColors.high : theme.success,
13852
+ onPress: copyNotice
13853
+ },
13814
13854
  {
13815
13855
  label: state.paused && state.parked.length > 0 ? `${state.parked.length} held` : "",
13816
13856
  color: severityColors.medium
@@ -13843,7 +13883,7 @@ function renderDashboard(ui, state, theme, options = {}) {
13843
13883
  throughputPanel(right, state, theme);
13844
13884
  });
13845
13885
  });
13846
- footer(col, state, theme);
13886
+ footer(col, state, theme, options);
13847
13887
  });
13848
13888
  }
13849
13889
  var init_view = __esm({
@@ -13899,6 +13939,15 @@ async function startDashboard(options = {}) {
13899
13939
  state = reducer(state, action);
13900
13940
  app.invalidate();
13901
13941
  };
13942
+ const copyText = (text) => {
13943
+ if (!text) return;
13944
+ try {
13945
+ process.stdout.write(clipboardSequence(text, !!process.env.TMUX));
13946
+ dispatch({ type: "notice", text: `copied to clipboard: ${text.length > 60 ? `${text.slice(0, 57)}...` : text}`, tone: "ok" });
13947
+ } catch (err) {
13948
+ dispatch({ type: "notice", text: `copy failed: ${err.message}`, tone: "error" });
13949
+ }
13950
+ };
13902
13951
  let client = null;
13903
13952
  let stopped = false;
13904
13953
  const timers = [];
@@ -14077,6 +14126,9 @@ async function startDashboard(options = {}) {
14077
14126
  case "c":
14078
14127
  dispatch({ type: "toggle_cron" });
14079
14128
  break;
14129
+ case "y":
14130
+ copyText(state.notice?.tone === "error" ? state.notice.text : state.lastError ?? state.notice?.text ?? "");
14131
+ break;
14080
14132
  case "tab":
14081
14133
  dispatch({ type: "focus_next" });
14082
14134
  break;
@@ -14113,6 +14165,7 @@ async function startDashboard(options = {}) {
14113
14165
  app.render(({ ui, theme }) => {
14114
14166
  renderDashboard(ui, state, theme, {
14115
14167
  demo: options.demo,
14168
+ onCopy: copyText,
14116
14169
  onFeedScroll: (delta) => dispatch({ type: "scroll", delta: -delta }),
14117
14170
  // One click focuses the panel, picks the row, and filters the feed to that
14118
14171
  // source — "what has this one IP done" in a single click. Clicking the
@@ -16319,22 +16372,90 @@ var source_default = chalk;
16319
16372
  // src/index.ts
16320
16373
  var import_readline = __toESM(require("readline"));
16321
16374
  var import_node_child_process15 = require("child_process");
16322
- var import_node_fs36 = require("fs");
16323
- var import_node_path24 = require("path");
16375
+ var import_node_fs40 = require("fs");
16376
+ var import_node_path27 = require("path");
16324
16377
  var import_node_os11 = require("os");
16325
16378
 
16326
16379
  // src/commands/monitor.ts
16327
- var import_node_fs7 = require("fs");
16328
- var import_node_readline = require("readline");
16380
+ var import_node_fs8 = require("fs");
16329
16381
 
16330
- // src/core/version.ts
16382
+ // src/core/log-tail.ts
16331
16383
  var import_node_fs = require("fs");
16384
+ var LogTail = class {
16385
+ /** Starts at the end of the file: history is not replayed. */
16386
+ constructor(path, fromStart = false) {
16387
+ this.path = path;
16388
+ try {
16389
+ const st = (0, import_node_fs.statSync)(path);
16390
+ this.pos = fromStart ? 0 : st.size;
16391
+ this.inode = st.ino;
16392
+ } catch {
16393
+ this.pos = 0;
16394
+ }
16395
+ }
16396
+ path;
16397
+ pos;
16398
+ partial = "";
16399
+ inode;
16400
+ get position() {
16401
+ return this.pos;
16402
+ }
16403
+ /**
16404
+ * Hands each complete new line to onLine. A line still being written (no
16405
+ * newline yet) waits for the next poll. Rotation (a new inode, or a file
16406
+ * shorter than our position) restarts at the top of the new file.
16407
+ * At most maxBytes are read per poll, so a burst is spread over polls
16408
+ * instead of blocking the daemon.
16409
+ */
16410
+ poll(onLine, maxBytes = 4 << 20) {
16411
+ let fd;
16412
+ try {
16413
+ fd = (0, import_node_fs.openSync)(this.path, "r");
16414
+ } catch {
16415
+ return 0;
16416
+ }
16417
+ try {
16418
+ const st = (0, import_node_fs.fstatSync)(fd);
16419
+ if (this.inode !== void 0 && st.ino !== this.inode || st.size < this.pos) {
16420
+ this.pos = 0;
16421
+ this.partial = "";
16422
+ }
16423
+ this.inode = st.ino;
16424
+ const end = Math.min(st.size, this.pos + maxBytes);
16425
+ if (end <= this.pos) return 0;
16426
+ const buf = Buffer.allocUnsafe(Math.min(end - this.pos, 1 << 20));
16427
+ let lines = 0;
16428
+ while (this.pos < end) {
16429
+ const want = Math.min(buf.length, end - this.pos);
16430
+ const n = (0, import_node_fs.readSync)(fd, buf, 0, want, this.pos);
16431
+ if (n <= 0) break;
16432
+ this.pos += n;
16433
+ const text = this.partial + buf.toString("utf-8", 0, n);
16434
+ const parts = text.split("\n");
16435
+ this.partial = parts.pop() ?? "";
16436
+ for (const line of parts) {
16437
+ if (line.trim()) {
16438
+ lines++;
16439
+ onLine(line);
16440
+ }
16441
+ }
16442
+ }
16443
+ if (this.partial.length > 1 << 20) this.partial = "";
16444
+ return lines;
16445
+ } finally {
16446
+ (0, import_node_fs.closeSync)(fd);
16447
+ }
16448
+ }
16449
+ };
16450
+
16451
+ // src/core/version.ts
16452
+ var import_node_fs2 = require("fs");
16332
16453
  var import_node_path = require("path");
16333
16454
  var FALLBACK_VERSION = "0.0.0";
16334
16455
  function readPackageVersion() {
16335
16456
  try {
16336
16457
  const pkg = JSON.parse(
16337
- (0, import_node_fs.readFileSync)((0, import_node_path.join)(__dirname, "..", "package.json"), "utf-8")
16458
+ (0, import_node_fs2.readFileSync)((0, import_node_path.join)(__dirname, "..", "package.json"), "utf-8")
16338
16459
  );
16339
16460
  return pkg.version || FALLBACK_VERSION;
16340
16461
  } catch {
@@ -22582,12 +22703,12 @@ var TRANSFORMS = {
22582
22703
  };
22583
22704
 
22584
22705
  // src/core/crs/libinjection.ts
22585
- var import_node_fs2 = require("fs");
22706
+ var import_node_fs3 = require("fs");
22586
22707
  var import_node_path2 = require("path");
22587
22708
  var wasm;
22588
22709
  function loadLibinjection() {
22589
22710
  if (!wasm) {
22590
- const bytes = (0, import_node_fs2.readFileSync)((0, import_node_path2.join)(__dirname, "libinjection", "libinjection.wasm"));
22711
+ const bytes = (0, import_node_fs3.readFileSync)((0, import_node_path2.join)(__dirname, "libinjection", "libinjection.wasm"));
22591
22712
  wasm = new WebAssembly.Instance(new WebAssembly.Module(bytes), {}).exports;
22592
22713
  wasm._initialize();
22593
22714
  }
@@ -23084,7 +23205,7 @@ function parseSyslogTimestamp(s) {
23084
23205
  }
23085
23206
 
23086
23207
  // src/core/config.ts
23087
- var import_node_fs3 = require("fs");
23208
+ var import_node_fs4 = require("fs");
23088
23209
  var import_node_path3 = require("path");
23089
23210
  var import_toml = __toESM(require_toml());
23090
23211
  var DEFAULT_CONFIG_PATH = "/etc/threatcrush/threatcrushd.conf";
@@ -23111,11 +23232,11 @@ var DEFAULT_CONFIG = {
23111
23232
  };
23112
23233
  function loadConfig(configPath) {
23113
23234
  const path = configPath || DEFAULT_CONFIG_PATH;
23114
- if (!(0, import_node_fs3.existsSync)(path)) {
23235
+ if (!(0, import_node_fs4.existsSync)(path)) {
23115
23236
  return { ...DEFAULT_CONFIG };
23116
23237
  }
23117
23238
  try {
23118
- const raw = (0, import_node_fs3.readFileSync)(path, "utf-8");
23239
+ const raw = (0, import_node_fs4.readFileSync)(path, "utf-8");
23119
23240
  const parsed = import_toml.default.parse(raw);
23120
23241
  return {
23121
23242
  daemon: { ...DEFAULT_CONFIG.daemon, ...parsed.daemon },
@@ -23125,6 +23246,8 @@ function loadConfig(configPath) {
23125
23246
  remediation: parsed.remediation,
23126
23247
  detection: parsed.detection,
23127
23248
  cloud: parsed.cloud,
23249
+ watchdog: parsed.watchdog,
23250
+ storage: parsed.storage,
23128
23251
  license: parsed.license
23129
23252
  };
23130
23253
  } catch {
@@ -23134,13 +23257,13 @@ function loadConfig(configPath) {
23134
23257
  function loadModuleConfigs(confDir) {
23135
23258
  const dir = confDir || DEFAULT_CONFDIR;
23136
23259
  const configs = /* @__PURE__ */ new Map();
23137
- if (!(0, import_node_fs3.existsSync)(dir)) {
23260
+ if (!(0, import_node_fs4.existsSync)(dir)) {
23138
23261
  return configs;
23139
23262
  }
23140
- const files = (0, import_node_fs3.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
23263
+ const files = (0, import_node_fs4.readdirSync)(dir).filter((f) => f.endsWith(".conf"));
23141
23264
  for (const file of files) {
23142
23265
  try {
23143
- const raw = (0, import_node_fs3.readFileSync)((0, import_node_path3.join)(dir, file), "utf-8");
23266
+ const raw = (0, import_node_fs4.readFileSync)((0, import_node_path3.join)(dir, file), "utf-8");
23144
23267
  const parsed = import_toml.default.parse(raw);
23145
23268
  for (const [name, config] of Object.entries(parsed)) {
23146
23269
  configs.set(name, config);
@@ -23261,35 +23384,70 @@ function getRecentEvents(limit = 50) {
23261
23384
  `).all(limit);
23262
23385
  return rows.map(rowToEvent);
23263
23386
  }
23387
+ var RECENT_WINDOW = 2e5;
23388
+ function eventsEverRecorded(database) {
23389
+ const row = database.prepare(`SELECT seq FROM sqlite_sequence WHERE name = 'events'`).get();
23390
+ return row?.seq ?? 0;
23391
+ }
23264
23392
  function getEventCount(since) {
23265
23393
  const database = tryDb();
23266
23394
  if (!database) return 0;
23267
23395
  if (since) {
23268
- return database.prepare(`SELECT COUNT(*) as count FROM events WHERE timestamp >= ?`).get(since.toISOString()).count;
23396
+ return database.prepare(
23397
+ `SELECT COUNT(*) as count FROM (SELECT timestamp FROM events ORDER BY id DESC LIMIT ?) WHERE timestamp >= ?`
23398
+ ).get(RECENT_WINDOW, since.toISOString()).count;
23269
23399
  }
23270
- return database.prepare(`SELECT COUNT(*) as count FROM events`).get().count;
23400
+ return eventsEverRecorded(database);
23271
23401
  }
23272
23402
  function getThreatCount(since) {
23273
23403
  const database = tryDb();
23274
23404
  if (!database) return 0;
23275
23405
  const severities = "('medium','high','critical')";
23276
- if (since) {
23277
- return database.prepare(
23278
- `SELECT COUNT(*) as count FROM events WHERE severity IN ${severities} AND timestamp >= ?`
23279
- ).get(since.toISOString()).count;
23280
- }
23406
+ const cutoff = since ? since.toISOString() : "";
23281
23407
  return database.prepare(
23282
- `SELECT COUNT(*) as count FROM events WHERE severity IN ${severities}`
23283
- ).get().count;
23408
+ `SELECT COUNT(*) as count FROM (SELECT severity, timestamp FROM events ORDER BY id DESC LIMIT ?)
23409
+ WHERE severity IN ${severities} AND timestamp >= ?`
23410
+ ).get(RECENT_WINDOW, cutoff).count;
23284
23411
  }
23285
23412
  function getTopSources(limit = 10) {
23286
23413
  const database = tryDb();
23287
23414
  if (!database) return [];
23288
23415
  return database.prepare(`
23289
- SELECT source_ip as ip, COUNT(*) as count FROM events
23416
+ SELECT source_ip as ip, COUNT(*) as count
23417
+ FROM (SELECT source_ip FROM events ORDER BY id DESC LIMIT ?)
23290
23418
  WHERE source_ip IS NOT NULL
23291
23419
  GROUP BY source_ip ORDER BY count DESC LIMIT ?
23292
- `).all(limit);
23420
+ `).all(RECENT_WINDOW, limit);
23421
+ }
23422
+ var DEFAULT_EVENT_RETENTION_SECONDS = 14 * 86400;
23423
+ var DEFAULT_MAX_EVENTS = 2e6;
23424
+ function pruneEvents(opts = {}) {
23425
+ const database = tryDb();
23426
+ if (!database) return 0;
23427
+ const retention = opts.retentionSeconds ?? DEFAULT_EVENT_RETENTION_SECONDS;
23428
+ const maxEvents = opts.maxEvents ?? DEFAULT_MAX_EVENTS;
23429
+ const batch = opts.batch ?? 5e3;
23430
+ const maxBatches = opts.maxBatches ?? 20;
23431
+ const cutoff = new Date((opts.now ?? Date.now()) - retention * 1e3).toISOString();
23432
+ const byAge = database.prepare(
23433
+ `DELETE FROM events WHERE id IN (SELECT id FROM events WHERE timestamp < ? ORDER BY id LIMIT ?)`
23434
+ );
23435
+ const lowest = database.prepare(`SELECT MIN(id) as lo, MAX(id) as hi FROM events`);
23436
+ const byCount = database.prepare(`DELETE FROM events WHERE id < ?`);
23437
+ let deleted = 0;
23438
+ for (let i = 0; i < maxBatches; i++) {
23439
+ const n = byAge.run(cutoff, batch).changes;
23440
+ deleted += n;
23441
+ if (n < batch) break;
23442
+ }
23443
+ for (let i = 0; i < maxBatches; i++) {
23444
+ const { lo, hi } = lowest.get();
23445
+ if (lo === null || hi === null || hi - lo + 1 <= maxEvents) break;
23446
+ const n = byCount.run(Math.min(lo + batch, hi - maxEvents + 1)).changes;
23447
+ deleted += n;
23448
+ if (n === 0) break;
23449
+ }
23450
+ return deleted;
23293
23451
  }
23294
23452
  function getModuleState(module2, key) {
23295
23453
  const database = db || initStateDB();
@@ -23346,9 +23504,9 @@ async function monitorCommand(options) {
23346
23504
  const unreadable = [];
23347
23505
  for (const s of LOG_SOURCES) {
23348
23506
  if (moduleFilter && !moduleFilter.includes(s.name)) continue;
23349
- if (!(0, import_node_fs7.existsSync)(s.path)) continue;
23507
+ if (!(0, import_node_fs8.existsSync)(s.path)) continue;
23350
23508
  try {
23351
- (0, import_node_fs7.accessSync)(s.path, import_node_fs7.constants.R_OK);
23509
+ (0, import_node_fs8.accessSync)(s.path, import_node_fs8.constants.R_OK);
23352
23510
  availableSources.push(s);
23353
23511
  } catch {
23354
23512
  unreadable.push(s);
@@ -23365,11 +23523,11 @@ async function monitorCommand(options) {
23365
23523
  logger.warn("No readable log files found to monitor.");
23366
23524
  logger.info("Available log paths checked:");
23367
23525
  for (const s of LOG_SOURCES) {
23368
- const exists = (0, import_node_fs7.existsSync)(s.path);
23526
+ const exists = (0, import_node_fs8.existsSync)(s.path);
23369
23527
  let readable = false;
23370
23528
  if (exists) {
23371
23529
  try {
23372
- (0, import_node_fs7.accessSync)(s.path, import_node_fs7.constants.R_OK);
23530
+ (0, import_node_fs8.accessSync)(s.path, import_node_fs8.constants.R_OK);
23373
23531
  readable = true;
23374
23532
  } catch {
23375
23533
  readable = false;
@@ -23402,31 +23560,14 @@ async function monitorCommand(options) {
23402
23560
  }
23403
23561
  function tailLog(source) {
23404
23562
  const { path, name, category } = source;
23405
- const stat = (0, import_node_fs7.statSync)(path);
23406
- let position = stat.size;
23563
+ const tail = new LogTail(path);
23564
+ let warned = false;
23407
23565
  const checkForNewData = () => {
23408
23566
  try {
23409
- const currentStat = (0, import_node_fs7.statSync)(path);
23410
- if (currentStat.size <= position) {
23411
- if (currentStat.size < position) position = 0;
23412
- return;
23413
- }
23414
- const stream = (0, import_node_fs7.createReadStream)(path, { start: position, encoding: "utf-8" });
23415
- stream.on("error", (err) => {
23416
- logger.warn(`stopped tailing ${path}: ${err.code || err.message}`);
23417
- position = currentStat.size;
23418
- });
23419
- const rl = (0, import_node_readline.createInterface)({ input: stream });
23420
- rl.on("error", () => {
23421
- });
23422
- rl.on("line", (line) => {
23423
- if (!line.trim()) return;
23424
- processLine(line, name, category);
23425
- });
23426
- rl.on("close", () => {
23427
- position = currentStat.size;
23428
- });
23429
- } catch {
23567
+ tail.poll((line) => processLine(line, name, category));
23568
+ } catch (err) {
23569
+ if (!warned) logger.warn(`cannot read ${path}: ${err.code || err.message}`);
23570
+ warned = true;
23430
23571
  }
23431
23572
  };
23432
23573
  setInterval(checkForNewData, 1e3);
@@ -23527,9 +23668,470 @@ async function runDemoMode() {
23527
23668
  });
23528
23669
  }
23529
23670
 
23530
- // src/commands/scan.ts
23671
+ // src/commands/watchdog.ts
23531
23672
  var import_node_fs10 = require("fs");
23532
- var import_node_path9 = require("path");
23673
+ var import_node_path7 = require("path");
23674
+ init_paths();
23675
+
23676
+ // src/core/watchdog.ts
23677
+ var import_node_fs9 = require("fs");
23678
+ var import_node_crypto2 = require("crypto");
23679
+ var import_node_path6 = require("path");
23680
+ var WATCHDOG_DIRNAME = "watchdog";
23681
+ var LOG_FILE = "attacks.jsonl";
23682
+ var ROTATED_FILE = "attacks.1.jsonl";
23683
+ var TRIAGE_FILE = "triage.json";
23684
+ var ROTATE_BYTES = 50 * 1024 * 1024;
23685
+ var SEEN_LIMIT = 5e3;
23686
+ var OUTCOME_ORDER = ["answered", "errored", "unknown", "redirected", "refused"];
23687
+ var TRIAGE_STATUSES = ["new", "hole", "fp", "fixed"];
23688
+ var SEVERITY_RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
23689
+ function str(v) {
23690
+ return typeof v === "string" && v !== "" && v !== "-" ? v : void 0;
23691
+ }
23692
+ function isAttack(event) {
23693
+ if (event.module === "firewall-rules") return false;
23694
+ const d = event.details ?? {};
23695
+ if (d.heartbeat) return false;
23696
+ const crs = typeof d.crs_score === "number" ? d.crs_score : 0;
23697
+ if (crs > 0 || str(d.attack_type)) return true;
23698
+ if (event.category === "web" && typeof d.status === "number" && !str(d.rule_id)) return false;
23699
+ return SEVERITY_RANK[event.severity] >= SEVERITY_RANK.medium;
23700
+ }
23701
+ function outcomeFor(status) {
23702
+ if (typeof status !== "number" || !Number.isFinite(status)) return "unknown";
23703
+ if (status >= 500) return "errored";
23704
+ if (status >= 400) return "refused";
23705
+ if (status >= 300) return "redirected";
23706
+ if (status >= 100) return "answered";
23707
+ return "unknown";
23708
+ }
23709
+ function requestFromMessage(message) {
23710
+ const m = /\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|CONNECT|TRACE|PROPFIND)\s+(\S+)/.exec(message);
23711
+ return m ? { method: m[1], url: m[2] } : {};
23712
+ }
23713
+ function signatureOf(r) {
23714
+ if (r.path) {
23715
+ return ["web", r.host ?? "", r.method ?? "", r.path, r.attack_type ?? r.rule_id ?? ""].join("|");
23716
+ }
23717
+ if (r.rule_id) return ["rule", r.module, r.rule_id].join("|");
23718
+ const shape = r.message.replace(/\b\d{1,3}(?:\.\d{1,3}){3}(?:\/\d+)?\b/g, "<ip>").replace(/\b[0-9a-f]*:[0-9a-f:]+\b/gi, "<ip>").replace(/\d+/g, "#");
23719
+ return ["msg", r.module, shape].join("|");
23720
+ }
23721
+ function findingId(signature) {
23722
+ return (0, import_node_crypto2.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
23723
+ }
23724
+ function toRecord(event) {
23725
+ const d = event.details ?? {};
23726
+ const fromMsg = requestFromMessage(event.message);
23727
+ const url = str(d.url) ?? fromMsg.url;
23728
+ const path = str(d.path) ?? (url ? url.split("?")[0] : void 0);
23729
+ const status = typeof d.status === "number" ? d.status : void 0;
23730
+ const base = {
23731
+ module: event.module,
23732
+ host: str(d.host),
23733
+ method: str(d.method) ?? fromMsg.method,
23734
+ path,
23735
+ attack_type: str(d.attack_type),
23736
+ rule_id: str(d.rule_id),
23737
+ message: event.message
23738
+ };
23739
+ const timestamp = event.timestamp instanceof Date ? event.timestamp : new Date(event.timestamp);
23740
+ const record = {
23741
+ v: 1,
23742
+ id: findingId(signatureOf(base)),
23743
+ at: (Number.isNaN(timestamp.getTime()) ? /* @__PURE__ */ new Date() : timestamp).toISOString(),
23744
+ category: event.category,
23745
+ severity: event.severity,
23746
+ ...base,
23747
+ ip: event.source_ip,
23748
+ url,
23749
+ status,
23750
+ outcome: outcomeFor(status),
23751
+ crs_score: typeof d.crs_score === "number" ? d.crs_score : void 0,
23752
+ ua: str(d.ua)
23753
+ };
23754
+ for (const k of Object.keys(record)) {
23755
+ if (record[k] === void 0) delete record[k];
23756
+ }
23757
+ return record;
23758
+ }
23759
+ function dedupeKey(r) {
23760
+ return `${r.at}|${r.ip ?? ""}|${r.message}`;
23761
+ }
23762
+ function isShared(dir) {
23763
+ try {
23764
+ return ((0, import_node_fs9.statSync)(dir).mode & 1024) !== 0;
23765
+ } catch {
23766
+ return false;
23767
+ }
23768
+ }
23769
+ var WatchdogLog = class {
23770
+ dir;
23771
+ file;
23772
+ buffer = [];
23773
+ seen = /* @__PURE__ */ new Set();
23774
+ shareGid;
23775
+ stats = { logged: 0, answered: 0, errored: 0 };
23776
+ constructor(dir, options = {}) {
23777
+ this.dir = dir;
23778
+ this.file = (0, import_node_path6.join)(dir, LOG_FILE);
23779
+ this.shareGid = options.shareGid;
23780
+ (0, import_node_fs9.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
23781
+ if (this.shareGid !== void 0) {
23782
+ (0, import_node_fs9.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
23783
+ (0, import_node_fs9.chmodSync)(dir, 1528);
23784
+ }
23785
+ for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
23786
+ }
23787
+ remember(key) {
23788
+ this.seen.add(key);
23789
+ if (this.seen.size > SEEN_LIMIT) {
23790
+ const oldest = this.seen.values().next().value;
23791
+ if (oldest !== void 0) this.seen.delete(oldest);
23792
+ }
23793
+ }
23794
+ /** Logs the event if it is an attack not already logged. Returns the record when it was. */
23795
+ record(event) {
23796
+ if (!isAttack(event)) return null;
23797
+ const rec = toRecord(event);
23798
+ const key = dedupeKey(rec);
23799
+ if (this.seen.has(key)) return null;
23800
+ this.remember(key);
23801
+ this.buffer.push(JSON.stringify(rec));
23802
+ this.stats.logged++;
23803
+ if (rec.outcome === "answered") this.stats.answered++;
23804
+ if (rec.outcome === "errored") this.stats.errored++;
23805
+ return rec;
23806
+ }
23807
+ flush() {
23808
+ if (this.buffer.length === 0) return;
23809
+ const chunk = this.buffer.join("\n") + "\n";
23810
+ this.buffer = [];
23811
+ try {
23812
+ if ((0, import_node_fs9.statSync)(this.file).size > ROTATE_BYTES) {
23813
+ (0, import_node_fs9.renameSync)(this.file, (0, import_node_path6.join)(this.dir, ROTATED_FILE));
23814
+ }
23815
+ } catch {
23816
+ }
23817
+ (0, import_node_fs9.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
23818
+ if (this.shareGid !== void 0) {
23819
+ try {
23820
+ (0, import_node_fs9.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
23821
+ (0, import_node_fs9.chmodSync)(this.file, 432);
23822
+ } catch {
23823
+ }
23824
+ }
23825
+ }
23826
+ };
23827
+ function parseLines(text) {
23828
+ const out = [];
23829
+ for (const line of text.split("\n")) {
23830
+ if (!line) continue;
23831
+ try {
23832
+ const r = JSON.parse(line);
23833
+ if (r && r.v === 1 && typeof r.id === "string") out.push(r);
23834
+ } catch {
23835
+ }
23836
+ }
23837
+ return out;
23838
+ }
23839
+ function readTail(file, bytes) {
23840
+ let fd;
23841
+ try {
23842
+ fd = (0, import_node_fs9.openSync)(file, "r");
23843
+ } catch (err) {
23844
+ if (err.code === "ENOENT") return [];
23845
+ throw err;
23846
+ }
23847
+ try {
23848
+ const size = (0, import_node_fs9.fstatSync)(fd).size;
23849
+ const start = Math.max(0, size - bytes);
23850
+ const buf = Buffer.alloc(size - start);
23851
+ (0, import_node_fs9.readSync)(fd, buf, 0, buf.length, start);
23852
+ let text = buf.toString("utf8");
23853
+ if (start > 0) text = text.slice(text.indexOf("\n") + 1);
23854
+ return parseLines(text);
23855
+ } finally {
23856
+ (0, import_node_fs9.closeSync)(fd);
23857
+ }
23858
+ }
23859
+ function readAttacks(dir) {
23860
+ const out = [];
23861
+ for (const name of [ROTATED_FILE, LOG_FILE]) {
23862
+ const file = (0, import_node_path6.join)(dir, name);
23863
+ if ((0, import_node_fs9.existsSync)(file)) out.push(...parseLines((0, import_node_fs9.readFileSync)(file, "utf8")));
23864
+ }
23865
+ return out;
23866
+ }
23867
+ function readTriage(dir) {
23868
+ const file = (0, import_node_path6.join)(dir, TRIAGE_FILE);
23869
+ if (!(0, import_node_fs9.existsSync)(file)) return {};
23870
+ try {
23871
+ return JSON.parse((0, import_node_fs9.readFileSync)(file, "utf8"));
23872
+ } catch {
23873
+ return {};
23874
+ }
23875
+ }
23876
+ function writeTriage(dir, map) {
23877
+ (0, import_node_fs9.mkdirSync)(dir, { recursive: true });
23878
+ const file = (0, import_node_path6.join)(dir, TRIAGE_FILE);
23879
+ const mode = isShared(dir) ? 432 : 384;
23880
+ (0, import_node_fs9.writeFileSync)(`${file}.tmp`, JSON.stringify(map, null, 2) + "\n", { mode });
23881
+ try {
23882
+ (0, import_node_fs9.chmodSync)(`${file}.tmp`, mode);
23883
+ } catch {
23884
+ }
23885
+ (0, import_node_fs9.renameSync)(`${file}.tmp`, file);
23886
+ }
23887
+ function setTriage(dir, id, update, now = /* @__PURE__ */ new Date()) {
23888
+ const map = readTriage(dir);
23889
+ const prev = map[id];
23890
+ const entry = {
23891
+ status: update.status,
23892
+ note: update.note ?? prev?.note,
23893
+ pr: update.pr ?? prev?.pr,
23894
+ updated_at: now.toISOString()
23895
+ };
23896
+ if (!entry.note) delete entry.note;
23897
+ if (!entry.pr) delete entry.pr;
23898
+ map[id] = entry;
23899
+ writeTriage(dir, map);
23900
+ return entry;
23901
+ }
23902
+ var SOURCES_CAP = 20;
23903
+ var SAMPLES_CAP = 5;
23904
+ function groupFindings(records, triage = {}) {
23905
+ const byId = /* @__PURE__ */ new Map();
23906
+ for (const r of records) {
23907
+ let f = byId.get(r.id);
23908
+ if (!f) {
23909
+ f = {
23910
+ id: r.id,
23911
+ outcome: r.outcome,
23912
+ severity: r.severity,
23913
+ count: 0,
23914
+ first_seen: r.at,
23915
+ last_seen: r.at,
23916
+ host: r.host,
23917
+ method: r.method,
23918
+ path: r.path,
23919
+ attack_type: r.attack_type,
23920
+ rule_id: r.rule_id,
23921
+ module: r.module,
23922
+ title: r.message,
23923
+ sources: [],
23924
+ source_count: 0,
23925
+ statuses: {},
23926
+ samples: [],
23927
+ triage: triage[r.id] ?? { status: "new", updated_at: r.at },
23928
+ _ips: /* @__PURE__ */ new Set()
23929
+ };
23930
+ byId.set(r.id, f);
23931
+ }
23932
+ f.count++;
23933
+ if (r.at < f.first_seen) f.first_seen = r.at;
23934
+ if (r.at > f.last_seen) f.last_seen = r.at;
23935
+ if (OUTCOME_ORDER.indexOf(r.outcome) < OUTCOME_ORDER.indexOf(f.outcome)) f.outcome = r.outcome;
23936
+ if (SEVERITY_RANK[r.severity] > SEVERITY_RANK[f.severity]) f.severity = r.severity;
23937
+ if (r.status !== void 0) f.statuses[r.status] = (f.statuses[r.status] ?? 0) + 1;
23938
+ if (r.ip && !f._ips.has(r.ip)) {
23939
+ f._ips.add(r.ip);
23940
+ if (f.sources.length < SOURCES_CAP) f.sources.push(r.ip);
23941
+ }
23942
+ f.samples.push(r);
23943
+ }
23944
+ const findings = [];
23945
+ for (const f of byId.values()) {
23946
+ const { _ips, ...rest } = f;
23947
+ rest.source_count = _ips.size;
23948
+ 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);
23949
+ findings.push(rest);
23950
+ }
23951
+ const triaged = (f) => f.triage.status === "new" ? 0 : 1;
23952
+ return findings.sort((a, b) => triaged(a) - triaged(b) || OUTCOME_ORDER.indexOf(a.outcome) - OUTCOME_ORDER.indexOf(b.outcome) || SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] || b.count - a.count || b.last_seen.localeCompare(a.last_seen));
23953
+ }
23954
+ function findFinding(findings, id) {
23955
+ const exact = findings.find((f) => f.id === id);
23956
+ if (exact) return exact;
23957
+ const matches2 = findings.filter((f) => f.id.startsWith(id));
23958
+ return matches2.length === 1 ? matches2[0] : null;
23959
+ }
23960
+ function shellQuote(s) {
23961
+ return `'${s.replace(/'/g, `'\\''`)}'`;
23962
+ }
23963
+ function reproCommand(r) {
23964
+ if (!r.host || !r.url) return null;
23965
+ const method = r.method && r.method !== "GET" ? ` -X ${r.method}` : "";
23966
+ return `curl -sk -o /dev/null -w '%{http_code}\\n'${method} ${shellQuote(`https://${r.host}${r.url}`)}`;
23967
+ }
23968
+ function findingBrief(f) {
23969
+ const lines = [];
23970
+ const where2 = f.host ? `${f.host} ${f.method ?? ""} ${f.path ?? ""}`.trim() : f.title;
23971
+ lines.push(`# Watchdog finding ${f.id}: ${f.attack_type ?? f.rule_id ?? f.module} on ${where2}`);
23972
+ lines.push("");
23973
+ lines.push(`- **Outcome:** ${f.outcome}${outcomeExplainer(f.outcome)}`);
23974
+ lines.push(`- **Severity:** ${f.severity} \xB7 **hits:** ${f.count} from ${f.source_count} source(s)`);
23975
+ lines.push(`- **Seen:** ${f.first_seen} \u2192 ${f.last_seen}`);
23976
+ const statuses = Object.entries(f.statuses).map(([s, n]) => `${s}\xD7${n}`).join(", ");
23977
+ if (statuses) lines.push(`- **Status codes:** ${statuses}`);
23978
+ if (f.host) lines.push(`- **Vhost:** ${f.host}`);
23979
+ if (f.path) lines.push(`- **Endpoint:** ${f.method ?? ""} ${f.path}`.replace(" ", " "));
23980
+ if (f.rule_id) lines.push(`- **Rule:** ${f.rule_id}`);
23981
+ lines.push(`- **Detected by:** ${f.module}`);
23982
+ lines.push(`- **Triage:** ${f.triage.status}${f.triage.note ? ` \u2014 ${f.triage.note}` : ""}${f.triage.pr ? ` (${f.triage.pr})` : ""}`);
23983
+ lines.push("");
23984
+ lines.push("## Sample requests");
23985
+ lines.push("");
23986
+ for (const s of f.samples) {
23987
+ lines.push(`- \`${s.at}\` ${s.ip ?? "?"} \u2192 ${s.status ?? "\u2014"} \`${(s.method ? `${s.method} ` : "") + (s.url ?? s.message)}\``);
23988
+ if (s.ua) lines.push(` - UA: \`${s.ua}\``);
23989
+ }
23990
+ const repro = f.samples.map(reproCommand).find(Boolean);
23991
+ if (repro) {
23992
+ lines.push("");
23993
+ lines.push("## Reproduce (against our own site only)");
23994
+ lines.push("");
23995
+ lines.push("```sh");
23996
+ lines.push(repro);
23997
+ lines.push("```");
23998
+ }
23999
+ lines.push("");
24000
+ lines.push("## Verify, then fix");
24001
+ lines.push("");
24002
+ lines.push("1. Find the repo that serves this vhost and the handler for the endpoint above.");
24003
+ lines.push("2. Decide whether the request did anything it should not: read the handler, replay the sample against a dev instance, check the response body, not just the status code.");
24004
+ lines.push(`3. Not a hole: \`threatcrush watchdog mark ${f.id} fp --note "<why>"\`.`);
24005
+ lines.push("4. A hole: write a failing test that sends the sample payload, fix the handler, open a PR with this brief in the body, merge it once checks are green and ship it.");
24006
+ lines.push(`5. Record it: \`threatcrush watchdog mark ${f.id} fixed --pr <url>\`.`);
24007
+ return lines.join("\n") + "\n";
24008
+ }
24009
+ function outcomeExplainer(o) {
24010
+ switch (o) {
24011
+ case "answered":
24012
+ return " \u2014 the app served this request (2xx). Verify it did not do what the payload asked.";
24013
+ case "errored":
24014
+ return " \u2014 the app crashed on it (5xx). Input reached code that did not expect it.";
24015
+ case "redirected":
24016
+ return " \u2014 answered with a redirect (3xx); usually auth bouncing it.";
24017
+ case "refused":
24018
+ return " \u2014 refused (4xx). Probably not a hole; kept for the record.";
24019
+ default:
24020
+ return " \u2014 not an HTTP request (ssh, network, rule); check the detection itself.";
24021
+ }
24022
+ }
24023
+
24024
+ // src/commands/watchdog.ts
24025
+ function resolveWatchdogDir(dir) {
24026
+ if (dir) return dir;
24027
+ if (process.env.THREATCRUSH_WATCHDOG_DIR) return process.env.THREATCRUSH_WATCHDOG_DIR;
24028
+ const system = (0, import_node_path7.join)("/var/lib/threatcrush", WATCHDOG_DIRNAME);
24029
+ if ((0, import_node_fs10.existsSync)(system)) return system;
24030
+ return (0, import_node_path7.join)(PATHS.stateDir, WATCHDOG_DIRNAME);
24031
+ }
24032
+ function load(dir) {
24033
+ return groupFindings(readAttacks(dir), readTriage(dir));
24034
+ }
24035
+ var OUTCOME_COLOR = {
24036
+ answered: source_default.red.bold,
24037
+ errored: source_default.magenta.bold,
24038
+ unknown: source_default.yellow,
24039
+ redirected: source_default.cyan,
24040
+ refused: source_default.gray
24041
+ };
24042
+ var TRIAGE_COLOR = {
24043
+ new: source_default.white,
24044
+ hole: source_default.red.bold,
24045
+ fp: source_default.gray,
24046
+ fixed: source_default.green
24047
+ };
24048
+ function where(f) {
24049
+ if (f.path) return `${f.host ? `${f.host} ` : ""}${f.method ?? ""} ${f.path}`.trim();
24050
+ return f.title;
24051
+ }
24052
+ function watchdogListCommand(opts) {
24053
+ const dir = resolveWatchdogDir(opts.dir);
24054
+ let findings = load(dir);
24055
+ if (opts.status) findings = findings.filter((f) => f.triage.status === opts.status);
24056
+ if (opts.outcome) findings = findings.filter((f) => f.outcome === opts.outcome);
24057
+ if (!opts.all && !opts.status && !opts.outcome) {
24058
+ findings = findings.filter((f) => (f.triage.status === "new" || f.triage.status === "hole") && f.outcome !== "refused");
24059
+ }
24060
+ const limit = opts.limit ? Math.max(1, parseInt(opts.limit, 10) || 50) : 50;
24061
+ if (opts.json) {
24062
+ console.log(JSON.stringify(findings.slice(0, limit), null, 2));
24063
+ return;
24064
+ }
24065
+ if (findings.length === 0) {
24066
+ const empty = (0, import_node_fs10.existsSync)((0, import_node_path7.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).`;
24067
+ console.log(source_default.dim(empty));
24068
+ return;
24069
+ }
24070
+ console.log(source_default.dim(`${dir} \xB7 ${findings.length} finding(s)
24071
+ `));
24072
+ for (const f of findings.slice(0, limit)) {
24073
+ const statuses = Object.keys(f.statuses).join(",") || "\u2014";
24074
+ console.log(
24075
+ `${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)}`
24076
+ );
24077
+ }
24078
+ if (findings.length > limit) console.log(source_default.dim(`
24079
+ \u2026 ${findings.length - limit} more (--limit)`));
24080
+ console.log(source_default.dim("\nthreatcrush watchdog show <id> \xB7 brief <id> \xB7 mark <id> hole|fp|fixed"));
24081
+ }
24082
+ function resolve(dir, id) {
24083
+ const found = findFinding(load(dir), id);
24084
+ if (!found) {
24085
+ console.error(source_default.red(`No single finding matches "${id}" in ${dir}.`));
24086
+ process.exit(1);
24087
+ }
24088
+ return found;
24089
+ }
24090
+ function watchdogShowCommand(id, opts) {
24091
+ const dir = resolveWatchdogDir(opts.dir);
24092
+ const f = resolve(dir, id);
24093
+ if (opts.json) {
24094
+ console.log(JSON.stringify(f, null, 2));
24095
+ return;
24096
+ }
24097
+ console.log(`${source_default.bold(f.id)} ${OUTCOME_COLOR[f.outcome](f.outcome)} ${TRIAGE_COLOR[f.triage.status](f.triage.status)}`);
24098
+ console.log(`${source_default.cyan(f.attack_type ?? f.rule_id ?? f.module)} ${where(f)}`);
24099
+ console.log(source_default.dim(`${f.count} hit(s) from ${f.source_count} source(s) \xB7 ${f.first_seen} \u2192 ${f.last_seen}`));
24100
+ const statuses = Object.entries(f.statuses).map(([s, n]) => `${s}\xD7${n}`).join(" ");
24101
+ if (statuses) console.log(source_default.dim(`status codes: ${statuses}`));
24102
+ if (f.triage.note) console.log(`note: ${f.triage.note}`);
24103
+ if (f.triage.pr) console.log(`pr: ${f.triage.pr}`);
24104
+ console.log("\nsamples:");
24105
+ for (const s of f.samples) {
24106
+ console.log(` ${source_default.dim(s.at)} ${s.ip ?? "?"} \u2192 ${s.status ?? "\u2014"} ${s.method ? `${s.method} ` : ""}${s.url ?? s.message}`);
24107
+ }
24108
+ console.log(`
24109
+ sources: ${f.sources.join(", ")}${f.source_count > f.sources.length ? ` (+${f.source_count - f.sources.length})` : ""}`);
24110
+ const repro = f.samples.map(reproCommand).find(Boolean);
24111
+ if (repro) console.log(`
24112
+ reproduce: ${repro}`);
24113
+ }
24114
+ function watchdogBriefCommand(id, opts) {
24115
+ const dir = resolveWatchdogDir(opts.dir);
24116
+ process.stdout.write(findingBrief(resolve(dir, id)));
24117
+ }
24118
+ function watchdogMarkCommand(id, status, opts) {
24119
+ if (!TRIAGE_STATUSES.includes(status)) {
24120
+ console.error(source_default.red(`Status must be one of: ${TRIAGE_STATUSES.join(", ")}`));
24121
+ process.exit(1);
24122
+ }
24123
+ const dir = resolveWatchdogDir(opts.dir);
24124
+ const f = resolve(dir, id);
24125
+ const entry = setTriage(dir, f.id, { status, note: opts.note, pr: opts.pr });
24126
+ console.log(`${source_default.bold(f.id)} \u2192 ${TRIAGE_COLOR[entry.status](entry.status)}${entry.pr ? ` (${entry.pr})` : ""}`);
24127
+ }
24128
+ function watchdogPathCommand(opts) {
24129
+ console.log(resolveWatchdogDir(opts.dir));
24130
+ }
24131
+
24132
+ // src/commands/scan.ts
24133
+ var import_node_fs13 = require("fs");
24134
+ var import_node_path11 = require("path");
23533
24135
 
23534
24136
  // ../../node_modules/.pnpm/ora@8.2.0/node_modules/ora/index.js
23535
24137
  var import_node_process7 = __toESM(require("process"), 1);
@@ -23857,7 +24459,7 @@ var {
23857
24459
  *
23858
24460
  * @internal
23859
24461
  */
23860
- load,
24462
+ load: load2,
23861
24463
  /**
23862
24464
  * Unload the listeners. Likely you never need to call this, unless
23863
24465
  * doing a rather deep integration with signal-exit functionality.
@@ -27158,7 +27760,7 @@ function isTestPath(relativePath) {
27158
27760
  function rustCodeLines(lines) {
27159
27761
  const out = [];
27160
27762
  let commentDepth = 0;
27161
- let str2 = null;
27763
+ let str3 = null;
27162
27764
  for (const line of lines) {
27163
27765
  let code = "";
27164
27766
  let i = 0;
@@ -27182,15 +27784,15 @@ function rustCodeLines(lines) {
27182
27784
  i += 1;
27183
27785
  continue;
27184
27786
  }
27185
- if (str2) {
27186
- if (str2.raw) {
27787
+ if (str3) {
27788
+ if (str3.raw) {
27187
27789
  if (c === '"') {
27188
27790
  let hashes = 0;
27189
27791
  while (line[i + 1 + hashes] === "#") hashes += 1;
27190
- if (hashes >= str2.hashes) {
27191
- code += " ".repeat(1 + str2.hashes);
27192
- i += 1 + str2.hashes;
27193
- str2 = null;
27792
+ if (hashes >= str3.hashes) {
27793
+ code += " ".repeat(1 + str3.hashes);
27794
+ i += 1 + str3.hashes;
27795
+ str3 = null;
27194
27796
  continue;
27195
27797
  }
27196
27798
  }
@@ -27204,7 +27806,7 @@ function rustCodeLines(lines) {
27204
27806
  continue;
27205
27807
  }
27206
27808
  if (c === '"') {
27207
- str2 = null;
27809
+ str3 = null;
27208
27810
  code += " ";
27209
27811
  i += 1;
27210
27812
  continue;
@@ -27226,14 +27828,14 @@ function rustCodeLines(lines) {
27226
27828
  if (i === 0 || !/[A-Za-z0-9_]/.test(line[i - 1])) {
27227
27829
  const raw = /^b?r(#*)"/.exec(line.slice(i));
27228
27830
  if (raw) {
27229
- str2 = { raw: true, hashes: raw[1].length };
27831
+ str3 = { raw: true, hashes: raw[1].length };
27230
27832
  code += " ".repeat(raw[0].length);
27231
27833
  i += raw[0].length;
27232
27834
  continue;
27233
27835
  }
27234
27836
  }
27235
27837
  if (c === '"') {
27236
- str2 = { raw: false, hashes: 0 };
27838
+ str3 = { raw: false, hashes: 0 };
27237
27839
  code += " ";
27238
27840
  i += 1;
27239
27841
  continue;
@@ -27443,8 +28045,8 @@ function meetsFailThreshold(findings, threshold) {
27443
28045
  }
27444
28046
 
27445
28047
  // ../../packages/scan/src/node/walk.ts
27446
- var import_node_fs8 = require("fs");
27447
- var import_node_path6 = require("path");
28048
+ var import_node_fs11 = require("fs");
28049
+ var import_node_path8 = require("path");
27448
28050
  function compileExcludes(patterns) {
27449
28051
  const matchers = patterns.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith("#")).map(compilePattern);
27450
28052
  if (matchers.length === 0) return () => false;
@@ -27515,7 +28117,7 @@ function matchPrefix(parts, segs) {
27515
28117
  }
27516
28118
  function readIgnoreFile(root) {
27517
28119
  try {
27518
- return (0, import_node_fs8.readFileSync)((0, import_node_path6.join)(root, ".threatcrushignore"), "utf-8").split("\n");
28120
+ return (0, import_node_fs11.readFileSync)((0, import_node_path8.join)(root, ".threatcrushignore"), "utf-8").split("\n");
27519
28121
  } catch {
27520
28122
  return [];
27521
28123
  }
@@ -27531,16 +28133,16 @@ function scanPath(targetPath, options = {}) {
27531
28133
  let excluded = 0;
27532
28134
  const rootIsDirectory = (() => {
27533
28135
  try {
27534
- return (0, import_node_fs8.statSync)(targetPath).isDirectory();
28136
+ return (0, import_node_fs11.statSync)(targetPath).isDirectory();
27535
28137
  } catch {
27536
28138
  return true;
27537
28139
  }
27538
28140
  })();
27539
- const walkRoot = rootIsDirectory ? targetPath : (0, import_node_path6.dirname)(targetPath);
28141
+ const walkRoot = rootIsDirectory ? targetPath : (0, import_node_path8.dirname)(targetPath);
27540
28142
  const isExcluded = compileExcludes([...options.exclude ?? [], ...readIgnoreFile(walkRoot)]);
27541
28143
  const scanFile = (fullPath, filename) => {
27542
28144
  const relativePath = toRelative(walkRoot, fullPath);
27543
- const extension = (0, import_node_path6.extname)(filename).toLowerCase();
28145
+ const extension = (0, import_node_path8.extname)(filename).toLowerCase();
27544
28146
  const isManifest = filename === "package.json" || filename === "requirements.txt";
27545
28147
  const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env");
27546
28148
  const mayDeclareInterpreter = !scannable && !isManifest && extension === "";
@@ -27552,26 +28154,26 @@ function scanPath(targetPath, options = {}) {
27552
28154
  let handle;
27553
28155
  let declared = null;
27554
28156
  try {
27555
- handle = (0, import_node_fs8.openSync)(fullPath, "r");
28157
+ handle = (0, import_node_fs11.openSync)(fullPath, "r");
27556
28158
  } catch {
27557
28159
  unreadable.push(relativePath);
27558
28160
  return;
27559
28161
  }
27560
28162
  try {
27561
- if ((0, import_node_fs8.fstatSync)(handle).size > maxFileBytes) return;
28163
+ if ((0, import_node_fs11.fstatSync)(handle).size > maxFileBytes) return;
27562
28164
  if (mayDeclareInterpreter) {
27563
28165
  const prefix = Buffer.alloc(128);
27564
- const read = (0, import_node_fs8.readSync)(handle, prefix, 0, prefix.length, 0);
28166
+ const read = (0, import_node_fs11.readSync)(handle, prefix, 0, prefix.length, 0);
27565
28167
  declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
27566
28168
  if (!declared) return;
27567
28169
  }
27568
- text = (0, import_node_fs8.readFileSync)(handle, "utf-8");
28170
+ text = (0, import_node_fs11.readFileSync)(handle, "utf-8");
27569
28171
  } catch {
27570
28172
  unreadable.push(relativePath);
27571
28173
  return;
27572
28174
  } finally {
27573
28175
  try {
27574
- (0, import_node_fs8.closeSync)(handle);
28176
+ (0, import_node_fs11.closeSync)(handle);
27575
28177
  } catch {
27576
28178
  }
27577
28179
  }
@@ -27589,13 +28191,13 @@ function scanPath(targetPath, options = {}) {
27589
28191
  const walk = (currentPath) => {
27590
28192
  let entries;
27591
28193
  try {
27592
- entries = (0, import_node_fs8.readdirSync)(currentPath, { withFileTypes: true });
28194
+ entries = (0, import_node_fs11.readdirSync)(currentPath, { withFileTypes: true });
27593
28195
  } catch {
27594
28196
  unreadable.push(toRelative(walkRoot, currentPath));
27595
28197
  return;
27596
28198
  }
27597
28199
  for (const entry of entries) {
27598
- const fullPath = (0, import_node_path6.join)(currentPath, entry.name);
28200
+ const fullPath = (0, import_node_path8.join)(currentPath, entry.name);
27599
28201
  const relativePath = toRelative(walkRoot, fullPath);
27600
28202
  if (entry.isDirectory()) {
27601
28203
  if (SKIP_DIRS.has(entry.name)) continue;
@@ -27619,7 +28221,7 @@ function scanPath(targetPath, options = {}) {
27619
28221
  } else if (isExcluded(toRelative(walkRoot, targetPath))) {
27620
28222
  excluded += 1;
27621
28223
  } else {
27622
- scanFile(targetPath, (0, import_node_path6.basename)(targetPath));
28224
+ scanFile(targetPath, (0, import_node_path8.basename)(targetPath));
27623
28225
  }
27624
28226
  if (options.missingControls) findings.push(...controls.findings());
27625
28227
  const filtered = allowed ? findings.filter((f) => allowed.has(f.category)) : findings;
@@ -27651,22 +28253,22 @@ function recordSensitiveFile(filename, relativePath, sink, fileFindings) {
27651
28253
  }
27652
28254
  }
27653
28255
  function toRelative(base, target) {
27654
- const rel = (0, import_node_path6.relative)(base, target);
27655
- return (rel === "" ? target : rel).split(import_node_path6.sep).join("/");
28256
+ const rel = (0, import_node_path8.relative)(base, target);
28257
+ return (rel === "" ? target : rel).split(import_node_path8.sep).join("/");
27656
28258
  }
27657
28259
 
27658
28260
  // ../../packages/scan/src/node/dependencies.ts
27659
- var import_node_fs9 = require("fs");
27660
- var import_node_path7 = require("path");
28261
+ var import_node_fs12 = require("fs");
28262
+ var import_node_path9 = require("path");
27661
28263
  var MAX_DEPS_PER_LOCKFILE = 50;
27662
28264
  async function scanDependencies(targetPath) {
27663
28265
  const findings = [];
27664
28266
  for (const { file, ecosystem, parse: parse2 } of LOCKFILES) {
27665
- const lockPath = (0, import_node_path7.join)(targetPath, file);
27666
- if (!(0, import_node_fs9.existsSync)(lockPath)) continue;
28267
+ const lockPath = (0, import_node_path9.join)(targetPath, file);
28268
+ if (!(0, import_node_fs12.existsSync)(lockPath)) continue;
27667
28269
  let deps;
27668
28270
  try {
27669
- deps = dedupe(parse2((0, import_node_fs9.readFileSync)(lockPath, "utf-8")));
28271
+ deps = dedupe(parse2((0, import_node_fs12.readFileSync)(lockPath, "utf-8")));
27670
28272
  } catch {
27671
28273
  continue;
27672
28274
  }
@@ -27880,12 +28482,12 @@ async function queryOsv(name, version, ecosystem) {
27880
28482
  }
27881
28483
 
27882
28484
  // ../../packages/scan/src/node/sarif.ts
27883
- var import_node_crypto2 = require("crypto");
27884
- var import_node_path8 = require("path");
28485
+ var import_node_crypto3 = require("crypto");
28486
+ var import_node_path10 = require("path");
27885
28487
  var FINGERPRINT_KEY = "threatcrush/contentHash/v1";
27886
28488
  function fingerprintOf(finding) {
27887
28489
  const content = finding.excerpt.replace(/\s+/g, " ").trim();
27888
- return (0, import_node_crypto2.createHash)("sha256").update(`${finding.ruleId}
28490
+ return (0, import_node_crypto3.createHash)("sha256").update(`${finding.ruleId}
27889
28491
  ${finding.file}
27890
28492
  ${content}`).digest("hex").slice(0, 32);
27891
28493
  }
@@ -27919,11 +28521,11 @@ function securitySeverity(severity) {
27919
28521
  }
27920
28522
  }
27921
28523
  function toArtifactUri(filePath, base, prefix = "", root = base) {
27922
- const absolute = (0, import_node_path8.isAbsolute)(filePath) ? filePath : (0, import_node_path8.resolve)(root, filePath);
27923
- const relativePath = (0, import_node_path8.relative)(base, absolute);
28524
+ const absolute = (0, import_node_path10.isAbsolute)(filePath) ? filePath : (0, import_node_path10.resolve)(root, filePath);
28525
+ const relativePath = (0, import_node_path10.relative)(base, absolute);
27924
28526
  const escapedOut = relativePath.startsWith("..") || relativePath === "";
27925
28527
  const chosen = escapedOut ? absolute : relativePath;
27926
- const posix = chosen.split(import_node_path8.sep).join("/").replace(/^\.\//, "");
28528
+ const posix = chosen.split(import_node_path10.sep).join("/").replace(/^\.\//, "");
27927
28529
  if (!prefix || escapedOut) return posix;
27928
28530
  const trimmed = prefix.replace(/^\/+|\/+$/g, "");
27929
28531
  return trimmed ? `${trimmed}/${posix}` : posix;
@@ -28013,11 +28615,11 @@ ${finding.consequence}` : `**${finding.title}**`
28013
28615
  // src/commands/scan.ts
28014
28616
  function readVersion() {
28015
28617
  for (const candidate of [
28016
- (0, import_node_path9.join)(__dirname, "..", "package.json"),
28017
- (0, import_node_path9.join)(__dirname, "..", "..", "package.json")
28618
+ (0, import_node_path11.join)(__dirname, "..", "package.json"),
28619
+ (0, import_node_path11.join)(__dirname, "..", "..", "package.json")
28018
28620
  ]) {
28019
28621
  try {
28020
- return JSON.parse((0, import_node_fs10.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
28622
+ return JSON.parse((0, import_node_fs13.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
28021
28623
  } catch {
28022
28624
  }
28023
28625
  }
@@ -28084,7 +28686,7 @@ async function scanCommand(targetPath, options = {}) {
28084
28686
  const say = machineReadable ? (line) => process.stderr.write(`${line}
28085
28687
  `) : (line) => process.stdout.write(`${line}
28086
28688
  `);
28087
- if (!(0, import_node_fs10.existsSync)(targetPath)) {
28689
+ if (!(0, import_node_fs13.existsSync)(targetPath)) {
28088
28690
  say(source_default.red(`Scan target does not exist: ${targetPath}`));
28089
28691
  process.exitCode = 2;
28090
28692
  return failedResult(targetPath, `no such path: ${targetPath}`);
@@ -28180,7 +28782,7 @@ function emitMachineReadable(format, outcome, targetPath, options, say) {
28180
28782
  // and it fails silently. `--path-prefix` covers the remaining case:
28181
28783
  // a scan run from inside the subdirectory it is scanning.
28182
28784
  base: process.cwd(),
28183
- root: (0, import_node_path9.resolve)(outcome.root)
28785
+ root: (0, import_node_path11.resolve)(outcome.root)
28184
28786
  }) : {
28185
28787
  tool: "threatcrush",
28186
28788
  version: PKG_VERSION2,
@@ -28194,8 +28796,8 @@ function emitMachineReadable(format, outcome, targetPath, options, say) {
28194
28796
  const serialized = `${JSON.stringify(payload, null, 2)}
28195
28797
  `;
28196
28798
  if (options.output) {
28197
- (0, import_node_fs10.mkdirSync)((0, import_node_path9.dirname)((0, import_node_path9.resolve)(options.output)), { recursive: true });
28198
- (0, import_node_fs10.writeFileSync)(options.output, serialized, "utf-8");
28799
+ (0, import_node_fs13.mkdirSync)((0, import_node_path11.dirname)((0, import_node_path11.resolve)(options.output)), { recursive: true });
28800
+ (0, import_node_fs13.writeFileSync)(options.output, serialized, "utf-8");
28199
28801
  say(
28200
28802
  source_default.gray(
28201
28803
  ` ${format.toUpperCase()} written to ${options.output} (${outcome.findings.length} finding(s))`
@@ -28247,30 +28849,30 @@ function printHuman(outcome) {
28247
28849
  }
28248
28850
 
28249
28851
  // src/commands/init.ts
28250
- var import_node_fs12 = require("fs");
28852
+ var import_node_fs15 = require("fs");
28251
28853
  var import_node_child_process = require("child_process");
28252
28854
 
28253
28855
  // src/core/cli-config.ts
28254
- var import_node_fs11 = require("fs");
28255
- var import_node_path10 = require("path");
28856
+ var import_node_fs14 = require("fs");
28857
+ var import_node_path12 = require("path");
28256
28858
  var import_node_os4 = require("os");
28257
- var CLI_CONFIG_DIR = (0, import_node_path10.join)((0, import_node_os4.homedir)(), ".threatcrush");
28258
- var CLI_CONFIG_PATH = (0, import_node_path10.join)(CLI_CONFIG_DIR, "config.json");
28859
+ var CLI_CONFIG_DIR = (0, import_node_path12.join)((0, import_node_os4.homedir)(), ".threatcrush");
28860
+ var CLI_CONFIG_PATH = (0, import_node_path12.join)(CLI_CONFIG_DIR, "config.json");
28259
28861
  function apiUrl() {
28260
28862
  return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
28261
28863
  }
28262
28864
  function readCliConfig() {
28263
28865
  try {
28264
- return JSON.parse((0, import_node_fs11.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
28866
+ return JSON.parse((0, import_node_fs14.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
28265
28867
  } catch {
28266
28868
  return {};
28267
28869
  }
28268
28870
  }
28269
28871
  function writeCliConfig(config) {
28270
- if (!(0, import_node_fs11.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs11.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
28271
- (0, import_node_fs11.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
28872
+ if (!(0, import_node_fs14.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs14.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
28873
+ (0, import_node_fs14.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
28272
28874
  try {
28273
- (0, import_node_fs11.chmodSync)(CLI_CONFIG_PATH, 384);
28875
+ (0, import_node_fs14.chmodSync)(CLI_CONFIG_PATH, 384);
28274
28876
  } catch {
28275
28877
  }
28276
28878
  }
@@ -28361,7 +28963,7 @@ async function cloudFetch(path, init = {}) {
28361
28963
  }
28362
28964
 
28363
28965
  // src/core/prompt.ts
28364
- var import_node_readline2 = __toESM(require("readline"));
28966
+ var import_node_readline = __toESM(require("readline"));
28365
28967
  var import_node_stream = require("stream");
28366
28968
  function stdinIsInteractive() {
28367
28969
  return Boolean(process.stdin.isTTY);
@@ -28369,7 +28971,7 @@ function stdinIsInteractive() {
28369
28971
  var piped = null;
28370
28972
  function pipedReader() {
28371
28973
  if (piped) return piped;
28372
- const rl = import_node_readline2.default.createInterface({ input: process.stdin, terminal: false });
28974
+ const rl = import_node_readline.default.createInterface({ input: process.stdin, terminal: false });
28373
28975
  const reader = { rl, lines: [], waiting: null, ended: false };
28374
28976
  rl.on("line", (line) => {
28375
28977
  const waiting = reader.waiting;
@@ -28400,29 +29002,29 @@ function askPiped(question, mask) {
28400
29002
  if (reader.lines.length > 0) return Promise.resolve(settle(reader.lines.shift()));
28401
29003
  if (reader.ended) return Promise.resolve(settle(null));
28402
29004
  reader.rl.resume();
28403
- return new Promise((resolve5) => {
28404
- reader.waiting = (line) => resolve5(settle(line));
29005
+ return new Promise((resolve6) => {
29006
+ reader.waiting = (line) => resolve6(settle(line));
28405
29007
  });
28406
29008
  }
28407
29009
  function askTerminal(question, mask) {
28408
29010
  const output = mask ? new import_node_stream.Writable({ write(_chunk, _enc, cb) {
28409
29011
  cb();
28410
29012
  } }) : process.stdout;
28411
- const rl = import_node_readline2.default.createInterface({ input: process.stdin, output, terminal: true });
28412
- return new Promise((resolve5) => {
29013
+ const rl = import_node_readline.default.createInterface({ input: process.stdin, output, terminal: true });
29014
+ return new Promise((resolve6) => {
28413
29015
  let settled = false;
28414
29016
  rl.on("close", () => {
28415
29017
  if (settled) return;
28416
29018
  settled = true;
28417
29019
  process.stdout.write("\n");
28418
- resolve5(null);
29020
+ resolve6(null);
28419
29021
  });
28420
29022
  if (mask) process.stdout.write(question);
28421
29023
  rl.question(mask ? "" : question, (answer) => {
28422
29024
  settled = true;
28423
29025
  rl.close();
28424
29026
  if (mask) process.stdout.write("\n");
28425
- resolve5(answer);
29027
+ resolve6(answer);
28426
29028
  });
28427
29029
  });
28428
29030
  }
@@ -28432,11 +29034,11 @@ function ask(question, opts = {}) {
28432
29034
  }
28433
29035
 
28434
29036
  // src/core/link-login.ts
28435
- var import_node_crypto3 = require("crypto");
29037
+ var import_node_crypto4 = require("crypto");
28436
29038
  var import_node_os5 = require("os");
28437
29039
  function createPkce() {
28438
- const verifier = (0, import_node_crypto3.randomBytes)(32).toString("base64url");
28439
- const challenge = (0, import_node_crypto3.createHash)("sha256").update(verifier).digest("base64url");
29040
+ const verifier = (0, import_node_crypto4.randomBytes)(32).toString("base64url");
29041
+ const challenge = (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
28440
29042
  return { verifier, challenge };
28441
29043
  }
28442
29044
  async function startLinkLogin(pkce, deviceName = (0, import_node_os5.hostname)()) {
@@ -28456,7 +29058,7 @@ async function startLinkLogin(pkce, deviceName = (0, import_node_os5.hostname)()
28456
29058
  }
28457
29059
  return data;
28458
29060
  }
28459
- var sleep = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
29061
+ var sleep = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
28460
29062
  async function waitForApproval(request, pkce, opts = {}) {
28461
29063
  const wait = opts.sleepMs ?? sleep;
28462
29064
  const now = opts.now ?? Date.now;
@@ -28740,7 +29342,7 @@ function binaryExists(name) {
28740
29342
  }
28741
29343
  }
28742
29344
  function findLogPath(paths) {
28743
- return paths.find((p) => (0, import_node_fs12.existsSync)(p));
29345
+ return paths.find((p) => (0, import_node_fs15.existsSync)(p));
28744
29346
  }
28745
29347
  async function promptYesNo(question, fallback2) {
28746
29348
  const hint = fallback2 ? "(Y/n)" : "(y/N)";
@@ -28884,11 +29486,11 @@ async function initCommand(opts = {}) {
28884
29486
  }
28885
29487
  } else {
28886
29488
  const spinner2 = ora({ text: "Writing configuration files...", color: "green" }).start();
28887
- (0, import_node_fs12.mkdirSync)(confDDir, { recursive: true });
28888
- (0, import_node_fs12.mkdirSync)("/var/log/threatcrush", { recursive: true });
28889
- (0, import_node_fs12.mkdirSync)("/var/lib/threatcrush", { recursive: true });
29489
+ (0, import_node_fs15.mkdirSync)(confDDir, { recursive: true });
29490
+ (0, import_node_fs15.mkdirSync)("/var/log/threatcrush", { recursive: true });
29491
+ (0, import_node_fs15.mkdirSync)("/var/lib/threatcrush", { recursive: true });
28890
29492
  const mainConfig = generateDefaultConfig(detected.map((d) => d.name));
28891
- (0, import_node_fs12.writeFileSync)(`${configDir}/threatcrushd.conf`, mainConfig);
29493
+ (0, import_node_fs15.writeFileSync)(`${configDir}/threatcrushd.conf`, mainConfig);
28892
29494
  for (const svc of detected) {
28893
29495
  const svcDef = SERVICES_TO_DETECT.find((s) => s.name === svc.name);
28894
29496
  if (!svcDef) continue;
@@ -28897,7 +29499,7 @@ async function initCommand(opts = {}) {
28897
29499
  ...svcDef.moduleConfig,
28898
29500
  log_path: svc.logPath || svcDef.logPaths[0]
28899
29501
  });
28900
- (0, import_node_fs12.writeFileSync)(`${confDDir}/${modName}.conf`, modConfig);
29502
+ (0, import_node_fs15.writeFileSync)(`${confDDir}/${modName}.conf`, modConfig);
28901
29503
  }
28902
29504
  spinner2.succeed("Configuration written successfully");
28903
29505
  console.log();
@@ -28915,8 +29517,8 @@ async function initCommand(opts = {}) {
28915
29517
  }
28916
29518
  function checkWriteAccess(dir) {
28917
29519
  try {
28918
- if (!(0, import_node_fs12.existsSync)(dir)) {
28919
- (0, import_node_fs12.mkdirSync)(dir, { recursive: true });
29520
+ if (!(0, import_node_fs15.existsSync)(dir)) {
29521
+ (0, import_node_fs15.mkdirSync)(dir, { recursive: true });
28920
29522
  }
28921
29523
  return true;
28922
29524
  } catch {
@@ -28934,8 +29536,8 @@ var BUILTIN_MODULES = [
28934
29536
  ];
28935
29537
 
28936
29538
  // src/core/module-loader.ts
28937
- var import_node_fs13 = require("fs");
28938
- var import_node_path11 = require("path");
29539
+ var import_node_fs16 = require("fs");
29540
+ var import_node_path13 = require("path");
28939
29541
  var import_toml2 = __toESM(require_toml());
28940
29542
  init_paths();
28941
29543
  function discoverModules(moduleDir, confDir) {
@@ -28943,22 +29545,22 @@ function discoverModules(moduleDir, confDir) {
28943
29545
  const configs = loadModuleConfigs(confDir || PATHS.confD);
28944
29546
  const searchPaths = [
28945
29547
  moduleDir || PATHS.moduleDir,
28946
- (0, import_node_path11.resolve)(process.cwd(), "modules")
29548
+ (0, import_node_path13.resolve)(process.cwd(), "modules")
28947
29549
  ];
28948
- const builtinDir = (0, import_node_path11.resolve)(__dirname || ".", "..", "modules");
28949
- if ((0, import_node_fs13.existsSync)(builtinDir)) {
29550
+ const builtinDir = (0, import_node_path13.resolve)(__dirname || ".", "..", "modules");
29551
+ if ((0, import_node_fs16.existsSync)(builtinDir)) {
28950
29552
  searchPaths.push(builtinDir);
28951
29553
  }
28952
29554
  for (const basePath of searchPaths) {
28953
- if (!(0, import_node_fs13.existsSync)(basePath)) continue;
28954
- const entries = (0, import_node_fs13.readdirSync)(basePath, { withFileTypes: true });
29555
+ if (!(0, import_node_fs16.existsSync)(basePath)) continue;
29556
+ const entries = (0, import_node_fs16.readdirSync)(basePath, { withFileTypes: true });
28955
29557
  for (const entry of entries) {
28956
29558
  if (!entry.isDirectory()) continue;
28957
- const modPath = (0, import_node_path11.join)(basePath, entry.name);
28958
- const manifestPath = (0, import_node_path11.join)(modPath, "mod.toml");
28959
- if (!(0, import_node_fs13.existsSync)(manifestPath)) continue;
29559
+ const modPath = (0, import_node_path13.join)(basePath, entry.name);
29560
+ const manifestPath = (0, import_node_path13.join)(modPath, "mod.toml");
29561
+ if (!(0, import_node_fs16.existsSync)(manifestPath)) continue;
28960
29562
  try {
28961
- const raw = (0, import_node_fs13.readFileSync)(manifestPath, "utf-8");
29563
+ const raw = (0, import_node_fs16.readFileSync)(manifestPath, "utf-8");
28962
29564
  const manifest = import_toml2.default.parse(raw);
28963
29565
  const config = configs.get(manifest.module.name) || { enabled: true };
28964
29566
  modules.push({
@@ -28984,21 +29586,21 @@ function discoverModules(moduleDir, confDir) {
28984
29586
  init_ipc_client();
28985
29587
 
28986
29588
  // src/daemon/pidfile.ts
28987
- var import_node_fs14 = require("fs");
29589
+ var import_node_fs17 = require("fs");
28988
29590
  init_paths();
28989
29591
  function writePidFile() {
28990
29592
  ensureRuntimeDirs();
28991
- (0, import_node_fs14.writeFileSync)(PATHS.pidFile, String(process.pid), "utf-8");
29593
+ (0, import_node_fs17.writeFileSync)(PATHS.pidFile, String(process.pid), "utf-8");
28992
29594
  }
28993
29595
  function readPidFile() {
28994
- if (!(0, import_node_fs14.existsSync)(PATHS.pidFile)) return null;
28995
- const raw = (0, import_node_fs14.readFileSync)(PATHS.pidFile, "utf-8").trim();
29596
+ if (!(0, import_node_fs17.existsSync)(PATHS.pidFile)) return null;
29597
+ const raw = (0, import_node_fs17.readFileSync)(PATHS.pidFile, "utf-8").trim();
28996
29598
  const pid = parseInt(raw, 10);
28997
29599
  return Number.isFinite(pid) ? pid : null;
28998
29600
  }
28999
29601
  function removePidFile() {
29000
29602
  try {
29001
- if ((0, import_node_fs14.existsSync)(PATHS.pidFile)) (0, import_node_fs14.unlinkSync)(PATHS.pidFile);
29603
+ if ((0, import_node_fs17.existsSync)(PATHS.pidFile)) (0, import_node_fs17.unlinkSync)(PATHS.pidFile);
29002
29604
  } catch {
29003
29605
  }
29004
29606
  }
@@ -29010,7 +29612,7 @@ function procStatState(stat) {
29010
29612
  function isZombie(pid) {
29011
29613
  let stat;
29012
29614
  try {
29013
- stat = (0, import_node_fs14.readFileSync)(`/proc/${pid}/stat`, "utf-8");
29615
+ stat = (0, import_node_fs17.readFileSync)(`/proc/${pid}/stat`, "utf-8");
29014
29616
  } catch {
29015
29617
  return false;
29016
29618
  }
@@ -29136,24 +29738,24 @@ function formatUptime2(seconds) {
29136
29738
 
29137
29739
  // src/commands/modules.ts
29138
29740
  var import_node_child_process2 = require("child_process");
29139
- var import_node_fs16 = require("fs");
29140
- var import_node_path13 = require("path");
29741
+ var import_node_fs19 = require("fs");
29742
+ var import_node_path15 = require("path");
29141
29743
  var import_toml3 = __toESM(require_toml());
29142
29744
  init_paths();
29143
29745
 
29144
29746
  // src/daemon/module-trust.ts
29145
- var import_node_crypto4 = require("crypto");
29146
- var import_node_fs15 = require("fs");
29147
- var import_node_path12 = require("path");
29747
+ var import_node_crypto5 = require("crypto");
29748
+ var import_node_fs18 = require("fs");
29749
+ var import_node_path14 = require("path");
29148
29750
  init_paths();
29149
- var TRUST_FILE = (0, import_node_path12.join)(PATHS.configDir, "trusted-modules.json");
29150
- var PUBLISHER_KEYS_FILE = (0, import_node_path12.join)(PATHS.configDir, "publisher-keys.json");
29751
+ var TRUST_FILE = (0, import_node_path14.join)(PATHS.configDir, "trusted-modules.json");
29752
+ var PUBLISHER_KEYS_FILE = (0, import_node_path14.join)(PATHS.configDir, "publisher-keys.json");
29151
29753
  var DIGEST_EXCLUDED_DIRS = /* @__PURE__ */ new Set([".git"]);
29152
29754
  function collectFiles(root, dir = root, out = []) {
29153
- for (const entry of (0, import_node_fs15.readdirSync)(dir, { withFileTypes: true }).sort(
29755
+ for (const entry of (0, import_node_fs18.readdirSync)(dir, { withFileTypes: true }).sort(
29154
29756
  (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
29155
29757
  )) {
29156
- const full = (0, import_node_path12.join)(dir, entry.name);
29758
+ const full = (0, import_node_path14.join)(dir, entry.name);
29157
29759
  if (entry.isSymbolicLink()) {
29158
29760
  out.push({ path: full, isSymlink: true });
29159
29761
  } else if (entry.isDirectory()) {
@@ -29166,26 +29768,26 @@ function collectFiles(root, dir = root, out = []) {
29166
29768
  return out;
29167
29769
  }
29168
29770
  function computeModuleDigest(modulePath) {
29169
- const hash = (0, import_node_crypto4.createHash)("sha256");
29771
+ const hash = (0, import_node_crypto5.createHash)("sha256");
29170
29772
  for (const entry of collectFiles(modulePath)) {
29171
- const relPath = (0, import_node_path12.relative)(modulePath, entry.path).split(import_node_path12.sep).join("/");
29773
+ const relPath = (0, import_node_path14.relative)(modulePath, entry.path).split(import_node_path14.sep).join("/");
29172
29774
  hash.update(relPath);
29173
29775
  hash.update("\0");
29174
29776
  if (entry.isSymlink) {
29175
29777
  hash.update("symlink:");
29176
- hash.update((0, import_node_fs15.readlinkSync)(entry.path));
29778
+ hash.update((0, import_node_fs18.readlinkSync)(entry.path));
29177
29779
  } else {
29178
29780
  hash.update("file:");
29179
- hash.update((0, import_node_fs15.readFileSync)(entry.path));
29781
+ hash.update((0, import_node_fs18.readFileSync)(entry.path));
29180
29782
  }
29181
29783
  hash.update("\0");
29182
29784
  }
29183
29785
  return hash.digest("hex");
29184
29786
  }
29185
29787
  function readTrustFile() {
29186
- if (!(0, import_node_fs15.existsSync)(TRUST_FILE)) return { version: 1, modules: {} };
29788
+ if (!(0, import_node_fs18.existsSync)(TRUST_FILE)) return { version: 1, modules: {} };
29187
29789
  try {
29188
- const parsed = JSON.parse((0, import_node_fs15.readFileSync)(TRUST_FILE, "utf-8"));
29790
+ const parsed = JSON.parse((0, import_node_fs18.readFileSync)(TRUST_FILE, "utf-8"));
29189
29791
  if (parsed.version !== 1 || typeof parsed.modules !== "object" || !parsed.modules) {
29190
29792
  return { version: 1, modules: {} };
29191
29793
  }
@@ -29195,9 +29797,9 @@ function readTrustFile() {
29195
29797
  }
29196
29798
  }
29197
29799
  function writeTrustFile(file) {
29198
- (0, import_node_fs15.writeFileSync)(TRUST_FILE, JSON.stringify(file, null, 2) + "\n", { mode: 384 });
29800
+ (0, import_node_fs18.writeFileSync)(TRUST_FILE, JSON.stringify(file, null, 2) + "\n", { mode: 384 });
29199
29801
  try {
29200
- (0, import_node_fs15.chmodSync)(TRUST_FILE, 384);
29802
+ (0, import_node_fs18.chmodSync)(TRUST_FILE, 384);
29201
29803
  } catch {
29202
29804
  }
29203
29805
  }
@@ -29223,9 +29825,9 @@ function listTrustedModules() {
29223
29825
  return readTrustFile().modules;
29224
29826
  }
29225
29827
  function readPublisherKeys() {
29226
- if (!(0, import_node_fs15.existsSync)(PUBLISHER_KEYS_FILE)) return {};
29828
+ if (!(0, import_node_fs18.existsSync)(PUBLISHER_KEYS_FILE)) return {};
29227
29829
  try {
29228
- const parsed = JSON.parse((0, import_node_fs15.readFileSync)(PUBLISHER_KEYS_FILE, "utf-8"));
29830
+ const parsed = JSON.parse((0, import_node_fs18.readFileSync)(PUBLISHER_KEYS_FILE, "utf-8"));
29229
29831
  return parsed && typeof parsed === "object" ? parsed : {};
29230
29832
  } catch {
29231
29833
  return {};
@@ -29234,16 +29836,16 @@ function readPublisherKeys() {
29234
29836
  function verifyModuleSignature(modulePath, digest) {
29235
29837
  const keys = readPublisherKeys();
29236
29838
  const pinnedKeyIds = Object.keys(keys);
29237
- const sigPath = (0, import_node_path12.join)(modulePath, "mod.sig");
29839
+ const sigPath = (0, import_node_path14.join)(modulePath, "mod.sig");
29238
29840
  if (pinnedKeyIds.length === 0) {
29239
29841
  return { ok: true };
29240
29842
  }
29241
- if (!(0, import_node_fs15.existsSync)(sigPath)) {
29843
+ if (!(0, import_node_fs18.existsSync)(sigPath)) {
29242
29844
  return { ok: false, reason: "publisher keys are pinned but the module ships no mod.sig" };
29243
29845
  }
29244
29846
  let parsed;
29245
29847
  try {
29246
- parsed = JSON.parse((0, import_node_fs15.readFileSync)(sigPath, "utf-8"));
29848
+ parsed = JSON.parse((0, import_node_fs18.readFileSync)(sigPath, "utf-8"));
29247
29849
  } catch {
29248
29850
  return { ok: false, reason: "mod.sig is not valid JSON" };
29249
29851
  }
@@ -29255,7 +29857,7 @@ function verifyModuleSignature(modulePath, digest) {
29255
29857
  return { ok: false, reason: `mod.sig references unpinned key "${parsed.keyId}"` };
29256
29858
  }
29257
29859
  try {
29258
- const valid = (0, import_node_crypto4.verify)(
29860
+ const valid = (0, import_node_crypto5.verify)(
29259
29861
  null,
29260
29862
  Buffer.from(digest, "hex"),
29261
29863
  publicKey,
@@ -29304,7 +29906,7 @@ function safeModuleDirName(name, label = "module name") {
29304
29906
  return name;
29305
29907
  }
29306
29908
  function moduleDestination(dir, name, label) {
29307
- return (0, import_node_path13.join)(dir, safeModuleDirName(name, label));
29909
+ return (0, import_node_path15.join)(dir, safeModuleDirName(name, label));
29308
29910
  }
29309
29911
  function assertSafeTarballEntries(tarPath) {
29310
29912
  const listing = (0, import_node_child_process2.execFileSync)("tar", ["-tzf", tarPath], { encoding: "utf-8" });
@@ -29317,12 +29919,12 @@ function assertSafeTarballEntries(tarPath) {
29317
29919
  }
29318
29920
  }
29319
29921
  function validateManifest(modPath) {
29320
- const manifestPath = (0, import_node_path13.join)(modPath, "mod.toml");
29321
- if (!(0, import_node_fs16.existsSync)(manifestPath)) {
29922
+ const manifestPath = (0, import_node_path15.join)(modPath, "mod.toml");
29923
+ if (!(0, import_node_fs19.existsSync)(manifestPath)) {
29322
29924
  return { ok: false, error: `mod.toml not found at ${manifestPath}` };
29323
29925
  }
29324
29926
  try {
29325
- const raw = (0, import_node_fs16.readFileSync)(manifestPath, "utf-8");
29927
+ const raw = (0, import_node_fs19.readFileSync)(manifestPath, "utf-8");
29326
29928
  const parsed = import_toml3.default.parse(raw);
29327
29929
  const name = parsed.module?.name;
29328
29930
  const version = parsed.module?.version;
@@ -29384,8 +29986,8 @@ async function modulesInstallCommand(source) {
29384
29986
  console.log();
29385
29987
  const dir = modulesDir();
29386
29988
  if (source.startsWith("./") || source.startsWith("/") || source.startsWith("~")) {
29387
- const absPath = (0, import_node_path13.resolve)(source.startsWith("~") ? source.replace("~", process.env.HOME || "") : source);
29388
- if (!(0, import_node_fs16.existsSync)(absPath)) {
29989
+ const absPath = (0, import_node_path15.resolve)(source.startsWith("~") ? source.replace("~", process.env.HOME || "") : source);
29990
+ if (!(0, import_node_fs19.existsSync)(absPath)) {
29389
29991
  console.log(source_default.red(` \u2717 Path not found: ${absPath}
29390
29992
  `));
29391
29993
  return;
@@ -29404,7 +30006,7 @@ async function modulesInstallCommand(source) {
29404
30006
  `));
29405
30007
  return;
29406
30008
  }
29407
- if ((0, import_node_fs16.existsSync)(dest2)) {
30009
+ if ((0, import_node_fs19.existsSync)(dest2)) {
29408
30010
  console.log(source_default.yellow(` ! ${check.name} is already installed at ${dest2}`));
29409
30011
  console.log(source_default.dim(` Run ${source_default.white(`threatcrush modules remove ${check.name}`)} first.
29410
30012
  `));
@@ -29412,7 +30014,7 @@ async function modulesInstallCommand(source) {
29412
30014
  }
29413
30015
  const spinner2 = ora({ text: `Copying module files...`, color: "green" }).start();
29414
30016
  try {
29415
- (0, import_node_fs16.cpSync)(absPath, dest2, { recursive: true, dereference: true });
30017
+ (0, import_node_fs19.cpSync)(absPath, dest2, { recursive: true, dereference: true });
29416
30018
  spinner2.succeed(`Installed ${source_default.white(check.name)} v${check.version} \u2192 ${dest2}`);
29417
30019
  } catch (err) {
29418
30020
  spinner2.fail(`Copy failed: ${err.message}`);
@@ -29428,14 +30030,14 @@ async function modulesInstallCommand(source) {
29428
30030
  let name;
29429
30031
  let dest2;
29430
30032
  try {
29431
- name = safeModuleDirName((0, import_node_path13.basename)(gitUrl.replace(/\.git$/, "")), "repository name");
30033
+ name = safeModuleDirName((0, import_node_path15.basename)(gitUrl.replace(/\.git$/, "")), "repository name");
29432
30034
  dest2 = moduleDestination(dir, name);
29433
30035
  } catch (err) {
29434
30036
  console.log(source_default.red(` x ${err.message}
29435
30037
  `));
29436
30038
  return;
29437
30039
  }
29438
- if ((0, import_node_fs16.existsSync)(dest2)) {
30040
+ if ((0, import_node_fs19.existsSync)(dest2)) {
29439
30041
  console.log(source_default.yellow(` ! ${name} is already installed at ${dest2}`));
29440
30042
  console.log(source_default.dim(` Run ${source_default.white(`threatcrush modules remove ${name}`)} first.
29441
30043
  `));
@@ -29452,7 +30054,7 @@ async function modulesInstallCommand(source) {
29452
30054
  if (!check.ok) {
29453
30055
  spinner2.fail(check.error);
29454
30056
  try {
29455
- (0, import_node_fs16.rmSync)(dest2, { recursive: true, force: true });
30057
+ (0, import_node_fs19.rmSync)(dest2, { recursive: true, force: true });
29456
30058
  } catch {
29457
30059
  }
29458
30060
  return;
@@ -29499,7 +30101,7 @@ async function modulesInstallCommand(source) {
29499
30101
  `));
29500
30102
  return;
29501
30103
  }
29502
- if ((0, import_node_fs16.existsSync)(dest)) {
30104
+ if ((0, import_node_fs19.existsSync)(dest)) {
29503
30105
  console.log(source_default.yellow(` ! ${mod.slug} is already installed at ${dest}
29504
30106
  `));
29505
30107
  return;
@@ -29525,7 +30127,7 @@ async function modulesInstallCommand(source) {
29525
30127
  if (!check.ok) {
29526
30128
  cloneSpinner.fail(check.error);
29527
30129
  try {
29528
- (0, import_node_fs16.rmSync)(dest, { recursive: true, force: true });
30130
+ (0, import_node_fs19.rmSync)(dest, { recursive: true, force: true });
29529
30131
  } catch {
29530
30132
  }
29531
30133
  return;
@@ -29539,11 +30141,11 @@ async function modulesInstallCommand(source) {
29539
30141
  dlSpinner.fail(`HTTP ${res.status}`);
29540
30142
  return;
29541
30143
  }
29542
- const tar = (0, import_node_path13.join)(dir, `${mod.slug}.tar.gz`);
29543
- (0, import_node_fs16.writeFileSync)(tar, Buffer.from(await res.arrayBuffer()));
30144
+ const tar = (0, import_node_path15.join)(dir, `${mod.slug}.tar.gz`);
30145
+ (0, import_node_fs19.writeFileSync)(tar, Buffer.from(await res.arrayBuffer()));
29544
30146
  assertSafeTarballEntries(tar);
29545
30147
  (0, import_node_child_process2.execFileSync)("tar", ["-xzf", tar, "-C", dir], { stdio: "pipe" });
29546
- (0, import_node_fs16.rmSync)(tar, { force: true });
30148
+ (0, import_node_fs19.rmSync)(tar, { force: true });
29547
30149
  const check = validateManifest(dest);
29548
30150
  if (!check.ok) {
29549
30151
  dlSpinner.fail(check.error);
@@ -29575,7 +30177,7 @@ async function modulesRemoveCommand(name) {
29575
30177
  `));
29576
30178
  return;
29577
30179
  }
29578
- if (!(0, import_node_fs16.existsSync)(target)) {
30180
+ if (!(0, import_node_fs19.existsSync)(target)) {
29579
30181
  console.log(source_default.yellow(` ! No module named "${name}" in ${dir}
29580
30182
  `));
29581
30183
  return;
@@ -29585,7 +30187,7 @@ async function modulesRemoveCommand(name) {
29585
30187
  console.log(source_default.yellow(` ! Directory name "${name}" does not match manifest name "${check.name}"`));
29586
30188
  }
29587
30189
  try {
29588
- (0, import_node_fs16.rmSync)(target, { recursive: true, force: true });
30190
+ (0, import_node_fs19.rmSync)(target, { recursive: true, force: true });
29589
30191
  untrustModule(name);
29590
30192
  console.log(source_default.green(` \u2713 Removed ${name} from ${dir}
29591
30193
  `));
@@ -29610,7 +30212,7 @@ async function modulesTrustCommand(name) {
29610
30212
  `));
29611
30213
  return;
29612
30214
  }
29613
- if (!(0, import_node_fs16.existsSync)(target)) {
30215
+ if (!(0, import_node_fs19.existsSync)(target)) {
29614
30216
  console.log(source_default.yellow(` ! No module named "${name}" in ${dir}
29615
30217
  `));
29616
30218
  return;
@@ -30045,7 +30647,7 @@ async function pentestCommand(targetUrl) {
30045
30647
  }
30046
30648
 
30047
30649
  // src/commands/ai-scan.ts
30048
- var import_node_fs17 = require("fs");
30650
+ var import_node_fs20 = require("fs");
30049
30651
 
30050
30652
  // src/aiscan/probes.ts
30051
30653
  function makeCanary() {
@@ -30322,7 +30924,7 @@ async function aiScanMoshCommand(file, args) {
30322
30924
  console.log();
30323
30925
  let source;
30324
30926
  try {
30325
- source = (0, import_node_fs17.readFileSync)(file, "utf-8");
30927
+ source = (0, import_node_fs20.readFileSync)(file, "utf-8");
30326
30928
  } catch (err) {
30327
30929
  logger.error(`Cannot read ${file}: ${err.message}`);
30328
30930
  process.exitCode = 1;
@@ -30343,21 +30945,21 @@ async function aiScanMoshCommand(file, args) {
30343
30945
 
30344
30946
  // src/commands/orgs.ts
30345
30947
  var import_node_os6 = require("os");
30346
- var import_node_fs18 = require("fs");
30347
- var import_node_path14 = require("path");
30948
+ var import_node_fs21 = require("fs");
30949
+ var import_node_path16 = require("path");
30348
30950
  var API_URL3 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
30349
- var CONFIG_PATH = (0, import_node_path14.join)((0, import_node_os6.homedir)(), ".threatcrush", "config.json");
30951
+ var CONFIG_PATH = (0, import_node_path16.join)((0, import_node_os6.homedir)(), ".threatcrush", "config.json");
30350
30952
  function readConfig() {
30351
30953
  try {
30352
- return JSON.parse((0, import_node_fs18.readFileSync)(CONFIG_PATH, "utf-8"));
30954
+ return JSON.parse((0, import_node_fs21.readFileSync)(CONFIG_PATH, "utf-8"));
30353
30955
  } catch {
30354
30956
  return {};
30355
30957
  }
30356
30958
  }
30357
30959
  function writeConfig(config) {
30358
- const dir = (0, import_node_path14.join)((0, import_node_os6.homedir)(), ".threatcrush");
30359
- if (!(0, import_node_fs18.existsSync)(dir)) (0, import_node_fs18.mkdirSync)(dir, { recursive: true });
30360
- (0, import_node_fs18.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
30960
+ const dir = (0, import_node_path16.join)((0, import_node_os6.homedir)(), ".threatcrush");
30961
+ if (!(0, import_node_fs21.existsSync)(dir)) (0, import_node_fs21.mkdirSync)(dir, { recursive: true });
30962
+ (0, import_node_fs21.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
30361
30963
  }
30362
30964
  function getAuthHeaders() {
30363
30965
  const config = readConfig();
@@ -30492,7 +31094,7 @@ async function useOrganization(slug) {
30492
31094
  }
30493
31095
 
30494
31096
  // src/commands/servers.ts
30495
- var import_node_readline3 = __toESM(require("readline"));
31097
+ var import_node_readline2 = __toESM(require("readline"));
30496
31098
  var import_node_os7 = require("os");
30497
31099
  async function serversCommand(options) {
30498
31100
  const { action, name, org } = options;
@@ -30557,10 +31159,10 @@ async function fetchOrgs() {
30557
31159
  return data.organizations || [];
30558
31160
  }
30559
31161
  function askChoice(question) {
30560
- const rl = import_node_readline3.default.createInterface({ input: process.stdin, output: process.stdout });
30561
- return new Promise((resolve5) => rl.question(question, (answer) => {
31162
+ const rl = import_node_readline2.default.createInterface({ input: process.stdin, output: process.stdout });
31163
+ return new Promise((resolve6) => rl.question(question, (answer) => {
30562
31164
  rl.close();
30563
- resolve5(answer.trim());
31165
+ resolve6(answer.trim());
30564
31166
  }));
30565
31167
  }
30566
31168
  async function chooseOrg(orgs, flag, ask2) {
@@ -30702,14 +31304,14 @@ function timeAgo(dateStr) {
30702
31304
 
30703
31305
  // src/commands/connect.ts
30704
31306
  var import_node_os8 = require("os");
30705
- var import_node_fs19 = require("fs");
30706
- var import_node_path15 = require("path");
31307
+ var import_node_fs22 = require("fs");
31308
+ var import_node_path17 = require("path");
30707
31309
  var import_node_child_process3 = require("child_process");
30708
31310
  var API_URL4 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
30709
- var CONFIG_PATH2 = (0, import_node_path15.join)((0, import_node_os8.homedir)(), ".threatcrush", "config.json");
31311
+ var CONFIG_PATH2 = (0, import_node_path17.join)((0, import_node_os8.homedir)(), ".threatcrush", "config.json");
30710
31312
  function readConfig2() {
30711
31313
  try {
30712
- return JSON.parse((0, import_node_fs19.readFileSync)(CONFIG_PATH2, "utf-8"));
31314
+ return JSON.parse((0, import_node_fs22.readFileSync)(CONFIG_PATH2, "utf-8"));
30713
31315
  } catch {
30714
31316
  return {};
30715
31317
  }
@@ -30864,21 +31466,21 @@ async function sshConnect(options) {
30864
31466
 
30865
31467
  // src/commands/daemon.ts
30866
31468
  var import_node_child_process11 = require("child_process");
30867
- var import_node_fs30 = require("fs");
30868
- var import_node_path21 = require("path");
30869
- var import_node_fs31 = require("fs");
31469
+ var import_node_fs34 = require("fs");
31470
+ var import_node_path24 = require("path");
31471
+ var import_node_fs35 = require("fs");
30870
31472
 
30871
31473
  // src/daemon/index.ts
30872
- var import_node_fs29 = require("fs");
31474
+ var import_node_fs33 = require("fs");
30873
31475
  var import_node_child_process10 = require("child_process");
30874
31476
  var import_node_os9 = require("os");
30875
- var import_node_path20 = require("path");
31477
+ var import_node_path23 = require("path");
30876
31478
  var import_node_util = require("util");
30877
31479
  init_paths();
30878
31480
 
30879
31481
  // src/daemon/ipc-server.ts
30880
31482
  var import_node_net2 = require("net");
30881
- var import_node_fs20 = require("fs");
31483
+ var import_node_fs23 = require("fs");
30882
31484
  init_paths();
30883
31485
  init_control_token();
30884
31486
 
@@ -30901,10 +31503,11 @@ bus.setMaxListeners(50);
30901
31503
  // src/daemon/ipc-server.ts
30902
31504
  init_backoff();
30903
31505
  var IpcServer = class {
30904
- constructor(version, moduleHost, remediation) {
31506
+ constructor(version, moduleHost, remediation, watchdog) {
30905
31507
  this.version = version;
30906
31508
  this.moduleHost = moduleHost;
30907
31509
  this.remediation = remediation;
31510
+ this.watchdog = watchdog;
30908
31511
  bus.on("event", (event) => {
30909
31512
  this.counters.events++;
30910
31513
  if (event.severity === "medium" || event.severity === "high" || event.severity === "critical") {
@@ -30922,6 +31525,7 @@ var IpcServer = class {
30922
31525
  version;
30923
31526
  moduleHost;
30924
31527
  remediation;
31528
+ watchdog;
30925
31529
  server = null;
30926
31530
  clients = /* @__PURE__ */ new Map();
30927
31531
  nextClientId = 1;
@@ -30930,13 +31534,13 @@ var IpcServer = class {
30930
31534
  controlToken = "";
30931
31535
  async start() {
30932
31536
  this.controlToken = issueControlToken();
30933
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) {
31537
+ if ((0, import_node_fs23.existsSync)(PATHS.socket)) {
30934
31538
  try {
30935
- (0, import_node_fs20.unlinkSync)(PATHS.socket);
31539
+ (0, import_node_fs23.unlinkSync)(PATHS.socket);
30936
31540
  } catch {
30937
31541
  }
30938
31542
  }
30939
- return new Promise((resolve5, reject) => {
31543
+ return new Promise((resolve6, reject) => {
30940
31544
  this.server = (0, import_node_net2.createServer)((sock) => this.handleClient(sock));
30941
31545
  this.server.on("error", reject);
30942
31546
  this.server.listen(PATHS.socket, () => {
@@ -30953,7 +31557,7 @@ var IpcServer = class {
30953
31557
  } catch {
30954
31558
  }
30955
31559
  }
30956
- resolve5();
31560
+ resolve6();
30957
31561
  });
30958
31562
  });
30959
31563
  }
@@ -30965,20 +31569,20 @@ var IpcServer = class {
30965
31569
  }
30966
31570
  }
30967
31571
  this.clients.clear();
30968
- return new Promise((resolve5) => {
31572
+ return new Promise((resolve6) => {
30969
31573
  if (!this.server) {
30970
31574
  try {
30971
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) (0, import_node_fs20.unlinkSync)(PATHS.socket);
31575
+ if ((0, import_node_fs23.existsSync)(PATHS.socket)) (0, import_node_fs23.unlinkSync)(PATHS.socket);
30972
31576
  } catch {
30973
31577
  }
30974
- return resolve5();
31578
+ return resolve6();
30975
31579
  }
30976
31580
  this.server.close(() => {
30977
31581
  try {
30978
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) (0, import_node_fs20.unlinkSync)(PATHS.socket);
31582
+ if ((0, import_node_fs23.existsSync)(PATHS.socket)) (0, import_node_fs23.unlinkSync)(PATHS.socket);
30979
31583
  } catch {
30980
31584
  }
30981
- resolve5();
31585
+ resolve6();
30982
31586
  });
30983
31587
  });
30984
31588
  }
@@ -31046,7 +31650,8 @@ var IpcServer = class {
31046
31650
  },
31047
31651
  modules: this.moduleHost.summary(),
31048
31652
  counters: { ...this.counters },
31049
- stateDb: isStateDbAvailable()
31653
+ stateDb: isStateDbAvailable(),
31654
+ ...this.watchdog ? { watchdog: this.watchdog() } : {}
31050
31655
  };
31051
31656
  return this.send(client, { id: req.id, ok: true, result: status });
31052
31657
  }
@@ -31156,15 +31761,14 @@ var IpcServer = class {
31156
31761
  };
31157
31762
 
31158
31763
  // src/daemon/module-host.ts
31159
- var import_node_fs24 = require("fs");
31160
- var import_node_path16 = require("path");
31764
+ var import_node_fs27 = require("fs");
31765
+ var import_node_path18 = require("path");
31161
31766
  var import_node_url = require("url");
31162
31767
  var import_toml4 = __toESM(require_toml());
31163
31768
  init_paths();
31164
31769
 
31165
31770
  // src/daemon/watchers/log-watcher.ts
31166
- var import_node_fs21 = require("fs");
31167
- var import_node_readline4 = require("readline");
31771
+ var import_node_fs24 = require("fs");
31168
31772
  var DEFAULT_SOURCES = [
31169
31773
  { path: "/var/log/auth.log", module: "ssh-guard", category: "auth" },
31170
31774
  { path: "/var/log/secure", module: "ssh-guard", category: "auth" },
@@ -31179,14 +31783,14 @@ var LogWatcher = class {
31179
31783
  bus;
31180
31784
  sources;
31181
31785
  timers = /* @__PURE__ */ new Map();
31182
- positions = /* @__PURE__ */ new Map();
31786
+ tails = /* @__PURE__ */ new Map();
31183
31787
  active = /* @__PURE__ */ new Set();
31184
31788
  start() {
31185
31789
  const started = [];
31186
31790
  for (const src of this.sources) {
31187
- if (!(0, import_node_fs21.existsSync)(src.path)) continue;
31791
+ if (!(0, import_node_fs24.existsSync)(src.path)) continue;
31188
31792
  try {
31189
- (0, import_node_fs21.accessSync)(src.path, import_node_fs21.constants.R_OK);
31793
+ (0, import_node_fs24.accessSync)(src.path, import_node_fs24.constants.R_OK);
31190
31794
  } catch {
31191
31795
  continue;
31192
31796
  }
@@ -31198,7 +31802,7 @@ var LogWatcher = class {
31198
31802
  stop() {
31199
31803
  for (const t of this.timers.values()) clearInterval(t);
31200
31804
  this.timers.clear();
31201
- this.positions.clear();
31805
+ this.tails.clear();
31202
31806
  this.active.clear();
31203
31807
  }
31204
31808
  activeModules() {
@@ -31213,38 +31817,22 @@ var LogWatcher = class {
31213
31817
  return this.sources.filter((s) => s.category === "auth" && this.timers.has(s.path)).map((s) => s.path);
31214
31818
  }
31215
31819
  tail(src) {
31216
- try {
31217
- this.positions.set(src.path, (0, import_node_fs21.statSync)(src.path).size);
31218
- } catch {
31219
- this.positions.set(src.path, 0);
31220
- }
31820
+ const tail = new LogTail(src.path);
31821
+ this.tails.set(src.path, tail);
31221
31822
  const timer = setInterval(() => this.poll(src), 1e3);
31222
31823
  this.timers.set(src.path, timer);
31223
31824
  this.active.add(src.module);
31224
31825
  }
31826
+ /** Each new line exactly once; see LogTail for why this is synchronous. */
31225
31827
  poll(src) {
31226
- let stat;
31227
- try {
31228
- stat = (0, import_node_fs21.statSync)(src.path);
31229
- } catch {
31230
- return;
31231
- }
31232
- const prev = this.positions.get(src.path) ?? 0;
31233
- if (stat.size < prev) {
31234
- this.positions.set(src.path, 0);
31235
- return;
31236
- }
31237
- if (stat.size === prev) return;
31238
- const stream = (0, import_node_fs21.createReadStream)(src.path, { start: prev, encoding: "utf-8" });
31239
- stream.on("error", () => this.positions.set(src.path, stat.size));
31240
- const rl = (0, import_node_readline4.createInterface)({ input: stream });
31241
- rl.on("error", () => {
31242
- });
31243
- rl.on("line", (line) => {
31244
- if (!line.trim()) return;
31245
- this.process(line, src);
31828
+ const tail = this.tails.get(src.path);
31829
+ if (!tail) return 0;
31830
+ return tail.poll((line) => {
31831
+ try {
31832
+ this.process(line, src);
31833
+ } catch {
31834
+ }
31246
31835
  });
31247
- rl.on("close", () => this.positions.set(src.path, stat.size));
31248
31836
  }
31249
31837
  process(line, src) {
31250
31838
  const parsed = autoDetectParser(line);
@@ -31271,6 +31859,9 @@ var LogWatcher = class {
31271
31859
  const reqPath = (entry.fields.path || "").split("?")[0];
31272
31860
  if (reqPath) details.path = reqPath;
31273
31861
  if (entry.fields.user_agent) details.ua = entry.fields.user_agent;
31862
+ if (Number.isFinite(status)) details.status = status;
31863
+ if (entry.fields.method) details.method = entry.fields.method;
31864
+ if (entry.fields.path) details.url = entry.fields.path.slice(0, 2048);
31274
31865
  if (crs.score > 0) {
31275
31866
  Object.assign(details, {
31276
31867
  attack_type: crs.attackType,
@@ -31496,7 +32087,7 @@ function realtimeToDate(rt) {
31496
32087
 
31497
32088
  // src/modules/network-monitor/index.ts
31498
32089
  var import_node_child_process5 = require("child_process");
31499
- var import_node_fs22 = require("fs");
32090
+ var import_node_fs25 = require("fs");
31500
32091
  var NetworkMonitor = class {
31501
32092
  constructor(bus2) {
31502
32093
  this.bus = bus2;
@@ -31560,7 +32151,7 @@ var NetworkMonitor = class {
31560
32151
  hasConntrackOrSs() {
31561
32152
  const ss = (0, import_node_child_process5.spawnSync)("ss", ["--version"], { stdio: "pipe" });
31562
32153
  if (ss.status === 0) return true;
31563
- return (0, import_node_fs22.existsSync)("/proc/net/tcp");
32154
+ return (0, import_node_fs25.existsSync)("/proc/net/tcp");
31564
32155
  }
31565
32156
  /**
31566
32157
  * The TCP ports this host actually listens on.
@@ -31747,9 +32338,9 @@ var NetworkMonitor = class {
31747
32338
  };
31748
32339
 
31749
32340
  // src/modules/dns-monitor/index.ts
31750
- var import_node_fs23 = require("fs");
32341
+ var import_node_fs26 = require("fs");
31751
32342
  var import_node_child_process6 = require("child_process");
31752
- var import_node_readline5 = require("readline");
32343
+ var import_node_readline3 = require("readline");
31753
32344
  var DNS_LOG_SOURCES = [
31754
32345
  "/var/log/syslog",
31755
32346
  // systemd-resolved logs here
@@ -31790,7 +32381,7 @@ var DnsMonitor = class {
31790
32381
  bus;
31791
32382
  active = false;
31792
32383
  timers = /* @__PURE__ */ new Map();
31793
- positions = /* @__PURE__ */ new Map();
32384
+ tails = /* @__PURE__ */ new Map();
31794
32385
  // Tracking windows
31795
32386
  txtQueryCounts = /* @__PURE__ */ new Map();
31796
32387
  domainBuffer = [];
@@ -31829,9 +32420,9 @@ var DnsMonitor = class {
31829
32420
  }
31830
32421
  start() {
31831
32422
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
31832
- if (!(0, import_node_fs23.existsSync)(p)) return false;
32423
+ if (!(0, import_node_fs26.existsSync)(p)) return false;
31833
32424
  try {
31834
- (0, import_node_fs23.accessSync)(p, import_node_fs23.constants.R_OK);
32425
+ (0, import_node_fs26.accessSync)(p, import_node_fs26.constants.R_OK);
31835
32426
  return true;
31836
32427
  } catch {
31837
32428
  return false;
@@ -31894,7 +32485,7 @@ var DnsMonitor = class {
31894
32485
  stdio: ["ignore", "pipe", "ignore"]
31895
32486
  });
31896
32487
  if (!child.stdout) return;
31897
- const rl = (0, import_node_readline5.createInterface)({ input: child.stdout });
32488
+ const rl = (0, import_node_readline3.createInterface)({ input: child.stdout });
31898
32489
  rl.on("line", (line) => this.parseDnsLine(line));
31899
32490
  child.on("error", () => {
31900
32491
  });
@@ -31906,33 +32497,11 @@ var DnsMonitor = class {
31906
32497
  return this.active;
31907
32498
  }
31908
32499
  tailLog(path) {
31909
- try {
31910
- this.positions.set(path, (0, import_node_fs23.statSync)(path).size);
31911
- } catch {
31912
- this.positions.set(path, 0);
31913
- }
31914
- const timer = setInterval(() => this.pollLog(path), 2e3);
32500
+ const tail = new LogTail(path);
32501
+ this.tails.set(path, tail);
32502
+ const timer = setInterval(() => tail.poll((line) => this.parseDnsLine(line)), 2e3);
31915
32503
  this.timers.set(path, timer);
31916
32504
  }
31917
- pollLog(path) {
31918
- let stat;
31919
- try {
31920
- stat = (0, import_node_fs23.statSync)(path);
31921
- } catch {
31922
- return;
31923
- }
31924
- const prev = this.positions.get(path) ?? 0;
31925
- if (stat.size < prev) {
31926
- this.positions.set(path, 0);
31927
- return;
31928
- }
31929
- if (stat.size === prev) return;
31930
- const stream = (0, import_node_fs23.createReadStream)(path, { start: prev, encoding: "utf-8" });
31931
- stream.on("error", () => this.positions.set(path, stat.size));
31932
- const rl = (0, import_node_readline5.createInterface)({ input: stream });
31933
- rl.on("line", (line) => this.parseDnsLine(line));
31934
- rl.on("close", () => this.positions.set(path, stat.size));
31935
- }
31936
32505
  parseDnsLine(line) {
31937
32506
  const moshpit = line.match(
31938
32507
  /\[dns\]\s+(?:udp|tcp|doh)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\w+)/i
@@ -32037,14 +32606,14 @@ var DnsMonitor = class {
32037
32606
  );
32038
32607
  }
32039
32608
  }
32040
- shannonEntropy(str2) {
32609
+ shannonEntropy(str3) {
32041
32610
  const freq = /* @__PURE__ */ new Map();
32042
- for (const ch of str2) {
32611
+ for (const ch of str3) {
32043
32612
  freq.set(ch, (freq.get(ch) || 0) + 1);
32044
32613
  }
32045
32614
  let entropy = 0;
32046
32615
  for (const count of freq.values()) {
32047
- const p = count / str2.length;
32616
+ const p = count / str3.length;
32048
32617
  if (p > 0) entropy -= p * Math.log2(p);
32049
32618
  }
32050
32619
  return entropy;
@@ -32186,15 +32755,15 @@ var ModuleHost = class {
32186
32755
  }
32187
32756
  }
32188
32757
  async discoverAndStartInstalled() {
32189
- if (!(0, import_node_fs24.existsSync)(PATHS.moduleDir)) return;
32758
+ if (!(0, import_node_fs27.existsSync)(PATHS.moduleDir)) return;
32190
32759
  const configs = loadModuleConfigs(PATHS.confD);
32191
- const entries = (0, import_node_fs24.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
32760
+ const entries = (0, import_node_fs27.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
32192
32761
  for (const entry of entries) {
32193
32762
  if (!entry.isDirectory()) continue;
32194
- const manifestPath = (0, import_node_path16.join)(PATHS.moduleDir, entry.name, "mod.toml");
32195
- if (!(0, import_node_fs24.existsSync)(manifestPath)) continue;
32763
+ const manifestPath = (0, import_node_path18.join)(PATHS.moduleDir, entry.name, "mod.toml");
32764
+ if (!(0, import_node_fs27.existsSync)(manifestPath)) continue;
32196
32765
  try {
32197
- const manifest = import_toml4.default.parse((0, import_node_fs24.readFileSync)(manifestPath, "utf-8"));
32766
+ const manifest = import_toml4.default.parse((0, import_node_fs27.readFileSync)(manifestPath, "utf-8"));
32198
32767
  const name = manifest.module?.name || entry.name;
32199
32768
  const defaults = manifest.module?.config?.defaults || {};
32200
32769
  const config = {
@@ -32208,7 +32777,7 @@ var ModuleHost = class {
32208
32777
  source: "installed",
32209
32778
  status: config.enabled === false ? "disabled" : "loaded",
32210
32779
  events: 0,
32211
- path: (0, import_node_path16.join)(PATHS.moduleDir, entry.name),
32780
+ path: (0, import_node_path18.join)(PATHS.moduleDir, entry.name),
32212
32781
  config
32213
32782
  };
32214
32783
  this.modules.set(name, hosted);
@@ -32223,7 +32792,7 @@ var ModuleHost = class {
32223
32792
  status: "error",
32224
32793
  events: 0,
32225
32794
  detail: `manifest load failed: ${String(err.message || err)}`,
32226
- path: (0, import_node_path16.join)(PATHS.moduleDir, entry.name)
32795
+ path: (0, import_node_path18.join)(PATHS.moduleDir, entry.name)
32227
32796
  });
32228
32797
  }
32229
32798
  }
@@ -32262,17 +32831,17 @@ var ModuleHost = class {
32262
32831
  }
32263
32832
  }
32264
32833
  installedEntrypoint(modulePath) {
32265
- const packageJson = (0, import_node_path16.join)(modulePath, "package.json");
32834
+ const packageJson = (0, import_node_path18.join)(modulePath, "package.json");
32266
32835
  const candidates = [];
32267
- if ((0, import_node_fs24.existsSync)(packageJson)) {
32836
+ if ((0, import_node_fs27.existsSync)(packageJson)) {
32268
32837
  try {
32269
- const pkg = JSON.parse((0, import_node_fs24.readFileSync)(packageJson, "utf-8"));
32270
- if (pkg.main) candidates.push((0, import_node_path16.join)(modulePath, pkg.main));
32838
+ const pkg = JSON.parse((0, import_node_fs27.readFileSync)(packageJson, "utf-8"));
32839
+ if (pkg.main) candidates.push((0, import_node_path18.join)(modulePath, pkg.main));
32271
32840
  } catch {
32272
32841
  }
32273
32842
  }
32274
- candidates.push((0, import_node_path16.join)(modulePath, "dist", "index.js"), (0, import_node_path16.join)(modulePath, "index.js"));
32275
- return candidates.find((candidate) => (0, import_node_fs24.existsSync)(candidate)) || null;
32843
+ candidates.push((0, import_node_path18.join)(modulePath, "dist", "index.js"), (0, import_node_path18.join)(modulePath, "index.js"));
32844
+ return candidates.find((candidate) => (0, import_node_fs27.existsSync)(candidate)) || null;
32276
32845
  }
32277
32846
  isThreatCrushModule(value) {
32278
32847
  return Boolean(
@@ -32316,7 +32885,7 @@ var ModuleHost = class {
32316
32885
  // src/daemon/alerts/smtp.ts
32317
32886
  var transporter = null;
32318
32887
  var nodemailer = null;
32319
- var SEVERITY_RANK = {
32888
+ var SEVERITY_RANK2 = {
32320
32889
  info: 0,
32321
32890
  low: 1,
32322
32891
  medium: 2,
@@ -32343,7 +32912,7 @@ async function ensureTransporter(config) {
32343
32912
  }
32344
32913
  function meetsSeverity(event, min) {
32345
32914
  if (!min) return true;
32346
- return (SEVERITY_RANK[event.severity] ?? 0) >= (SEVERITY_RANK[min] ?? 0);
32915
+ return (SEVERITY_RANK2[event.severity] ?? 0) >= (SEVERITY_RANK2[min] ?? 0);
32347
32916
  }
32348
32917
  function renderBody(event) {
32349
32918
  const ts = event.timestamp.toISOString();
@@ -32377,7 +32946,7 @@ function smtpChannel(config) {
32377
32946
  }
32378
32947
 
32379
32948
  // src/daemon/alerts/discord.ts
32380
- var SEVERITY_RANK2 = {
32949
+ var SEVERITY_RANK3 = {
32381
32950
  info: 0,
32382
32951
  low: 1,
32383
32952
  medium: 2,
@@ -32399,8 +32968,8 @@ var SEVERITY_COLORS2 = {
32399
32968
  function discordChannel(config) {
32400
32969
  return async (event) => {
32401
32970
  if (config.min_severity) {
32402
- const eventRank = SEVERITY_RANK2[event.severity] ?? 0;
32403
- const minRank = SEVERITY_RANK2[config.min_severity] ?? 0;
32971
+ const eventRank = SEVERITY_RANK3[event.severity] ?? 0;
32972
+ const minRank = SEVERITY_RANK3[config.min_severity] ?? 0;
32404
32973
  if (eventRank < minRank) return;
32405
32974
  }
32406
32975
  const embed = {
@@ -32423,7 +32992,7 @@ function discordChannel(config) {
32423
32992
  }
32424
32993
 
32425
32994
  // src/daemon/alerts/pagerduty.ts
32426
- var SEVERITY_RANK3 = {
32995
+ var SEVERITY_RANK4 = {
32427
32996
  info: 0,
32428
32997
  low: 1,
32429
32998
  medium: 2,
@@ -32440,8 +33009,8 @@ var PD_SEVERITY = {
32440
33009
  function pagerdutyChannel(config) {
32441
33010
  return async (event) => {
32442
33011
  if (config.min_severity) {
32443
- const eventRank = SEVERITY_RANK3[event.severity] ?? 0;
32444
- const minRank = SEVERITY_RANK3[config.min_severity] ?? 0;
33012
+ const eventRank = SEVERITY_RANK4[event.severity] ?? 0;
33013
+ const minRank = SEVERITY_RANK4[config.min_severity] ?? 0;
32445
33014
  if (eventRank < minRank) return;
32446
33015
  }
32447
33016
  const payload = {
@@ -32676,7 +33245,7 @@ var RunsWorker = class {
32676
33245
  };
32677
33246
 
32678
33247
  // src/core/cloud-events.ts
32679
- var import_node_crypto5 = require("crypto");
33248
+ var import_node_crypto6 = require("crypto");
32680
33249
  var import_node_net3 = require("net");
32681
33250
  function currentLink() {
32682
33251
  if (!hasSession()) return null;
@@ -32684,7 +33253,7 @@ function currentLink() {
32684
33253
  if (!cfg.server_id || !cfg.server_org_id) return null;
32685
33254
  return { serverId: cfg.server_id, orgId: cfg.server_org_id };
32686
33255
  }
32687
- var SEVERITY_RANK4 = {
33256
+ var SEVERITY_RANK5 = {
32688
33257
  info: 0,
32689
33258
  low: 1,
32690
33259
  medium: 2,
@@ -32721,7 +33290,7 @@ function trimMetadata(meta) {
32721
33290
  }
32722
33291
  return truncated ? { ...out, _truncated: true } : out;
32723
33292
  }
32724
- function str(value) {
33293
+ function str2(value) {
32725
33294
  return typeof value === "string" && value ? value : void 0;
32726
33295
  }
32727
33296
  function detectionEvent(serverId, event) {
@@ -32732,10 +33301,10 @@ function detectionEvent(serverId, event) {
32732
33301
  server_id: serverId,
32733
33302
  severity: event.severity,
32734
33303
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
32735
- rule_id: str(rule_id) ?? event.module,
32736
- description: str(description),
33304
+ rule_id: str2(rule_id) ?? event.module,
33305
+ description: str2(description),
32737
33306
  source_ip: event.source_ip && (0, import_node_net3.isIP)(event.source_ip) ? event.source_ip : void 0,
32738
- username: str(username) ?? str(user),
33307
+ username: str2(username) ?? str2(user),
32739
33308
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
32740
33309
  detected_at: event.timestamp.toISOString()
32741
33310
  };
@@ -32749,13 +33318,13 @@ function remediationEvent(serverId, event) {
32749
33318
  return {
32750
33319
  type: "remediation",
32751
33320
  server_id: serverId,
32752
- event_id: (0, import_node_crypto5.randomUUID)(),
33321
+ event_id: (0, import_node_crypto6.randomUUID)(),
32753
33322
  action_type: d.action,
32754
33323
  target_value: event.source_ip,
32755
33324
  status: d.failed === true ? "failed" : "executed",
32756
- rule_id: str(d.rule_id),
32757
- reason: str(d.reason),
32758
- error: str(d.error),
33325
+ rule_id: str2(d.rule_id),
33326
+ reason: str2(d.reason),
33327
+ error: str2(d.error),
32759
33328
  dry_run: d.dry_run === true,
32760
33329
  executed_at: at.toISOString(),
32761
33330
  expires_at: d.action === "block" && ttl !== null && d.failed !== true ? new Date(at.getTime() + ttl * 1e3).toISOString() : null
@@ -32775,16 +33344,16 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
32775
33344
  }
32776
33345
 
32777
33346
  // src/daemon/workers/cloud-spool.ts
32778
- var import_node_fs25 = require("fs");
33347
+ var import_node_fs28 = require("fs");
32779
33348
  var import_promises = require("fs/promises");
32780
- var import_node_path17 = require("path");
33349
+ var import_node_path19 = require("path");
32781
33350
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
32782
33351
  var CloudSpool = class {
32783
33352
  constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
32784
33353
  this.path = path;
32785
33354
  this.limits = limits;
32786
33355
  try {
32787
- (0, import_node_fs25.mkdirSync)((0, import_node_path17.dirname)(path), { recursive: true });
33356
+ (0, import_node_fs28.mkdirSync)((0, import_node_path19.dirname)(path), { recursive: true });
32788
33357
  } catch {
32789
33358
  }
32790
33359
  this.load();
@@ -32853,7 +33422,7 @@ var CloudSpool = class {
32853
33422
  load() {
32854
33423
  let raw;
32855
33424
  try {
32856
- raw = (0, import_node_fs25.readFileSync)(this.path, "utf-8");
33425
+ raw = (0, import_node_fs28.readFileSync)(this.path, "utf-8");
32857
33426
  } catch {
32858
33427
  return;
32859
33428
  }
@@ -32979,7 +33548,7 @@ var CloudSync = class {
32979
33548
  let out = null;
32980
33549
  if (event.module === "firewall-rules") {
32981
33550
  out = remediationEvent(link.serverId, event);
32982
- } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK4[event.severity] >= SEVERITY_RANK4[this.opts.minSeverity]) {
33551
+ } else if ((event.module === "rule-engine" || !this.opts.ruleModules.has(event.module)) && event.details?.heartbeat !== true && SEVERITY_RANK5[event.severity] >= SEVERITY_RANK5[this.opts.minSeverity]) {
32983
33552
  out = detectionEvent(link.serverId, event);
32984
33553
  }
32985
33554
  if (!out) return;
@@ -33558,8 +34127,8 @@ var RuleEngine = class {
33558
34127
  };
33559
34128
 
33560
34129
  // src/daemon/rules/loader.ts
33561
- var import_node_fs26 = require("fs");
33562
- var import_node_path18 = require("path");
34130
+ var import_node_fs29 = require("fs");
34131
+ var import_node_path20 = require("path");
33563
34132
 
33564
34133
  // src/daemon/rules/default-rules.ts
33565
34134
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -33960,11 +34529,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
33960
34529
  function loadAllRules(customDir) {
33961
34530
  const rules = [...DEFAULT_RULES];
33962
34531
  const dir = customDir || RULES_DIR;
33963
- if ((0, import_node_fs26.existsSync)(dir)) {
33964
- const files = (0, import_node_fs26.readdirSync)(dir).filter((f) => f.endsWith(".json"));
34532
+ if ((0, import_node_fs29.existsSync)(dir)) {
34533
+ const files = (0, import_node_fs29.readdirSync)(dir).filter((f) => f.endsWith(".json"));
33965
34534
  for (const file of files) {
33966
34535
  try {
33967
- const raw = (0, import_node_fs26.readFileSync)((0, import_node_path18.join)(dir, file), "utf-8");
34536
+ const raw = (0, import_node_fs29.readFileSync)((0, import_node_path20.join)(dir, file), "utf-8");
33968
34537
  const parsed = JSON.parse(raw);
33969
34538
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
33970
34539
  for (const rule of customRules) {
@@ -33996,8 +34565,8 @@ function loadAllRules(customDir) {
33996
34565
 
33997
34566
  // src/daemon/firewall/adapters.ts
33998
34567
  var import_node_child_process8 = require("child_process");
33999
- var import_node_fs27 = require("fs");
34000
- var import_node_path19 = require("path");
34568
+ var import_node_fs30 = require("fs");
34569
+ var import_node_path21 = require("path");
34001
34570
  var import_node_net7 = require("net");
34002
34571
  function assertValidFirewallIp(ip) {
34003
34572
  if ((0, import_node_net7.isIP)(ip) !== 4) {
@@ -34010,9 +34579,9 @@ function assertBannableIp(ip) {
34010
34579
  }
34011
34580
  }
34012
34581
  function writeIfAbsent(path, contents) {
34013
- (0, import_node_fs27.mkdirSync)((0, import_node_path19.dirname)(path), { recursive: true });
34582
+ (0, import_node_fs30.mkdirSync)((0, import_node_path21.dirname)(path), { recursive: true });
34014
34583
  try {
34015
- (0, import_node_fs27.writeFileSync)(path, contents, { flag: "wx" });
34584
+ (0, import_node_fs30.writeFileSync)(path, contents, { flag: "wx" });
34016
34585
  } catch (err) {
34017
34586
  if (err.code !== "EEXIST") throw err;
34018
34587
  }
@@ -34267,7 +34836,7 @@ function detectFirewallAdapter(backend = "auto") {
34267
34836
  }
34268
34837
 
34269
34838
  // src/daemon/firewall/remediation.ts
34270
- var import_node_fs28 = require("fs");
34839
+ var import_node_fs31 = require("fs");
34271
34840
  var import_node_net8 = require("net");
34272
34841
  init_paths();
34273
34842
  init_backoff();
@@ -34328,7 +34897,7 @@ var DEFAULT_CONFIG2 = {
34328
34897
  protect_current_ssh_client: true,
34329
34898
  spare_verified_crawlers: true
34330
34899
  };
34331
- var SEVERITY_RANK5 = {
34900
+ var SEVERITY_RANK6 = {
34332
34901
  info: 0,
34333
34902
  low: 1,
34334
34903
  medium: 2,
@@ -34392,8 +34961,8 @@ var RemediationManager = class {
34392
34961
  }
34393
34962
  async handleDetection(event) {
34394
34963
  if (!this.config.enabled) return;
34395
- const eventRank = SEVERITY_RANK5[event.severity] ?? 0;
34396
- const minRank = SEVERITY_RANK5[this.config.min_severity] ?? 3;
34964
+ const eventRank = SEVERITY_RANK6[event.severity] ?? 0;
34965
+ const minRank = SEVERITY_RANK6[this.config.min_severity] ?? 3;
34397
34966
  if (eventRank < minRank) return;
34398
34967
  if (isSuccessfulAuth(event.message)) return;
34399
34968
  if (event.details?.rule_id) {
@@ -34677,7 +35246,7 @@ var RemediationManager = class {
34677
35246
  }
34678
35247
  logLine(line) {
34679
35248
  try {
34680
- (0, import_node_fs28.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
35249
+ (0, import_node_fs31.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
34681
35250
  `);
34682
35251
  } catch {
34683
35252
  }
@@ -34714,6 +35283,66 @@ function remediationSettings(section) {
34714
35283
  // src/daemon/index.ts
34715
35284
  init_backoff();
34716
35285
 
35286
+ // src/daemon/watchdog-service.ts
35287
+ var import_node_fs32 = require("fs");
35288
+ var import_node_path22 = require("path");
35289
+ function defaultShareGid() {
35290
+ const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
35291
+ if (!isRoot4) return void 0;
35292
+ try {
35293
+ return (0, import_node_fs32.statSync)("/var/log/auth.log").gid;
35294
+ } catch {
35295
+ return void 0;
35296
+ }
35297
+ }
35298
+ function startWatchdog(opts) {
35299
+ const dir = opts.config?.dir ?? (0, import_node_path22.join)(opts.stateDir, WATCHDOG_DIRNAME);
35300
+ const base = { dir, logged: 0, answered: 0, errored: 0 };
35301
+ if (opts.config?.enabled === false) {
35302
+ opts.log("[watchdog] off ([watchdog] enabled = false)");
35303
+ return { status: () => ({ enabled: false, ...base }), stop: () => {
35304
+ } };
35305
+ }
35306
+ let log;
35307
+ try {
35308
+ log = new WatchdogLog(dir, { shareGid: opts.shareGid ?? defaultShareGid() });
35309
+ } catch (err) {
35310
+ const error2 = err.message;
35311
+ opts.log(`[watchdog] cannot open ${dir}: ${error2}`);
35312
+ return { status: () => ({ enabled: false, ...base, error: error2 }), stop: () => {
35313
+ } };
35314
+ }
35315
+ let error;
35316
+ const onEvent = (event) => {
35317
+ log.record(event);
35318
+ };
35319
+ const flush = () => {
35320
+ try {
35321
+ log.flush();
35322
+ error = void 0;
35323
+ } catch (err) {
35324
+ const message = err.message;
35325
+ if (message !== error) opts.log(`[watchdog] write failed: ${message}`);
35326
+ error = message;
35327
+ }
35328
+ };
35329
+ opts.bus.on("event", onEvent);
35330
+ const timer = setInterval(flush, opts.flushMs ?? 1e3);
35331
+ timer.unref?.();
35332
+ opts.log(`[watchdog] logging attacks to ${log.file}`);
35333
+ return {
35334
+ status: () => ({ enabled: true, dir, ...log.stats, ...error ? { error } : {} }),
35335
+ stop: () => {
35336
+ clearInterval(timer);
35337
+ opts.bus.off("event", onEvent);
35338
+ flush();
35339
+ }
35340
+ };
35341
+ }
35342
+
35343
+ // src/daemon/index.ts
35344
+ init_backoff();
35345
+
34717
35346
  // src/core/telemetry.ts
34718
35347
  var ready = false;
34719
35348
  var sentry = null;
@@ -34782,7 +35411,7 @@ function versionOfNode(path) {
34782
35411
  // src/daemon/index.ts
34783
35412
  function readVersion2() {
34784
35413
  try {
34785
- const pkg = JSON.parse((0, import_node_fs29.readFileSync)((0, import_node_path20.join)(__dirname, "..", "package.json"), "utf-8"));
35414
+ const pkg = JSON.parse((0, import_node_fs33.readFileSync)((0, import_node_path23.join)(__dirname, "..", "package.json"), "utf-8"));
34786
35415
  return pkg.version || "0.0.0";
34787
35416
  } catch {
34788
35417
  return "0.0.0";
@@ -34791,7 +35420,7 @@ function readVersion2() {
34791
35420
  async function runHardeningChecks() {
34792
35421
  const { stdout } = await (0, import_node_util.promisify)(import_node_child_process10.execFile)(
34793
35422
  process.execPath,
34794
- [(0, import_node_path20.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
35423
+ [(0, import_node_path23.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
34795
35424
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
34796
35425
  );
34797
35426
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -34799,7 +35428,7 @@ async function runHardeningChecks() {
34799
35428
  }
34800
35429
  function logLine(line) {
34801
35430
  try {
34802
- (0, import_node_fs29.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
35431
+ (0, import_node_fs33.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
34803
35432
  `);
34804
35433
  } catch {
34805
35434
  }
@@ -34841,8 +35470,20 @@ async function runDaemon() {
34841
35470
  } catch (err) {
34842
35471
  logLine(`[daemon] state db unavailable: ${err.message}`);
34843
35472
  }
34844
- const config = loadConfig((0, import_node_fs29.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
35473
+ const config = loadConfig((0, import_node_fs33.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
34845
35474
  configureAttackDetection(config.detection);
35475
+ const retentionSeconds = parseDuration(config.storage?.event_retention) ?? DEFAULT_EVENT_RETENTION_SECONDS;
35476
+ const maxEvents = config.storage?.max_events ?? DEFAULT_MAX_EVENTS;
35477
+ const prune = () => {
35478
+ try {
35479
+ const n = pruneEvents({ retentionSeconds, maxEvents });
35480
+ if (n) logLine(`[daemon] pruned ${n} events (keep ${config.storage?.event_retention ?? "14d"}, at most ${maxEvents})`);
35481
+ } catch (err) {
35482
+ logLine(`[daemon] event pruning failed: ${err.message}`);
35483
+ }
35484
+ };
35485
+ setTimeout(prune, 5e3);
35486
+ setInterval(prune, 6e4);
34846
35487
  bus.on("event", (event) => {
34847
35488
  logLine(`[event] ${event.severity} ${event.module} ${event.message}`);
34848
35489
  });
@@ -34908,7 +35549,7 @@ async function runDaemon() {
34908
35549
  version,
34909
35550
  hostname: (0, import_node_os9.hostname)(),
34910
35551
  minSeverity,
34911
- spoolPath: (0, import_node_path20.join)(PATHS.stateDir, "cloud-spool.jsonl"),
35552
+ spoolPath: (0, import_node_path23.join)(PATHS.stateDir, "cloud-spool.jsonl"),
34912
35553
  log: logLine,
34913
35554
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
34914
35555
  runHardening: runHardeningChecks
@@ -34921,7 +35562,8 @@ async function runDaemon() {
34921
35562
  const link = currentLink();
34922
35563
  logLine(link ? `[cloud] reporting as server ${link.serverId} (org ${link.orgId}), detections >= ${minSeverity}` : "[cloud] not linked; run `threatcrush login` and `threatcrush servers link` to report to the dashboard");
34923
35564
  }
34924
- const ipc = new IpcServer(version, moduleHost, remediation);
35565
+ const watchdog = startWatchdog({ bus, config: config.watchdog, stateDir: PATHS.stateDir, log: logLine });
35566
+ const ipc = new IpcServer(version, moduleHost, remediation, () => watchdog.status());
34925
35567
  await ipc.start();
34926
35568
  logLine(`[daemon] ipc listening on ${PATHS.socket}`);
34927
35569
  const shutdown = async (signal) => {
@@ -34950,6 +35592,10 @@ async function runDaemon() {
34950
35592
  await moduleHost.stop();
34951
35593
  } catch {
34952
35594
  }
35595
+ try {
35596
+ watchdog.stop();
35597
+ } catch {
35598
+ }
34953
35599
  try {
34954
35600
  await ipc.stop();
34955
35601
  } catch {
@@ -34985,7 +35631,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
34985
35631
  function isRoot2() {
34986
35632
  return typeof process.getuid === "function" && process.getuid() === 0;
34987
35633
  }
34988
- var DAEMON_ENTRY = (0, import_node_path21.join)(__dirname, "daemon.js");
35634
+ var DAEMON_ENTRY = (0, import_node_path24.join)(__dirname, "daemon.js");
34989
35635
  async function daemonForeground() {
34990
35636
  await runDaemon();
34991
35637
  }
@@ -35006,7 +35652,7 @@ async function daemonStart() {
35006
35652
  return;
35007
35653
  }
35008
35654
  ensureRuntimeDirs();
35009
- if (!(0, import_node_fs30.existsSync)(DAEMON_ENTRY)) {
35655
+ if (!(0, import_node_fs34.existsSync)(DAEMON_ENTRY)) {
35010
35656
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
35011
35657
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
35012
35658
  return;
@@ -35014,8 +35660,8 @@ async function daemonStart() {
35014
35660
  let out;
35015
35661
  let err;
35016
35662
  try {
35017
- out = (0, import_node_fs31.openSync)(PATHS.logFile, "a");
35018
- err = (0, import_node_fs31.openSync)(PATHS.logFile, "a");
35663
+ out = (0, import_node_fs35.openSync)(PATHS.logFile, "a");
35664
+ err = (0, import_node_fs35.openSync)(PATHS.logFile, "a");
35019
35665
  } catch (e) {
35020
35666
  const code = e.code;
35021
35667
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -35103,12 +35749,12 @@ async function waitForExit(pid, timeoutMs) {
35103
35749
  }
35104
35750
  async function releaseStaleSocket() {
35105
35751
  const deadline = Date.now() + 2e3;
35106
- while ((0, import_node_fs30.existsSync)(PATHS.socket) && Date.now() < deadline) {
35752
+ while ((0, import_node_fs34.existsSync)(PATHS.socket) && Date.now() < deadline) {
35107
35753
  await new Promise((r) => setTimeout(r, 50));
35108
35754
  }
35109
- if ((0, import_node_fs30.existsSync)(PATHS.socket)) {
35755
+ if ((0, import_node_fs34.existsSync)(PATHS.socket)) {
35110
35756
  try {
35111
- (0, import_node_fs30.unlinkSync)(PATHS.socket);
35757
+ (0, import_node_fs34.unlinkSync)(PATHS.socket);
35112
35758
  } catch {
35113
35759
  }
35114
35760
  }
@@ -35116,26 +35762,26 @@ async function releaseStaleSocket() {
35116
35762
 
35117
35763
  // src/commands/service.ts
35118
35764
  var import_node_child_process12 = require("child_process");
35119
- var import_node_fs32 = require("fs");
35120
- var import_node_path22 = require("path");
35765
+ var import_node_fs36 = require("fs");
35766
+ var import_node_path25 = require("path");
35121
35767
  var import_node_os10 = require("os");
35122
35768
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
35123
35769
  var DAEMON_UNIT_NAME = "threatcrushd.service";
35124
35770
  function resolveTemplate() {
35125
- const templatePath = (0, import_node_path22.join)(__dirname, "systemd", "threatcrushd.service");
35126
- if (!(0, import_node_fs32.existsSync)(templatePath)) {
35771
+ const templatePath = (0, import_node_path25.join)(__dirname, "systemd", "threatcrushd.service");
35772
+ if (!(0, import_node_fs36.existsSync)(templatePath)) {
35127
35773
  throw new Error(`systemd unit template not found at ${templatePath}`);
35128
35774
  }
35129
- return (0, import_node_fs32.readFileSync)(templatePath, "utf-8");
35775
+ return (0, import_node_fs36.readFileSync)(templatePath, "utf-8");
35130
35776
  }
35131
35777
  function stableBinPath(binPath) {
35132
35778
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
35133
35779
  if (stable === binPath) return binPath;
35134
- return (0, import_node_fs32.existsSync)(stable) ? stable : binPath;
35780
+ return (0, import_node_fs36.existsSync)(stable) ? stable : binPath;
35135
35781
  }
35136
35782
  function resolveBinPath() {
35137
35783
  const arg = process.argv[1];
35138
- if (arg && (0, import_node_fs32.existsSync)(arg)) return stableBinPath(arg);
35784
+ if (arg && (0, import_node_fs36.existsSync)(arg)) return stableBinPath(arg);
35139
35785
  try {
35140
35786
  return (0, import_node_child_process12.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
35141
35787
  } catch {
@@ -35145,11 +35791,11 @@ function resolveBinPath() {
35145
35791
  function stableNodePath(execPath) {
35146
35792
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
35147
35793
  if (stable === execPath) return execPath;
35148
- return (0, import_node_fs32.existsSync)(stable) ? stable : execPath;
35794
+ return (0, import_node_fs36.existsSync)(stable) ? stable : execPath;
35149
35795
  }
35150
35796
  function looksLikeNodeScript(path) {
35151
35797
  try {
35152
- const head = (0, import_node_fs32.readFileSync)(path, "utf-8").slice(0, 120);
35798
+ const head = (0, import_node_fs36.readFileSync)(path, "utf-8").slice(0, 120);
35153
35799
  return /^#!.*\bnode\b/.test(head);
35154
35800
  } catch {
35155
35801
  return false;
@@ -35189,7 +35835,7 @@ function callerHome() {
35189
35835
  try {
35190
35836
  const line = (0, import_node_child_process12.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
35191
35837
  const home = line.split(":")[5];
35192
- return home && (0, import_node_fs32.existsSync)(home) ? home : null;
35838
+ return home && (0, import_node_fs36.existsSync)(home) ? home : null;
35193
35839
  } catch {
35194
35840
  return null;
35195
35841
  }
@@ -35197,13 +35843,13 @@ function callerHome() {
35197
35843
  function stopUserModeDaemon() {
35198
35844
  const home = callerHome();
35199
35845
  if (!home) return;
35200
- const runDir = (0, import_node_path22.join)(home, ".threatcrush", "run");
35201
- const pidFile = (0, import_node_path22.join)(runDir, "threatcrushd.pid");
35202
- const socket = (0, import_node_path22.join)(runDir, "threatcrushd.sock");
35203
- if (!(0, import_node_fs32.existsSync)(pidFile) && !(0, import_node_fs32.existsSync)(socket)) return;
35846
+ const runDir = (0, import_node_path25.join)(home, ".threatcrush", "run");
35847
+ const pidFile = (0, import_node_path25.join)(runDir, "threatcrushd.pid");
35848
+ const socket = (0, import_node_path25.join)(runDir, "threatcrushd.sock");
35849
+ if (!(0, import_node_fs36.existsSync)(pidFile) && !(0, import_node_fs36.existsSync)(socket)) return;
35204
35850
  let pid = null;
35205
35851
  try {
35206
- pid = Number.parseInt((0, import_node_fs32.readFileSync)(pidFile, "utf-8").trim(), 10);
35852
+ pid = Number.parseInt((0, import_node_fs36.readFileSync)(pidFile, "utf-8").trim(), 10);
35207
35853
  } catch {
35208
35854
  pid = null;
35209
35855
  }
@@ -35216,7 +35862,7 @@ function stopUserModeDaemon() {
35216
35862
  }
35217
35863
  for (const path of [socket, pidFile]) {
35218
35864
  try {
35219
- if ((0, import_node_fs32.existsSync)(path)) (0, import_node_fs32.rmSync)(path);
35865
+ if ((0, import_node_fs36.existsSync)(path)) (0, import_node_fs36.rmSync)(path);
35220
35866
  } catch {
35221
35867
  }
35222
35868
  }
@@ -35234,7 +35880,7 @@ async function installServiceCommand() {
35234
35880
  }
35235
35881
  const noSystemd = systemdUnavailableReason({
35236
35882
  hasSystemctl: (0, import_node_child_process12.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
35237
- booted: (0, import_node_fs32.existsSync)("/run/systemd/system")
35883
+ booted: (0, import_node_fs36.existsSync)("/run/systemd/system")
35238
35884
  });
35239
35885
  if (noSystemd) {
35240
35886
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -35256,7 +35902,7 @@ async function installServiceCommand() {
35256
35902
  const isNodeScript = looksLikeNodeScript(binPath);
35257
35903
  let nodePath = stableNodePath(process.execPath);
35258
35904
  if (isNodeScript && nodeVersionDir(binPath)) {
35259
- binPath = (0, import_node_fs32.realpathSync)(binPath);
35905
+ binPath = (0, import_node_fs36.realpathSync)(binPath);
35260
35906
  nodePath = process.execPath;
35261
35907
  }
35262
35908
  if (isNodeScript) {
@@ -35269,9 +35915,9 @@ async function installServiceCommand() {
35269
35915
  }
35270
35916
  }
35271
35917
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
35272
- const configDir = (0, import_node_path22.join)((0, import_node_os10.homedir)(), ".threatcrush");
35918
+ const configDir = (0, import_node_path25.join)((0, import_node_os10.homedir)(), ".threatcrush");
35273
35919
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
35274
- (0, import_node_fs32.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
35920
+ (0, import_node_fs36.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
35275
35921
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
35276
35922
  console.log(source_default.dim(` ExecStart=${exec}`));
35277
35923
  const nodeDir = nodeVersionDir(nodePath);
@@ -35320,20 +35966,20 @@ function ensureSystemDirs(configDir) {
35320
35966
  ];
35321
35967
  let admGid = null;
35322
35968
  try {
35323
- admGid = (0, import_node_fs32.statSync)("/var/log/auth.log").gid;
35969
+ admGid = (0, import_node_fs36.statSync)("/var/log/auth.log").gid;
35324
35970
  } catch {
35325
35971
  }
35326
35972
  for (const { path, groupWritable, sticky } of dirs) {
35327
35973
  try {
35328
- (0, import_node_fs32.mkdirSync)(path, { recursive: true });
35974
+ (0, import_node_fs36.mkdirSync)(path, { recursive: true });
35329
35975
  } catch {
35330
35976
  }
35331
35977
  try {
35332
35978
  if (groupWritable && admGid !== null) {
35333
- (0, import_node_fs32.chmodSync)(path, sticky ? 1533 : 509);
35979
+ (0, import_node_fs36.chmodSync)(path, sticky ? 1533 : 509);
35334
35980
  (0, import_node_child_process12.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
35335
35981
  } else {
35336
- (0, import_node_fs32.chmodSync)(path, 493);
35982
+ (0, import_node_fs36.chmodSync)(path, 493);
35337
35983
  }
35338
35984
  } catch {
35339
35985
  }
@@ -35361,7 +36007,7 @@ async function uninstallServiceCommand() {
35361
36007
  } catch {
35362
36008
  }
35363
36009
  try {
35364
- if ((0, import_node_fs32.existsSync)(UNIT_PATH)) {
36010
+ if ((0, import_node_fs36.existsSync)(UNIT_PATH)) {
35365
36011
  (0, import_node_child_process12.execSync)(`rm -f ${UNIT_PATH}`);
35366
36012
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
35367
36013
  }
@@ -35375,7 +36021,7 @@ async function uninstallServiceCommand() {
35375
36021
  }
35376
36022
 
35377
36023
  // src/commands/save.ts
35378
- var import_node_fs33 = require("fs");
36024
+ var import_node_fs37 = require("fs");
35379
36025
  var import_toml5 = __toESM(require_toml());
35380
36026
  init_paths();
35381
36027
  var SECRET_KEY = /pass(word)?|secret|token|api_?key|private|webhook|dsn|url|routing_key|auth/i;
@@ -35413,9 +36059,9 @@ async function saveCommand(opts = {}) {
35413
36059
  }
35414
36060
  const path = opts.config ?? PATHS.configFile;
35415
36061
  let config = {};
35416
- if ((0, import_node_fs33.existsSync)(path)) {
36062
+ if ((0, import_node_fs37.existsSync)(path)) {
35417
36063
  try {
35418
- config = import_toml5.default.parse((0, import_node_fs33.readFileSync)(path, "utf-8"));
36064
+ config = import_toml5.default.parse((0, import_node_fs37.readFileSync)(path, "utf-8"));
35419
36065
  } catch (err) {
35420
36066
  console.log(source_default.red(` \u2717 ${path} is not valid TOML: ${err.message}
35421
36067
  `));
@@ -35527,16 +36173,16 @@ function welcomeCommand() {
35527
36173
  }
35528
36174
 
35529
36175
  // src/commands/properties.ts
35530
- var import_node_fs34 = require("fs");
35531
- var import_node_path23 = require("path");
35532
- var import_node_readline6 = __toESM(require("readline"));
36176
+ var import_node_fs38 = require("fs");
36177
+ var import_node_path26 = require("path");
36178
+ var import_node_readline4 = __toESM(require("readline"));
35533
36179
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
35534
36180
  var KINDS = ["url", "api", "domain", "ip", "repo"];
35535
36181
  function prompt(question) {
35536
- const rl = import_node_readline6.default.createInterface({ input: process.stdin, output: process.stdout });
35537
- return new Promise((resolve5) => rl.question(question, (answer) => {
36182
+ const rl = import_node_readline4.default.createInterface({ input: process.stdin, output: process.stdout });
36183
+ return new Promise((resolve6) => rl.question(question, (answer) => {
35538
36184
  rl.close();
35539
- resolve5(answer.trim());
36185
+ resolve6(answer.trim());
35540
36186
  }));
35541
36187
  }
35542
36188
  async function requireAuth() {
@@ -35857,8 +36503,8 @@ async function propertiesRunsCommand(opts) {
35857
36503
  }
35858
36504
  }
35859
36505
  function parseImportFile(path) {
35860
- const ext = (0, import_node_path23.extname)(path).toLowerCase();
35861
- const raw = (0, import_node_fs34.readFileSync)(path, "utf-8");
36506
+ const ext = (0, import_node_path26.extname)(path).toLowerCase();
36507
+ const raw = (0, import_node_fs38.readFileSync)(path, "utf-8");
35862
36508
  if (ext === ".json") {
35863
36509
  const parsed = JSON.parse(raw);
35864
36510
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -36053,7 +36699,7 @@ async function rulesCommand(opts) {
36053
36699
  }
36054
36700
 
36055
36701
  // src/commands/harden.ts
36056
- var import_node_fs35 = require("fs");
36702
+ var import_node_fs39 = require("fs");
36057
36703
  var import_node_child_process13 = require("child_process");
36058
36704
  function tryExec(cmd) {
36059
36705
  try {
@@ -36064,7 +36710,7 @@ function tryExec(cmd) {
36064
36710
  }
36065
36711
  function tryRead(path) {
36066
36712
  try {
36067
- return (0, import_node_fs35.readFileSync)(path, "utf-8");
36713
+ return (0, import_node_fs39.readFileSync)(path, "utf-8");
36068
36714
  } catch {
36069
36715
  return null;
36070
36716
  }
@@ -36168,8 +36814,8 @@ function checkSshWeakConfig() {
36168
36814
  };
36169
36815
  }
36170
36816
  function checkAutoUpdates() {
36171
- const unattended = (0, import_node_fs35.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs35.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
36172
- const dnfAuto = (0, import_node_fs35.existsSync)("/etc/dnf/automatic.conf");
36817
+ const unattended = (0, import_node_fs39.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs39.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
36818
+ const dnfAuto = (0, import_node_fs39.existsSync)("/etc/dnf/automatic.conf");
36173
36819
  if (unattended || dnfAuto) {
36174
36820
  return {
36175
36821
  key: "auto-updates",
@@ -36295,7 +36941,7 @@ function checkFail2ban() {
36295
36941
  explanation: "fail2ban is installed and running."
36296
36942
  };
36297
36943
  }
36298
- if ((0, import_node_fs35.existsSync)("/etc/fail2ban/fail2ban.conf")) {
36944
+ if ((0, import_node_fs39.existsSync)("/etc/fail2ban/fail2ban.conf")) {
36299
36945
  return {
36300
36946
  key: checkKey,
36301
36947
  status: "warn",
@@ -36743,7 +37389,7 @@ ${source_default.dim(" C R U S H")}
36743
37389
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
36744
37390
  var PKG_NAME = "@profullstack/threatcrush";
36745
37391
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
36746
- var INSTALL_CONFIG_PATH = (0, import_node_path24.join)((0, import_node_os11.homedir)(), ".threatcrush", "install.json");
37392
+ var INSTALL_CONFIG_PATH = (0, import_node_path27.join)((0, import_node_os11.homedir)(), ".threatcrush", "install.json");
36747
37393
  function detectPackageManager() {
36748
37394
  try {
36749
37395
  const npmGlobal = (0, import_node_child_process15.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
@@ -36769,7 +37415,7 @@ function detectPackageManager() {
36769
37415
  }
36770
37416
  function readInstallConfig() {
36771
37417
  try {
36772
- return JSON.parse((0, import_node_fs36.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
37418
+ return JSON.parse((0, import_node_fs40.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
36773
37419
  } catch {
36774
37420
  return {};
36775
37421
  }
@@ -36906,6 +37552,7 @@ program2.name("threatcrush").description(
36906
37552
  ${source_default.dim("Examples:")}
36907
37553
  ${source_default.green("$")} threatcrush monitor ${source_default.dim("# Real-time monitoring")}
36908
37554
  ${source_default.green("$")} threatcrush tui ${source_default.dim("# Interactive dashboard")}
37555
+ ${source_default.green("$")} threatcrush watchdog ${source_default.dim("# Triage logged attacks: hole or not?")}
36909
37556
  ${source_default.green("$")} threatcrush scan ./src ${source_default.dim("# Scan code for vulns")}
36910
37557
  ${source_default.green("$")} threatcrush pentest URL ${source_default.dim("# Quick web checks on a URL")}
36911
37558
  ${source_default.green("$")} threatcrush ai-scan URL ${source_default.dim("# Red-team your AI/LLM endpoint (OWASP LLM Top 10)")}
@@ -36936,6 +37583,24 @@ program2.command("monitor").description("Watch nginx, auth and syslog for attack
36936
37583
  program2.command("tui").description("Interactive security dashboard (htop for security)").alias("dashboard").option("--demo", "Run on canned events instead of connecting to the daemon").action(async (opts) => {
36937
37584
  await monitorCommand({ tui: true, demo: opts.demo });
36938
37585
  });
37586
+ var watchdogCmd = program2.command("watchdog").description("Triage the attacks the daemon logged: was it a hole? fix it, PR it, mark it").option("--dir <dir>", "Watchdog log directory").action((opts) => {
37587
+ watchdogListCommand(opts);
37588
+ });
37589
+ watchdogCmd.command("list").alias("ls").description("Findings to triage, worst first (answered 2xx, then 5xx, ...)").option("--status <status>", "Only this triage status: new | hole | fp | fixed").option("--outcome <outcome>", "Only this outcome: answered | errored | unknown | redirected | refused").option("-a, --all", "Include refused and already-triaged findings").option("-n, --limit <n>", "Show at most n findings", "50").option("--json", "Output findings as JSON").action((_opts, cmd) => {
37590
+ watchdogListCommand(cmd.optsWithGlobals());
37591
+ });
37592
+ watchdogCmd.command("show <id>").description("Every detail of one finding: samples, sources, a repro command").option("--json", "Output as JSON").action((id, _opts, cmd) => {
37593
+ watchdogShowCommand(id, cmd.optsWithGlobals());
37594
+ });
37595
+ watchdogCmd.command("brief <id>").description("Markdown hand-off to verify and fix one finding (paste into an issue, PR or agent)").action((id, _opts, cmd) => {
37596
+ watchdogBriefCommand(id, cmd.optsWithGlobals());
37597
+ });
37598
+ watchdogCmd.command("mark <id> <status>").description("Record a verdict: hole | fp | fixed | new").option("--note <text>", "Why: what you checked, what you found").option("--pr <url>", "The PR that fixes it").action((id, status, _opts, cmd) => {
37599
+ watchdogMarkCommand(id, status, cmd.optsWithGlobals());
37600
+ });
37601
+ watchdogCmd.command("path").description("Print the watchdog log directory").action((_opts, cmd) => {
37602
+ watchdogPathCommand(cmd.optsWithGlobals());
37603
+ });
36939
37604
  program2.command("init").description("Sign in, auto-detect services, and configure ThreatCrush").option("-y, --yes", "Don't ask; answer yes to every question").option("--offline", "Skip signing in to threatcrush.com").action(async (opts) => {
36940
37605
  await initCommand({ yes: opts.yes, offline: opts.offline });
36941
37606
  });
@@ -37043,7 +37708,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
37043
37708
  program2.command("logs").description("Tail daemon logs").action(async () => {
37044
37709
  console.log(LOGO2);
37045
37710
  const logPath = PATHS.logFile;
37046
- if (!(0, import_node_fs36.existsSync)(logPath)) {
37711
+ if (!(0, import_node_fs40.existsSync)(logPath)) {
37047
37712
  console.log(source_default.yellow(` No log file found at ${logPath}`));
37048
37713
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
37049
37714
  return;
@@ -37111,10 +37776,10 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
37111
37776
  program2.command("remove").description("Uninstall ThreatCrush and the installed bundle").alias("uninstall").action(async () => {
37112
37777
  console.log(LOGO2);
37113
37778
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
37114
- const confirm = await new Promise((resolve5) => {
37779
+ const confirm = await new Promise((resolve6) => {
37115
37780
  rl.question(source_default.yellow(" Are you sure you want to uninstall ThreatCrush? (y/N): "), (answer) => {
37116
37781
  rl.close();
37117
- resolve5(answer.trim().toLowerCase());
37782
+ resolve6(answer.trim().toLowerCase());
37118
37783
  });
37119
37784
  });
37120
37785
  if (confirm !== "y" && confirm !== "yes") {
@@ -37216,19 +37881,19 @@ storeCmd.command("search <query>").description("Search for modules in the store"
37216
37881
  });
37217
37882
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
37218
37883
  console.log(LOGO2);
37219
- const configPath = (0, import_node_path24.join)((0, import_node_os11.homedir)(), ".threatcrush", "config.json");
37884
+ const configPath = (0, import_node_path27.join)((0, import_node_os11.homedir)(), ".threatcrush", "config.json");
37220
37885
  let email = "";
37221
37886
  try {
37222
- const config = JSON.parse((0, import_node_fs36.readFileSync)(configPath, "utf-8"));
37887
+ const config = JSON.parse((0, import_node_fs40.readFileSync)(configPath, "utf-8"));
37223
37888
  email = config.email || "";
37224
37889
  } catch {
37225
37890
  }
37226
37891
  if (!email) {
37227
37892
  const rl2 = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
37228
- email = await new Promise((resolve5) => {
37893
+ email = await new Promise((resolve6) => {
37229
37894
  rl2.question(source_default.green(" Enter your email: "), (answer) => {
37230
37895
  rl2.close();
37231
- resolve5(answer.trim());
37896
+ resolve6(answer.trim());
37232
37897
  });
37233
37898
  });
37234
37899
  if (!email || !email.includes("@")) {
@@ -37236,9 +37901,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
37236
37901
  return;
37237
37902
  }
37238
37903
  try {
37239
- const dir = (0, import_node_path24.join)((0, import_node_os11.homedir)(), ".threatcrush");
37240
- if (!(0, import_node_fs36.existsSync)(dir)) (0, import_node_fs36.mkdirSync)(dir, { recursive: true });
37241
- (0, import_node_fs36.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
37904
+ const dir = (0, import_node_path27.join)((0, import_node_os11.homedir)(), ".threatcrush");
37905
+ if (!(0, import_node_fs40.existsSync)(dir)) (0, import_node_fs40.mkdirSync)(dir, { recursive: true });
37906
+ (0, import_node_fs40.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
37242
37907
  console.log(source_default.dim(` Saved email to ${configPath}`));
37243
37908
  } catch {
37244
37909
  }
@@ -37282,10 +37947,10 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
37282
37947
  }
37283
37948
  console.log();
37284
37949
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
37285
- const confirm = await new Promise((resolve5) => {
37950
+ const confirm = await new Promise((resolve6) => {
37286
37951
  rl.question(source_default.yellow(" Publish this module? (y/N): "), (answer) => {
37287
37952
  rl.close();
37288
- resolve5(answer.trim().toLowerCase());
37953
+ resolve6(answer.trim().toLowerCase());
37289
37954
  });
37290
37955
  });
37291
37956
  if (confirm !== "y" && confirm !== "yes") {
@@ -37335,8 +38000,8 @@ orgsCmd.command("create <name>").description("Create a new organization").action
37335
38000
  orgsCmd.command("use <slug>").description("Switch to an organization").action(async (slug) => {
37336
38001
  await orgsCommand({ action: "use", name: slug });
37337
38002
  });
37338
- var serversCmd = program2.command("servers").alias("server").alias("srv").description("Manage servers").action(async (opts) => {
37339
- await serversCommand({ action: opts });
38003
+ var serversCmd = program2.command("servers").alias("server").alias("srv").description("Manage servers").action(async () => {
38004
+ await serversCommand({ action: "list" });
37340
38005
  });
37341
38006
  serversCmd.command("list").alias("ls").option("--org <slug>", "Filter by organization slug").description("List servers in current organization").action(async (opts) => {
37342
38007
  await serversCommand({ action: "list", org: opts.org });