@profullstack/threatcrush 0.13.20 → 0.13.21

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() {
@@ -12911,7 +12911,7 @@ var init_ipc_client = __esm({
12911
12911
  if (!(0, import_node_fs6.existsSync)(this.socketPath)) {
12912
12912
  throw new Error(`threatcrushd socket not found at ${this.socketPath}`);
12913
12913
  }
12914
- return new Promise((resolve5, reject) => {
12914
+ return new Promise((resolve6, reject) => {
12915
12915
  const sock = (0, import_node_net.createConnection)(this.socketPath);
12916
12916
  const timer = setTimeout(() => {
12917
12917
  sock.destroy();
@@ -12924,7 +12924,7 @@ var init_ipc_client = __esm({
12924
12924
  sock.on("data", (chunk) => this.onData(chunk.toString()));
12925
12925
  sock.on("close", () => this.onClose());
12926
12926
  sock.on("error", () => this.onClose());
12927
- resolve5();
12927
+ resolve6();
12928
12928
  });
12929
12929
  sock.once("error", (err) => {
12930
12930
  clearTimeout(timer);
@@ -12940,14 +12940,14 @@ var init_ipc_client = __esm({
12940
12940
  if (!this.socket) throw new Error("not connected");
12941
12941
  const id = this.nextId++;
12942
12942
  const frame = params ? { id, method, params } : { id, method };
12943
- return new Promise((resolve5, reject) => {
12943
+ return new Promise((resolve6, reject) => {
12944
12944
  const timer = setTimeout(() => {
12945
12945
  this.pending.delete(id);
12946
12946
  reject(new Error(
12947
12947
  `threatcrushd did not answer "${method}" within ${REQUEST_TIMEOUT_MS / 1e3}s; if it is older than this CLI, update it`
12948
12948
  ));
12949
12949
  }, REQUEST_TIMEOUT_MS);
12950
- this.pending.set(id, { resolve: resolve5, reject, timer });
12950
+ this.pending.set(id, { resolve: resolve6, reject, timer });
12951
12951
  this.socket.write(JSON.stringify(frame) + "\n", (err) => {
12952
12952
  if (err && this.pending.delete(id)) {
12953
12953
  clearTimeout(timer);
@@ -13030,6 +13030,11 @@ var init_ipc_client = __esm({
13030
13030
  });
13031
13031
 
13032
13032
  // src/tui/state.ts
13033
+ function watchdogView(status) {
13034
+ const wd = status.watchdog;
13035
+ if (!wd) return OFF_WATCHDOG;
13036
+ return { on: wd.enabled, logged: wd.logged, answered: wd.answered, errored: wd.errored };
13037
+ }
13033
13038
  function initialState(now = Date.now()) {
13034
13039
  return {
13035
13040
  connection: "searching",
@@ -13058,7 +13063,8 @@ function initialState(now = Date.now()) {
13058
13063
  moduleFilter: null,
13059
13064
  sourceFilter: null,
13060
13065
  showNoise: false,
13061
- muteCron: false
13066
+ muteCron: false,
13067
+ watchdog: OFF_WATCHDOG
13062
13068
  };
13063
13069
  }
13064
13070
  function isCronLine(event) {
@@ -13118,6 +13124,7 @@ function reducer(state, action) {
13118
13124
  connectionLabel: action.label,
13119
13125
  daemon: action.status,
13120
13126
  modules: action.status.modules,
13127
+ watchdog: watchdogView(action.status),
13121
13128
  counters: {
13122
13129
  events: action.status.counters.events,
13123
13130
  threats: action.status.counters.threats,
@@ -13125,7 +13132,7 @@ function reducer(state, action) {
13125
13132
  }
13126
13133
  };
13127
13134
  case "connection_lost":
13128
- return { ...state, connection: "lost", connectionLabel: action.label, daemon: null };
13135
+ return { ...state, connection: "lost", connectionLabel: action.label, daemon: null, watchdog: OFF_WATCHDOG };
13129
13136
  case "event": {
13130
13137
  if (state.paused) {
13131
13138
  return { ...state, parked: [...state.parked, action.event].slice(-FEED_LIMIT) };
@@ -13267,7 +13274,9 @@ function reducer(state, action) {
13267
13274
  sourceFilter: state.sourceFilter,
13268
13275
  moduleIndex: state.moduleIndex,
13269
13276
  showNoise: state.showNoise,
13270
- muteCron: state.muteCron
13277
+ muteCron: state.muteCron,
13278
+ // Reset clears the view; the watchdog log on disk is not the view.
13279
+ watchdog: state.watchdog
13271
13280
  };
13272
13281
  }
13273
13282
  }
@@ -13296,12 +13305,13 @@ function formatCount(n) {
13296
13305
  if (n < 1e6) return `${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}k`;
13297
13306
  return `${(n / 1e6).toFixed(1)}M`;
13298
13307
  }
13299
- var FOCUS_ORDER, NOTICE_MS, TIMELINE_SLOTS, FEED_LIMIT, SEVERITIES;
13308
+ var FOCUS_ORDER, NOTICE_MS, OFF_WATCHDOG, TIMELINE_SLOTS, FEED_LIMIT, SEVERITIES;
13300
13309
  var init_state = __esm({
13301
13310
  "src/tui/state.ts"() {
13302
13311
  "use strict";
13303
13312
  FOCUS_ORDER = ["feed", "modules", "threats", "bans"];
13304
13313
  NOTICE_MS = 6e3;
13314
+ OFF_WATCHDOG = { on: false, logged: 0, answered: 0, errored: 0 };
13305
13315
  TIMELINE_SLOTS = 60;
13306
13316
  FEED_LIMIT = 500;
13307
13317
  SEVERITIES = ["info", "low", "medium", "high", "critical"];
@@ -13430,6 +13440,15 @@ function connectionBadge(state, demo) {
13430
13440
  }
13431
13441
  return { glyph: "\u25CB", label: "OFFLINE", color: severityColors.high };
13432
13442
  }
13443
+ function watchdogBadge(state) {
13444
+ const wd = state.watchdog;
13445
+ if (!wd.on) return null;
13446
+ const hot = wd.answered + wd.errored;
13447
+ const parts = [`\u25C9 WATCHDOG ${formatCount(wd.logged)}`];
13448
+ if (wd.answered) parts.push(`${formatCount(wd.answered)} answered`);
13449
+ if (wd.errored) parts.push(`${formatCount(wd.errored)} 5xx`);
13450
+ return { label: parts.join(" \xB7 "), color: hot > 0 ? severityColors.high : severityColors.medium };
13451
+ }
13433
13452
  function header(ui, state, theme, demo) {
13434
13453
  const badge = connectionBadge(state, demo);
13435
13454
  const uptime = state.daemon ? formatUptime(state.daemon.uptimeSeconds) : "\u2014";
@@ -13439,6 +13458,8 @@ function header(ui, state, theme, demo) {
13439
13458
  row.text(`${badge.glyph} ${badge.label}`, { fg: badge.color, bold: true, size: 12 });
13440
13459
  row.text(state.connectionLabel, { fg: theme.muted, size: "fill" });
13441
13460
  if (state.paused) row.text("\u23F8 PAUSED", { fg: severityColors.medium, bold: true, size: 10 });
13461
+ const wd = watchdogBadge(state);
13462
+ if (wd) row.text(wd.label, { fg: wd.color, bold: true, size: wd.label.length + 1 });
13442
13463
  row.text(`uptime ${uptime}`, { fg: theme.muted, size: 16, align: "right" });
13443
13464
  });
13444
13465
  });
@@ -16319,8 +16340,8 @@ var source_default = chalk;
16319
16340
  // src/index.ts
16320
16341
  var import_readline = __toESM(require("readline"));
16321
16342
  var import_node_child_process15 = require("child_process");
16322
- var import_node_fs36 = require("fs");
16323
- var import_node_path24 = require("path");
16343
+ var import_node_fs39 = require("fs");
16344
+ var import_node_path27 = require("path");
16324
16345
  var import_node_os11 = require("os");
16325
16346
 
16326
16347
  // src/commands/monitor.ts
@@ -23125,6 +23146,7 @@ function loadConfig(configPath) {
23125
23146
  remediation: parsed.remediation,
23126
23147
  detection: parsed.detection,
23127
23148
  cloud: parsed.cloud,
23149
+ watchdog: parsed.watchdog,
23128
23150
  license: parsed.license
23129
23151
  };
23130
23152
  } catch {
@@ -23527,9 +23549,470 @@ async function runDemoMode() {
23527
23549
  });
23528
23550
  }
23529
23551
 
23552
+ // src/commands/watchdog.ts
23553
+ var import_node_fs9 = require("fs");
23554
+ var import_node_path7 = require("path");
23555
+ init_paths();
23556
+
23557
+ // src/core/watchdog.ts
23558
+ var import_node_fs8 = require("fs");
23559
+ var import_node_crypto2 = require("crypto");
23560
+ var import_node_path6 = require("path");
23561
+ var WATCHDOG_DIRNAME = "watchdog";
23562
+ var LOG_FILE = "attacks.jsonl";
23563
+ var ROTATED_FILE = "attacks.1.jsonl";
23564
+ var TRIAGE_FILE = "triage.json";
23565
+ var ROTATE_BYTES = 50 * 1024 * 1024;
23566
+ var SEEN_LIMIT = 5e3;
23567
+ var OUTCOME_ORDER = ["answered", "errored", "unknown", "redirected", "refused"];
23568
+ var TRIAGE_STATUSES = ["new", "hole", "fp", "fixed"];
23569
+ var SEVERITY_RANK = { info: 0, low: 1, medium: 2, high: 3, critical: 4 };
23570
+ function str(v) {
23571
+ return typeof v === "string" && v !== "" && v !== "-" ? v : void 0;
23572
+ }
23573
+ function isAttack(event) {
23574
+ if (event.module === "firewall-rules") return false;
23575
+ const d = event.details ?? {};
23576
+ if (d.heartbeat) return false;
23577
+ const crs = typeof d.crs_score === "number" ? d.crs_score : 0;
23578
+ if (crs > 0 || str(d.attack_type)) return true;
23579
+ if (event.category === "web" && typeof d.status === "number" && !str(d.rule_id)) return false;
23580
+ return SEVERITY_RANK[event.severity] >= SEVERITY_RANK.medium;
23581
+ }
23582
+ function outcomeFor(status) {
23583
+ if (typeof status !== "number" || !Number.isFinite(status)) return "unknown";
23584
+ if (status >= 500) return "errored";
23585
+ if (status >= 400) return "refused";
23586
+ if (status >= 300) return "redirected";
23587
+ if (status >= 100) return "answered";
23588
+ return "unknown";
23589
+ }
23590
+ function requestFromMessage(message) {
23591
+ const m = /\b(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|CONNECT|TRACE|PROPFIND)\s+(\S+)/.exec(message);
23592
+ return m ? { method: m[1], url: m[2] } : {};
23593
+ }
23594
+ function signatureOf(r) {
23595
+ if (r.path) {
23596
+ return ["web", r.host ?? "", r.method ?? "", r.path, r.attack_type ?? r.rule_id ?? ""].join("|");
23597
+ }
23598
+ if (r.rule_id) return ["rule", r.module, r.rule_id].join("|");
23599
+ 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, "#");
23600
+ return ["msg", r.module, shape].join("|");
23601
+ }
23602
+ function findingId(signature) {
23603
+ return (0, import_node_crypto2.createHash)("sha1").update(signature).digest("hex").slice(0, 10);
23604
+ }
23605
+ function toRecord(event) {
23606
+ const d = event.details ?? {};
23607
+ const fromMsg = requestFromMessage(event.message);
23608
+ const url = str(d.url) ?? fromMsg.url;
23609
+ const path = str(d.path) ?? (url ? url.split("?")[0] : void 0);
23610
+ const status = typeof d.status === "number" ? d.status : void 0;
23611
+ const base = {
23612
+ module: event.module,
23613
+ host: str(d.host),
23614
+ method: str(d.method) ?? fromMsg.method,
23615
+ path,
23616
+ attack_type: str(d.attack_type),
23617
+ rule_id: str(d.rule_id),
23618
+ message: event.message
23619
+ };
23620
+ const timestamp = event.timestamp instanceof Date ? event.timestamp : new Date(event.timestamp);
23621
+ const record = {
23622
+ v: 1,
23623
+ id: findingId(signatureOf(base)),
23624
+ at: (Number.isNaN(timestamp.getTime()) ? /* @__PURE__ */ new Date() : timestamp).toISOString(),
23625
+ category: event.category,
23626
+ severity: event.severity,
23627
+ ...base,
23628
+ ip: event.source_ip,
23629
+ url,
23630
+ status,
23631
+ outcome: outcomeFor(status),
23632
+ crs_score: typeof d.crs_score === "number" ? d.crs_score : void 0,
23633
+ ua: str(d.ua)
23634
+ };
23635
+ for (const k of Object.keys(record)) {
23636
+ if (record[k] === void 0) delete record[k];
23637
+ }
23638
+ return record;
23639
+ }
23640
+ function dedupeKey(r) {
23641
+ return `${r.at}|${r.ip ?? ""}|${r.message}`;
23642
+ }
23643
+ function isShared(dir) {
23644
+ try {
23645
+ return ((0, import_node_fs8.statSync)(dir).mode & 1024) !== 0;
23646
+ } catch {
23647
+ return false;
23648
+ }
23649
+ }
23650
+ var WatchdogLog = class {
23651
+ dir;
23652
+ file;
23653
+ buffer = [];
23654
+ seen = /* @__PURE__ */ new Set();
23655
+ shareGid;
23656
+ stats = { logged: 0, answered: 0, errored: 0 };
23657
+ constructor(dir, options = {}) {
23658
+ this.dir = dir;
23659
+ this.file = (0, import_node_path6.join)(dir, LOG_FILE);
23660
+ this.shareGid = options.shareGid;
23661
+ (0, import_node_fs8.mkdirSync)(dir, { recursive: true, mode: this.shareGid === void 0 ? 448 : 1528 });
23662
+ if (this.shareGid !== void 0) {
23663
+ (0, import_node_fs8.chownSync)(dir, process.getuid?.() ?? 0, this.shareGid);
23664
+ (0, import_node_fs8.chmodSync)(dir, 1528);
23665
+ }
23666
+ for (const r of readTail(this.file, 512 * 1024)) this.remember(dedupeKey(r));
23667
+ }
23668
+ remember(key) {
23669
+ this.seen.add(key);
23670
+ if (this.seen.size > SEEN_LIMIT) {
23671
+ const oldest = this.seen.values().next().value;
23672
+ if (oldest !== void 0) this.seen.delete(oldest);
23673
+ }
23674
+ }
23675
+ /** Logs the event if it is an attack not already logged. Returns the record when it was. */
23676
+ record(event) {
23677
+ if (!isAttack(event)) return null;
23678
+ const rec = toRecord(event);
23679
+ const key = dedupeKey(rec);
23680
+ if (this.seen.has(key)) return null;
23681
+ this.remember(key);
23682
+ this.buffer.push(JSON.stringify(rec));
23683
+ this.stats.logged++;
23684
+ if (rec.outcome === "answered") this.stats.answered++;
23685
+ if (rec.outcome === "errored") this.stats.errored++;
23686
+ return rec;
23687
+ }
23688
+ flush() {
23689
+ if (this.buffer.length === 0) return;
23690
+ const chunk = this.buffer.join("\n") + "\n";
23691
+ this.buffer = [];
23692
+ try {
23693
+ if ((0, import_node_fs8.statSync)(this.file).size > ROTATE_BYTES) {
23694
+ (0, import_node_fs8.renameSync)(this.file, (0, import_node_path6.join)(this.dir, ROTATED_FILE));
23695
+ }
23696
+ } catch {
23697
+ }
23698
+ (0, import_node_fs8.appendFileSync)(this.file, chunk, { mode: this.shareGid === void 0 ? 384 : 432 });
23699
+ if (this.shareGid !== void 0) {
23700
+ try {
23701
+ (0, import_node_fs8.chownSync)(this.file, process.getuid?.() ?? 0, this.shareGid);
23702
+ (0, import_node_fs8.chmodSync)(this.file, 432);
23703
+ } catch {
23704
+ }
23705
+ }
23706
+ }
23707
+ };
23708
+ function parseLines(text) {
23709
+ const out = [];
23710
+ for (const line of text.split("\n")) {
23711
+ if (!line) continue;
23712
+ try {
23713
+ const r = JSON.parse(line);
23714
+ if (r && r.v === 1 && typeof r.id === "string") out.push(r);
23715
+ } catch {
23716
+ }
23717
+ }
23718
+ return out;
23719
+ }
23720
+ function readTail(file, bytes) {
23721
+ let fd;
23722
+ try {
23723
+ fd = (0, import_node_fs8.openSync)(file, "r");
23724
+ } catch (err) {
23725
+ if (err.code === "ENOENT") return [];
23726
+ throw err;
23727
+ }
23728
+ try {
23729
+ const size = (0, import_node_fs8.fstatSync)(fd).size;
23730
+ const start = Math.max(0, size - bytes);
23731
+ const buf = Buffer.alloc(size - start);
23732
+ (0, import_node_fs8.readSync)(fd, buf, 0, buf.length, start);
23733
+ let text = buf.toString("utf8");
23734
+ if (start > 0) text = text.slice(text.indexOf("\n") + 1);
23735
+ return parseLines(text);
23736
+ } finally {
23737
+ (0, import_node_fs8.closeSync)(fd);
23738
+ }
23739
+ }
23740
+ function readAttacks(dir) {
23741
+ const out = [];
23742
+ for (const name of [ROTATED_FILE, LOG_FILE]) {
23743
+ const file = (0, import_node_path6.join)(dir, name);
23744
+ if ((0, import_node_fs8.existsSync)(file)) out.push(...parseLines((0, import_node_fs8.readFileSync)(file, "utf8")));
23745
+ }
23746
+ return out;
23747
+ }
23748
+ function readTriage(dir) {
23749
+ const file = (0, import_node_path6.join)(dir, TRIAGE_FILE);
23750
+ if (!(0, import_node_fs8.existsSync)(file)) return {};
23751
+ try {
23752
+ return JSON.parse((0, import_node_fs8.readFileSync)(file, "utf8"));
23753
+ } catch {
23754
+ return {};
23755
+ }
23756
+ }
23757
+ function writeTriage(dir, map) {
23758
+ (0, import_node_fs8.mkdirSync)(dir, { recursive: true });
23759
+ const file = (0, import_node_path6.join)(dir, TRIAGE_FILE);
23760
+ const mode = isShared(dir) ? 432 : 384;
23761
+ (0, import_node_fs8.writeFileSync)(`${file}.tmp`, JSON.stringify(map, null, 2) + "\n", { mode });
23762
+ try {
23763
+ (0, import_node_fs8.chmodSync)(`${file}.tmp`, mode);
23764
+ } catch {
23765
+ }
23766
+ (0, import_node_fs8.renameSync)(`${file}.tmp`, file);
23767
+ }
23768
+ function setTriage(dir, id, update, now = /* @__PURE__ */ new Date()) {
23769
+ const map = readTriage(dir);
23770
+ const prev = map[id];
23771
+ const entry = {
23772
+ status: update.status,
23773
+ note: update.note ?? prev?.note,
23774
+ pr: update.pr ?? prev?.pr,
23775
+ updated_at: now.toISOString()
23776
+ };
23777
+ if (!entry.note) delete entry.note;
23778
+ if (!entry.pr) delete entry.pr;
23779
+ map[id] = entry;
23780
+ writeTriage(dir, map);
23781
+ return entry;
23782
+ }
23783
+ var SOURCES_CAP = 20;
23784
+ var SAMPLES_CAP = 5;
23785
+ function groupFindings(records, triage = {}) {
23786
+ const byId = /* @__PURE__ */ new Map();
23787
+ for (const r of records) {
23788
+ let f = byId.get(r.id);
23789
+ if (!f) {
23790
+ f = {
23791
+ id: r.id,
23792
+ outcome: r.outcome,
23793
+ severity: r.severity,
23794
+ count: 0,
23795
+ first_seen: r.at,
23796
+ last_seen: r.at,
23797
+ host: r.host,
23798
+ method: r.method,
23799
+ path: r.path,
23800
+ attack_type: r.attack_type,
23801
+ rule_id: r.rule_id,
23802
+ module: r.module,
23803
+ title: r.message,
23804
+ sources: [],
23805
+ source_count: 0,
23806
+ statuses: {},
23807
+ samples: [],
23808
+ triage: triage[r.id] ?? { status: "new", updated_at: r.at },
23809
+ _ips: /* @__PURE__ */ new Set()
23810
+ };
23811
+ byId.set(r.id, f);
23812
+ }
23813
+ f.count++;
23814
+ if (r.at < f.first_seen) f.first_seen = r.at;
23815
+ if (r.at > f.last_seen) f.last_seen = r.at;
23816
+ if (OUTCOME_ORDER.indexOf(r.outcome) < OUTCOME_ORDER.indexOf(f.outcome)) f.outcome = r.outcome;
23817
+ if (SEVERITY_RANK[r.severity] > SEVERITY_RANK[f.severity]) f.severity = r.severity;
23818
+ if (r.status !== void 0) f.statuses[r.status] = (f.statuses[r.status] ?? 0) + 1;
23819
+ if (r.ip && !f._ips.has(r.ip)) {
23820
+ f._ips.add(r.ip);
23821
+ if (f.sources.length < SOURCES_CAP) f.sources.push(r.ip);
23822
+ }
23823
+ f.samples.push(r);
23824
+ }
23825
+ const findings = [];
23826
+ for (const f of byId.values()) {
23827
+ const { _ips, ...rest } = f;
23828
+ rest.source_count = _ips.size;
23829
+ 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);
23830
+ findings.push(rest);
23831
+ }
23832
+ const triaged = (f) => f.triage.status === "new" ? 0 : 1;
23833
+ 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));
23834
+ }
23835
+ function findFinding(findings, id) {
23836
+ const exact = findings.find((f) => f.id === id);
23837
+ if (exact) return exact;
23838
+ const matches2 = findings.filter((f) => f.id.startsWith(id));
23839
+ return matches2.length === 1 ? matches2[0] : null;
23840
+ }
23841
+ function shellQuote(s) {
23842
+ return `'${s.replace(/'/g, `'\\''`)}'`;
23843
+ }
23844
+ function reproCommand(r) {
23845
+ if (!r.host || !r.url) return null;
23846
+ const method = r.method && r.method !== "GET" ? ` -X ${r.method}` : "";
23847
+ return `curl -sk -o /dev/null -w '%{http_code}\\n'${method} ${shellQuote(`https://${r.host}${r.url}`)}`;
23848
+ }
23849
+ function findingBrief(f) {
23850
+ const lines = [];
23851
+ const where2 = f.host ? `${f.host} ${f.method ?? ""} ${f.path ?? ""}`.trim() : f.title;
23852
+ lines.push(`# Watchdog finding ${f.id}: ${f.attack_type ?? f.rule_id ?? f.module} on ${where2}`);
23853
+ lines.push("");
23854
+ lines.push(`- **Outcome:** ${f.outcome}${outcomeExplainer(f.outcome)}`);
23855
+ lines.push(`- **Severity:** ${f.severity} \xB7 **hits:** ${f.count} from ${f.source_count} source(s)`);
23856
+ lines.push(`- **Seen:** ${f.first_seen} \u2192 ${f.last_seen}`);
23857
+ const statuses = Object.entries(f.statuses).map(([s, n]) => `${s}\xD7${n}`).join(", ");
23858
+ if (statuses) lines.push(`- **Status codes:** ${statuses}`);
23859
+ if (f.host) lines.push(`- **Vhost:** ${f.host}`);
23860
+ if (f.path) lines.push(`- **Endpoint:** ${f.method ?? ""} ${f.path}`.replace(" ", " "));
23861
+ if (f.rule_id) lines.push(`- **Rule:** ${f.rule_id}`);
23862
+ lines.push(`- **Detected by:** ${f.module}`);
23863
+ lines.push(`- **Triage:** ${f.triage.status}${f.triage.note ? ` \u2014 ${f.triage.note}` : ""}${f.triage.pr ? ` (${f.triage.pr})` : ""}`);
23864
+ lines.push("");
23865
+ lines.push("## Sample requests");
23866
+ lines.push("");
23867
+ for (const s of f.samples) {
23868
+ lines.push(`- \`${s.at}\` ${s.ip ?? "?"} \u2192 ${s.status ?? "\u2014"} \`${(s.method ? `${s.method} ` : "") + (s.url ?? s.message)}\``);
23869
+ if (s.ua) lines.push(` - UA: \`${s.ua}\``);
23870
+ }
23871
+ const repro = f.samples.map(reproCommand).find(Boolean);
23872
+ if (repro) {
23873
+ lines.push("");
23874
+ lines.push("## Reproduce (against our own site only)");
23875
+ lines.push("");
23876
+ lines.push("```sh");
23877
+ lines.push(repro);
23878
+ lines.push("```");
23879
+ }
23880
+ lines.push("");
23881
+ lines.push("## Verify, then fix");
23882
+ lines.push("");
23883
+ lines.push("1. Find the repo that serves this vhost and the handler for the endpoint above.");
23884
+ 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.");
23885
+ lines.push(`3. Not a hole: \`threatcrush watchdog mark ${f.id} fp --note "<why>"\`.`);
23886
+ 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.");
23887
+ lines.push(`5. Record it: \`threatcrush watchdog mark ${f.id} fixed --pr <url>\`.`);
23888
+ return lines.join("\n") + "\n";
23889
+ }
23890
+ function outcomeExplainer(o) {
23891
+ switch (o) {
23892
+ case "answered":
23893
+ return " \u2014 the app served this request (2xx). Verify it did not do what the payload asked.";
23894
+ case "errored":
23895
+ return " \u2014 the app crashed on it (5xx). Input reached code that did not expect it.";
23896
+ case "redirected":
23897
+ return " \u2014 answered with a redirect (3xx); usually auth bouncing it.";
23898
+ case "refused":
23899
+ return " \u2014 refused (4xx). Probably not a hole; kept for the record.";
23900
+ default:
23901
+ return " \u2014 not an HTTP request (ssh, network, rule); check the detection itself.";
23902
+ }
23903
+ }
23904
+
23905
+ // src/commands/watchdog.ts
23906
+ function resolveWatchdogDir(dir) {
23907
+ if (dir) return dir;
23908
+ if (process.env.THREATCRUSH_WATCHDOG_DIR) return process.env.THREATCRUSH_WATCHDOG_DIR;
23909
+ const system = (0, import_node_path7.join)("/var/lib/threatcrush", WATCHDOG_DIRNAME);
23910
+ if ((0, import_node_fs9.existsSync)(system)) return system;
23911
+ return (0, import_node_path7.join)(PATHS.stateDir, WATCHDOG_DIRNAME);
23912
+ }
23913
+ function load(dir) {
23914
+ return groupFindings(readAttacks(dir), readTriage(dir));
23915
+ }
23916
+ var OUTCOME_COLOR = {
23917
+ answered: source_default.red.bold,
23918
+ errored: source_default.magenta.bold,
23919
+ unknown: source_default.yellow,
23920
+ redirected: source_default.cyan,
23921
+ refused: source_default.gray
23922
+ };
23923
+ var TRIAGE_COLOR = {
23924
+ new: source_default.white,
23925
+ hole: source_default.red.bold,
23926
+ fp: source_default.gray,
23927
+ fixed: source_default.green
23928
+ };
23929
+ function where(f) {
23930
+ if (f.path) return `${f.host ? `${f.host} ` : ""}${f.method ?? ""} ${f.path}`.trim();
23931
+ return f.title;
23932
+ }
23933
+ function watchdogListCommand(opts) {
23934
+ const dir = resolveWatchdogDir(opts.dir);
23935
+ let findings = load(dir);
23936
+ if (opts.status) findings = findings.filter((f) => f.triage.status === opts.status);
23937
+ if (opts.outcome) findings = findings.filter((f) => f.outcome === opts.outcome);
23938
+ if (!opts.all && !opts.status && !opts.outcome) {
23939
+ findings = findings.filter((f) => (f.triage.status === "new" || f.triage.status === "hole") && f.outcome !== "refused");
23940
+ }
23941
+ const limit = opts.limit ? Math.max(1, parseInt(opts.limit, 10) || 50) : 50;
23942
+ if (opts.json) {
23943
+ console.log(JSON.stringify(findings.slice(0, limit), null, 2));
23944
+ return;
23945
+ }
23946
+ if (findings.length === 0) {
23947
+ const empty = (0, import_node_fs9.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).`;
23948
+ console.log(source_default.dim(empty));
23949
+ return;
23950
+ }
23951
+ console.log(source_default.dim(`${dir} \xB7 ${findings.length} finding(s)
23952
+ `));
23953
+ for (const f of findings.slice(0, limit)) {
23954
+ const statuses = Object.keys(f.statuses).join(",") || "\u2014";
23955
+ console.log(
23956
+ `${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)}`
23957
+ );
23958
+ }
23959
+ if (findings.length > limit) console.log(source_default.dim(`
23960
+ \u2026 ${findings.length - limit} more (--limit)`));
23961
+ console.log(source_default.dim("\nthreatcrush watchdog show <id> \xB7 brief <id> \xB7 mark <id> hole|fp|fixed"));
23962
+ }
23963
+ function resolve(dir, id) {
23964
+ const found = findFinding(load(dir), id);
23965
+ if (!found) {
23966
+ console.error(source_default.red(`No single finding matches "${id}" in ${dir}.`));
23967
+ process.exit(1);
23968
+ }
23969
+ return found;
23970
+ }
23971
+ function watchdogShowCommand(id, opts) {
23972
+ const dir = resolveWatchdogDir(opts.dir);
23973
+ const f = resolve(dir, id);
23974
+ if (opts.json) {
23975
+ console.log(JSON.stringify(f, null, 2));
23976
+ return;
23977
+ }
23978
+ console.log(`${source_default.bold(f.id)} ${OUTCOME_COLOR[f.outcome](f.outcome)} ${TRIAGE_COLOR[f.triage.status](f.triage.status)}`);
23979
+ console.log(`${source_default.cyan(f.attack_type ?? f.rule_id ?? f.module)} ${where(f)}`);
23980
+ console.log(source_default.dim(`${f.count} hit(s) from ${f.source_count} source(s) \xB7 ${f.first_seen} \u2192 ${f.last_seen}`));
23981
+ const statuses = Object.entries(f.statuses).map(([s, n]) => `${s}\xD7${n}`).join(" ");
23982
+ if (statuses) console.log(source_default.dim(`status codes: ${statuses}`));
23983
+ if (f.triage.note) console.log(`note: ${f.triage.note}`);
23984
+ if (f.triage.pr) console.log(`pr: ${f.triage.pr}`);
23985
+ console.log("\nsamples:");
23986
+ for (const s of f.samples) {
23987
+ console.log(` ${source_default.dim(s.at)} ${s.ip ?? "?"} \u2192 ${s.status ?? "\u2014"} ${s.method ? `${s.method} ` : ""}${s.url ?? s.message}`);
23988
+ }
23989
+ console.log(`
23990
+ sources: ${f.sources.join(", ")}${f.source_count > f.sources.length ? ` (+${f.source_count - f.sources.length})` : ""}`);
23991
+ const repro = f.samples.map(reproCommand).find(Boolean);
23992
+ if (repro) console.log(`
23993
+ reproduce: ${repro}`);
23994
+ }
23995
+ function watchdogBriefCommand(id, opts) {
23996
+ const dir = resolveWatchdogDir(opts.dir);
23997
+ process.stdout.write(findingBrief(resolve(dir, id)));
23998
+ }
23999
+ function watchdogMarkCommand(id, status, opts) {
24000
+ if (!TRIAGE_STATUSES.includes(status)) {
24001
+ console.error(source_default.red(`Status must be one of: ${TRIAGE_STATUSES.join(", ")}`));
24002
+ process.exit(1);
24003
+ }
24004
+ const dir = resolveWatchdogDir(opts.dir);
24005
+ const f = resolve(dir, id);
24006
+ const entry = setTriage(dir, f.id, { status, note: opts.note, pr: opts.pr });
24007
+ console.log(`${source_default.bold(f.id)} \u2192 ${TRIAGE_COLOR[entry.status](entry.status)}${entry.pr ? ` (${entry.pr})` : ""}`);
24008
+ }
24009
+ function watchdogPathCommand(opts) {
24010
+ console.log(resolveWatchdogDir(opts.dir));
24011
+ }
24012
+
23530
24013
  // src/commands/scan.ts
23531
- var import_node_fs10 = require("fs");
23532
- var import_node_path9 = require("path");
24014
+ var import_node_fs12 = require("fs");
24015
+ var import_node_path11 = require("path");
23533
24016
 
23534
24017
  // ../../node_modules/.pnpm/ora@8.2.0/node_modules/ora/index.js
23535
24018
  var import_node_process7 = __toESM(require("process"), 1);
@@ -23857,7 +24340,7 @@ var {
23857
24340
  *
23858
24341
  * @internal
23859
24342
  */
23860
- load,
24343
+ load: load2,
23861
24344
  /**
23862
24345
  * Unload the listeners. Likely you never need to call this, unless
23863
24346
  * doing a rather deep integration with signal-exit functionality.
@@ -27158,7 +27641,7 @@ function isTestPath(relativePath) {
27158
27641
  function rustCodeLines(lines) {
27159
27642
  const out = [];
27160
27643
  let commentDepth = 0;
27161
- let str2 = null;
27644
+ let str3 = null;
27162
27645
  for (const line of lines) {
27163
27646
  let code = "";
27164
27647
  let i = 0;
@@ -27182,15 +27665,15 @@ function rustCodeLines(lines) {
27182
27665
  i += 1;
27183
27666
  continue;
27184
27667
  }
27185
- if (str2) {
27186
- if (str2.raw) {
27668
+ if (str3) {
27669
+ if (str3.raw) {
27187
27670
  if (c === '"') {
27188
27671
  let hashes = 0;
27189
27672
  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;
27673
+ if (hashes >= str3.hashes) {
27674
+ code += " ".repeat(1 + str3.hashes);
27675
+ i += 1 + str3.hashes;
27676
+ str3 = null;
27194
27677
  continue;
27195
27678
  }
27196
27679
  }
@@ -27204,7 +27687,7 @@ function rustCodeLines(lines) {
27204
27687
  continue;
27205
27688
  }
27206
27689
  if (c === '"') {
27207
- str2 = null;
27690
+ str3 = null;
27208
27691
  code += " ";
27209
27692
  i += 1;
27210
27693
  continue;
@@ -27226,14 +27709,14 @@ function rustCodeLines(lines) {
27226
27709
  if (i === 0 || !/[A-Za-z0-9_]/.test(line[i - 1])) {
27227
27710
  const raw = /^b?r(#*)"/.exec(line.slice(i));
27228
27711
  if (raw) {
27229
- str2 = { raw: true, hashes: raw[1].length };
27712
+ str3 = { raw: true, hashes: raw[1].length };
27230
27713
  code += " ".repeat(raw[0].length);
27231
27714
  i += raw[0].length;
27232
27715
  continue;
27233
27716
  }
27234
27717
  }
27235
27718
  if (c === '"') {
27236
- str2 = { raw: false, hashes: 0 };
27719
+ str3 = { raw: false, hashes: 0 };
27237
27720
  code += " ";
27238
27721
  i += 1;
27239
27722
  continue;
@@ -27443,8 +27926,8 @@ function meetsFailThreshold(findings, threshold) {
27443
27926
  }
27444
27927
 
27445
27928
  // ../../packages/scan/src/node/walk.ts
27446
- var import_node_fs8 = require("fs");
27447
- var import_node_path6 = require("path");
27929
+ var import_node_fs10 = require("fs");
27930
+ var import_node_path8 = require("path");
27448
27931
  function compileExcludes(patterns) {
27449
27932
  const matchers = patterns.map((p) => p.trim()).filter((p) => p.length > 0 && !p.startsWith("#")).map(compilePattern);
27450
27933
  if (matchers.length === 0) return () => false;
@@ -27515,7 +27998,7 @@ function matchPrefix(parts, segs) {
27515
27998
  }
27516
27999
  function readIgnoreFile(root) {
27517
28000
  try {
27518
- return (0, import_node_fs8.readFileSync)((0, import_node_path6.join)(root, ".threatcrushignore"), "utf-8").split("\n");
28001
+ return (0, import_node_fs10.readFileSync)((0, import_node_path8.join)(root, ".threatcrushignore"), "utf-8").split("\n");
27519
28002
  } catch {
27520
28003
  return [];
27521
28004
  }
@@ -27531,16 +28014,16 @@ function scanPath(targetPath, options = {}) {
27531
28014
  let excluded = 0;
27532
28015
  const rootIsDirectory = (() => {
27533
28016
  try {
27534
- return (0, import_node_fs8.statSync)(targetPath).isDirectory();
28017
+ return (0, import_node_fs10.statSync)(targetPath).isDirectory();
27535
28018
  } catch {
27536
28019
  return true;
27537
28020
  }
27538
28021
  })();
27539
- const walkRoot = rootIsDirectory ? targetPath : (0, import_node_path6.dirname)(targetPath);
28022
+ const walkRoot = rootIsDirectory ? targetPath : (0, import_node_path8.dirname)(targetPath);
27540
28023
  const isExcluded = compileExcludes([...options.exclude ?? [], ...readIgnoreFile(walkRoot)]);
27541
28024
  const scanFile = (fullPath, filename) => {
27542
28025
  const relativePath = toRelative(walkRoot, fullPath);
27543
- const extension = (0, import_node_path6.extname)(filename).toLowerCase();
28026
+ const extension = (0, import_node_path8.extname)(filename).toLowerCase();
27544
28027
  const isManifest = filename === "package.json" || filename === "requirements.txt";
27545
28028
  const scannable = SCAN_EXTENSIONS.has(extension) || filename.startsWith(".env");
27546
28029
  const mayDeclareInterpreter = !scannable && !isManifest && extension === "";
@@ -27552,26 +28035,26 @@ function scanPath(targetPath, options = {}) {
27552
28035
  let handle;
27553
28036
  let declared = null;
27554
28037
  try {
27555
- handle = (0, import_node_fs8.openSync)(fullPath, "r");
28038
+ handle = (0, import_node_fs10.openSync)(fullPath, "r");
27556
28039
  } catch {
27557
28040
  unreadable.push(relativePath);
27558
28041
  return;
27559
28042
  }
27560
28043
  try {
27561
- if ((0, import_node_fs8.fstatSync)(handle).size > maxFileBytes) return;
28044
+ if ((0, import_node_fs10.fstatSync)(handle).size > maxFileBytes) return;
27562
28045
  if (mayDeclareInterpreter) {
27563
28046
  const prefix = Buffer.alloc(128);
27564
- const read = (0, import_node_fs8.readSync)(handle, prefix, 0, prefix.length, 0);
28047
+ const read = (0, import_node_fs10.readSync)(handle, prefix, 0, prefix.length, 0);
27565
28048
  declared = languageOfShebang(prefix.subarray(0, read).toString("utf-8").split("\n", 1)[0] ?? "");
27566
28049
  if (!declared) return;
27567
28050
  }
27568
- text = (0, import_node_fs8.readFileSync)(handle, "utf-8");
28051
+ text = (0, import_node_fs10.readFileSync)(handle, "utf-8");
27569
28052
  } catch {
27570
28053
  unreadable.push(relativePath);
27571
28054
  return;
27572
28055
  } finally {
27573
28056
  try {
27574
- (0, import_node_fs8.closeSync)(handle);
28057
+ (0, import_node_fs10.closeSync)(handle);
27575
28058
  } catch {
27576
28059
  }
27577
28060
  }
@@ -27589,13 +28072,13 @@ function scanPath(targetPath, options = {}) {
27589
28072
  const walk = (currentPath) => {
27590
28073
  let entries;
27591
28074
  try {
27592
- entries = (0, import_node_fs8.readdirSync)(currentPath, { withFileTypes: true });
28075
+ entries = (0, import_node_fs10.readdirSync)(currentPath, { withFileTypes: true });
27593
28076
  } catch {
27594
28077
  unreadable.push(toRelative(walkRoot, currentPath));
27595
28078
  return;
27596
28079
  }
27597
28080
  for (const entry of entries) {
27598
- const fullPath = (0, import_node_path6.join)(currentPath, entry.name);
28081
+ const fullPath = (0, import_node_path8.join)(currentPath, entry.name);
27599
28082
  const relativePath = toRelative(walkRoot, fullPath);
27600
28083
  if (entry.isDirectory()) {
27601
28084
  if (SKIP_DIRS.has(entry.name)) continue;
@@ -27619,7 +28102,7 @@ function scanPath(targetPath, options = {}) {
27619
28102
  } else if (isExcluded(toRelative(walkRoot, targetPath))) {
27620
28103
  excluded += 1;
27621
28104
  } else {
27622
- scanFile(targetPath, (0, import_node_path6.basename)(targetPath));
28105
+ scanFile(targetPath, (0, import_node_path8.basename)(targetPath));
27623
28106
  }
27624
28107
  if (options.missingControls) findings.push(...controls.findings());
27625
28108
  const filtered = allowed ? findings.filter((f) => allowed.has(f.category)) : findings;
@@ -27651,22 +28134,22 @@ function recordSensitiveFile(filename, relativePath, sink, fileFindings) {
27651
28134
  }
27652
28135
  }
27653
28136
  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("/");
28137
+ const rel = (0, import_node_path8.relative)(base, target);
28138
+ return (rel === "" ? target : rel).split(import_node_path8.sep).join("/");
27656
28139
  }
27657
28140
 
27658
28141
  // ../../packages/scan/src/node/dependencies.ts
27659
- var import_node_fs9 = require("fs");
27660
- var import_node_path7 = require("path");
28142
+ var import_node_fs11 = require("fs");
28143
+ var import_node_path9 = require("path");
27661
28144
  var MAX_DEPS_PER_LOCKFILE = 50;
27662
28145
  async function scanDependencies(targetPath) {
27663
28146
  const findings = [];
27664
28147
  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;
28148
+ const lockPath = (0, import_node_path9.join)(targetPath, file);
28149
+ if (!(0, import_node_fs11.existsSync)(lockPath)) continue;
27667
28150
  let deps;
27668
28151
  try {
27669
- deps = dedupe(parse2((0, import_node_fs9.readFileSync)(lockPath, "utf-8")));
28152
+ deps = dedupe(parse2((0, import_node_fs11.readFileSync)(lockPath, "utf-8")));
27670
28153
  } catch {
27671
28154
  continue;
27672
28155
  }
@@ -27880,12 +28363,12 @@ async function queryOsv(name, version, ecosystem) {
27880
28363
  }
27881
28364
 
27882
28365
  // ../../packages/scan/src/node/sarif.ts
27883
- var import_node_crypto2 = require("crypto");
27884
- var import_node_path8 = require("path");
28366
+ var import_node_crypto3 = require("crypto");
28367
+ var import_node_path10 = require("path");
27885
28368
  var FINGERPRINT_KEY = "threatcrush/contentHash/v1";
27886
28369
  function fingerprintOf(finding) {
27887
28370
  const content = finding.excerpt.replace(/\s+/g, " ").trim();
27888
- return (0, import_node_crypto2.createHash)("sha256").update(`${finding.ruleId}
28371
+ return (0, import_node_crypto3.createHash)("sha256").update(`${finding.ruleId}
27889
28372
  ${finding.file}
27890
28373
  ${content}`).digest("hex").slice(0, 32);
27891
28374
  }
@@ -27919,11 +28402,11 @@ function securitySeverity(severity) {
27919
28402
  }
27920
28403
  }
27921
28404
  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);
28405
+ const absolute = (0, import_node_path10.isAbsolute)(filePath) ? filePath : (0, import_node_path10.resolve)(root, filePath);
28406
+ const relativePath = (0, import_node_path10.relative)(base, absolute);
27924
28407
  const escapedOut = relativePath.startsWith("..") || relativePath === "";
27925
28408
  const chosen = escapedOut ? absolute : relativePath;
27926
- const posix = chosen.split(import_node_path8.sep).join("/").replace(/^\.\//, "");
28409
+ const posix = chosen.split(import_node_path10.sep).join("/").replace(/^\.\//, "");
27927
28410
  if (!prefix || escapedOut) return posix;
27928
28411
  const trimmed = prefix.replace(/^\/+|\/+$/g, "");
27929
28412
  return trimmed ? `${trimmed}/${posix}` : posix;
@@ -28013,11 +28496,11 @@ ${finding.consequence}` : `**${finding.title}**`
28013
28496
  // src/commands/scan.ts
28014
28497
  function readVersion() {
28015
28498
  for (const candidate of [
28016
- (0, import_node_path9.join)(__dirname, "..", "package.json"),
28017
- (0, import_node_path9.join)(__dirname, "..", "..", "package.json")
28499
+ (0, import_node_path11.join)(__dirname, "..", "package.json"),
28500
+ (0, import_node_path11.join)(__dirname, "..", "..", "package.json")
28018
28501
  ]) {
28019
28502
  try {
28020
- return JSON.parse((0, import_node_fs10.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
28503
+ return JSON.parse((0, import_node_fs12.readFileSync)(candidate, "utf-8")).version ?? "0.0.0";
28021
28504
  } catch {
28022
28505
  }
28023
28506
  }
@@ -28084,7 +28567,7 @@ async function scanCommand(targetPath, options = {}) {
28084
28567
  const say = machineReadable ? (line) => process.stderr.write(`${line}
28085
28568
  `) : (line) => process.stdout.write(`${line}
28086
28569
  `);
28087
- if (!(0, import_node_fs10.existsSync)(targetPath)) {
28570
+ if (!(0, import_node_fs12.existsSync)(targetPath)) {
28088
28571
  say(source_default.red(`Scan target does not exist: ${targetPath}`));
28089
28572
  process.exitCode = 2;
28090
28573
  return failedResult(targetPath, `no such path: ${targetPath}`);
@@ -28180,7 +28663,7 @@ function emitMachineReadable(format, outcome, targetPath, options, say) {
28180
28663
  // and it fails silently. `--path-prefix` covers the remaining case:
28181
28664
  // a scan run from inside the subdirectory it is scanning.
28182
28665
  base: process.cwd(),
28183
- root: (0, import_node_path9.resolve)(outcome.root)
28666
+ root: (0, import_node_path11.resolve)(outcome.root)
28184
28667
  }) : {
28185
28668
  tool: "threatcrush",
28186
28669
  version: PKG_VERSION2,
@@ -28194,8 +28677,8 @@ function emitMachineReadable(format, outcome, targetPath, options, say) {
28194
28677
  const serialized = `${JSON.stringify(payload, null, 2)}
28195
28678
  `;
28196
28679
  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");
28680
+ (0, import_node_fs12.mkdirSync)((0, import_node_path11.dirname)((0, import_node_path11.resolve)(options.output)), { recursive: true });
28681
+ (0, import_node_fs12.writeFileSync)(options.output, serialized, "utf-8");
28199
28682
  say(
28200
28683
  source_default.gray(
28201
28684
  ` ${format.toUpperCase()} written to ${options.output} (${outcome.findings.length} finding(s))`
@@ -28247,30 +28730,30 @@ function printHuman(outcome) {
28247
28730
  }
28248
28731
 
28249
28732
  // src/commands/init.ts
28250
- var import_node_fs12 = require("fs");
28733
+ var import_node_fs14 = require("fs");
28251
28734
  var import_node_child_process = require("child_process");
28252
28735
 
28253
28736
  // src/core/cli-config.ts
28254
- var import_node_fs11 = require("fs");
28255
- var import_node_path10 = require("path");
28737
+ var import_node_fs13 = require("fs");
28738
+ var import_node_path12 = require("path");
28256
28739
  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");
28740
+ var CLI_CONFIG_DIR = (0, import_node_path12.join)((0, import_node_os4.homedir)(), ".threatcrush");
28741
+ var CLI_CONFIG_PATH = (0, import_node_path12.join)(CLI_CONFIG_DIR, "config.json");
28259
28742
  function apiUrl() {
28260
28743
  return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
28261
28744
  }
28262
28745
  function readCliConfig() {
28263
28746
  try {
28264
- return JSON.parse((0, import_node_fs11.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
28747
+ return JSON.parse((0, import_node_fs13.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
28265
28748
  } catch {
28266
28749
  return {};
28267
28750
  }
28268
28751
  }
28269
28752
  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");
28753
+ if (!(0, import_node_fs13.existsSync)(CLI_CONFIG_DIR)) (0, import_node_fs13.mkdirSync)(CLI_CONFIG_DIR, { recursive: true });
28754
+ (0, import_node_fs13.writeFileSync)(CLI_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
28272
28755
  try {
28273
- (0, import_node_fs11.chmodSync)(CLI_CONFIG_PATH, 384);
28756
+ (0, import_node_fs13.chmodSync)(CLI_CONFIG_PATH, 384);
28274
28757
  } catch {
28275
28758
  }
28276
28759
  }
@@ -28400,8 +28883,8 @@ function askPiped(question, mask) {
28400
28883
  if (reader.lines.length > 0) return Promise.resolve(settle(reader.lines.shift()));
28401
28884
  if (reader.ended) return Promise.resolve(settle(null));
28402
28885
  reader.rl.resume();
28403
- return new Promise((resolve5) => {
28404
- reader.waiting = (line) => resolve5(settle(line));
28886
+ return new Promise((resolve6) => {
28887
+ reader.waiting = (line) => resolve6(settle(line));
28405
28888
  });
28406
28889
  }
28407
28890
  function askTerminal(question, mask) {
@@ -28409,20 +28892,20 @@ function askTerminal(question, mask) {
28409
28892
  cb();
28410
28893
  } }) : process.stdout;
28411
28894
  const rl = import_node_readline2.default.createInterface({ input: process.stdin, output, terminal: true });
28412
- return new Promise((resolve5) => {
28895
+ return new Promise((resolve6) => {
28413
28896
  let settled = false;
28414
28897
  rl.on("close", () => {
28415
28898
  if (settled) return;
28416
28899
  settled = true;
28417
28900
  process.stdout.write("\n");
28418
- resolve5(null);
28901
+ resolve6(null);
28419
28902
  });
28420
28903
  if (mask) process.stdout.write(question);
28421
28904
  rl.question(mask ? "" : question, (answer) => {
28422
28905
  settled = true;
28423
28906
  rl.close();
28424
28907
  if (mask) process.stdout.write("\n");
28425
- resolve5(answer);
28908
+ resolve6(answer);
28426
28909
  });
28427
28910
  });
28428
28911
  }
@@ -28432,11 +28915,11 @@ function ask(question, opts = {}) {
28432
28915
  }
28433
28916
 
28434
28917
  // src/core/link-login.ts
28435
- var import_node_crypto3 = require("crypto");
28918
+ var import_node_crypto4 = require("crypto");
28436
28919
  var import_node_os5 = require("os");
28437
28920
  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");
28921
+ const verifier = (0, import_node_crypto4.randomBytes)(32).toString("base64url");
28922
+ const challenge = (0, import_node_crypto4.createHash)("sha256").update(verifier).digest("base64url");
28440
28923
  return { verifier, challenge };
28441
28924
  }
28442
28925
  async function startLinkLogin(pkce, deviceName = (0, import_node_os5.hostname)()) {
@@ -28456,7 +28939,7 @@ async function startLinkLogin(pkce, deviceName = (0, import_node_os5.hostname)()
28456
28939
  }
28457
28940
  return data;
28458
28941
  }
28459
- var sleep = (ms) => new Promise((resolve5) => setTimeout(resolve5, ms));
28942
+ var sleep = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
28460
28943
  async function waitForApproval(request, pkce, opts = {}) {
28461
28944
  const wait = opts.sleepMs ?? sleep;
28462
28945
  const now = opts.now ?? Date.now;
@@ -28740,7 +29223,7 @@ function binaryExists(name) {
28740
29223
  }
28741
29224
  }
28742
29225
  function findLogPath(paths) {
28743
- return paths.find((p) => (0, import_node_fs12.existsSync)(p));
29226
+ return paths.find((p) => (0, import_node_fs14.existsSync)(p));
28744
29227
  }
28745
29228
  async function promptYesNo(question, fallback2) {
28746
29229
  const hint = fallback2 ? "(Y/n)" : "(y/N)";
@@ -28884,11 +29367,11 @@ async function initCommand(opts = {}) {
28884
29367
  }
28885
29368
  } else {
28886
29369
  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 });
29370
+ (0, import_node_fs14.mkdirSync)(confDDir, { recursive: true });
29371
+ (0, import_node_fs14.mkdirSync)("/var/log/threatcrush", { recursive: true });
29372
+ (0, import_node_fs14.mkdirSync)("/var/lib/threatcrush", { recursive: true });
28890
29373
  const mainConfig = generateDefaultConfig(detected.map((d) => d.name));
28891
- (0, import_node_fs12.writeFileSync)(`${configDir}/threatcrushd.conf`, mainConfig);
29374
+ (0, import_node_fs14.writeFileSync)(`${configDir}/threatcrushd.conf`, mainConfig);
28892
29375
  for (const svc of detected) {
28893
29376
  const svcDef = SERVICES_TO_DETECT.find((s) => s.name === svc.name);
28894
29377
  if (!svcDef) continue;
@@ -28897,7 +29380,7 @@ async function initCommand(opts = {}) {
28897
29380
  ...svcDef.moduleConfig,
28898
29381
  log_path: svc.logPath || svcDef.logPaths[0]
28899
29382
  });
28900
- (0, import_node_fs12.writeFileSync)(`${confDDir}/${modName}.conf`, modConfig);
29383
+ (0, import_node_fs14.writeFileSync)(`${confDDir}/${modName}.conf`, modConfig);
28901
29384
  }
28902
29385
  spinner2.succeed("Configuration written successfully");
28903
29386
  console.log();
@@ -28915,8 +29398,8 @@ async function initCommand(opts = {}) {
28915
29398
  }
28916
29399
  function checkWriteAccess(dir) {
28917
29400
  try {
28918
- if (!(0, import_node_fs12.existsSync)(dir)) {
28919
- (0, import_node_fs12.mkdirSync)(dir, { recursive: true });
29401
+ if (!(0, import_node_fs14.existsSync)(dir)) {
29402
+ (0, import_node_fs14.mkdirSync)(dir, { recursive: true });
28920
29403
  }
28921
29404
  return true;
28922
29405
  } catch {
@@ -28934,8 +29417,8 @@ var BUILTIN_MODULES = [
28934
29417
  ];
28935
29418
 
28936
29419
  // src/core/module-loader.ts
28937
- var import_node_fs13 = require("fs");
28938
- var import_node_path11 = require("path");
29420
+ var import_node_fs15 = require("fs");
29421
+ var import_node_path13 = require("path");
28939
29422
  var import_toml2 = __toESM(require_toml());
28940
29423
  init_paths();
28941
29424
  function discoverModules(moduleDir, confDir) {
@@ -28943,22 +29426,22 @@ function discoverModules(moduleDir, confDir) {
28943
29426
  const configs = loadModuleConfigs(confDir || PATHS.confD);
28944
29427
  const searchPaths = [
28945
29428
  moduleDir || PATHS.moduleDir,
28946
- (0, import_node_path11.resolve)(process.cwd(), "modules")
29429
+ (0, import_node_path13.resolve)(process.cwd(), "modules")
28947
29430
  ];
28948
- const builtinDir = (0, import_node_path11.resolve)(__dirname || ".", "..", "modules");
28949
- if ((0, import_node_fs13.existsSync)(builtinDir)) {
29431
+ const builtinDir = (0, import_node_path13.resolve)(__dirname || ".", "..", "modules");
29432
+ if ((0, import_node_fs15.existsSync)(builtinDir)) {
28950
29433
  searchPaths.push(builtinDir);
28951
29434
  }
28952
29435
  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 });
29436
+ if (!(0, import_node_fs15.existsSync)(basePath)) continue;
29437
+ const entries = (0, import_node_fs15.readdirSync)(basePath, { withFileTypes: true });
28955
29438
  for (const entry of entries) {
28956
29439
  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;
29440
+ const modPath = (0, import_node_path13.join)(basePath, entry.name);
29441
+ const manifestPath = (0, import_node_path13.join)(modPath, "mod.toml");
29442
+ if (!(0, import_node_fs15.existsSync)(manifestPath)) continue;
28960
29443
  try {
28961
- const raw = (0, import_node_fs13.readFileSync)(manifestPath, "utf-8");
29444
+ const raw = (0, import_node_fs15.readFileSync)(manifestPath, "utf-8");
28962
29445
  const manifest = import_toml2.default.parse(raw);
28963
29446
  const config = configs.get(manifest.module.name) || { enabled: true };
28964
29447
  modules.push({
@@ -28984,21 +29467,21 @@ function discoverModules(moduleDir, confDir) {
28984
29467
  init_ipc_client();
28985
29468
 
28986
29469
  // src/daemon/pidfile.ts
28987
- var import_node_fs14 = require("fs");
29470
+ var import_node_fs16 = require("fs");
28988
29471
  init_paths();
28989
29472
  function writePidFile() {
28990
29473
  ensureRuntimeDirs();
28991
- (0, import_node_fs14.writeFileSync)(PATHS.pidFile, String(process.pid), "utf-8");
29474
+ (0, import_node_fs16.writeFileSync)(PATHS.pidFile, String(process.pid), "utf-8");
28992
29475
  }
28993
29476
  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();
29477
+ if (!(0, import_node_fs16.existsSync)(PATHS.pidFile)) return null;
29478
+ const raw = (0, import_node_fs16.readFileSync)(PATHS.pidFile, "utf-8").trim();
28996
29479
  const pid = parseInt(raw, 10);
28997
29480
  return Number.isFinite(pid) ? pid : null;
28998
29481
  }
28999
29482
  function removePidFile() {
29000
29483
  try {
29001
- if ((0, import_node_fs14.existsSync)(PATHS.pidFile)) (0, import_node_fs14.unlinkSync)(PATHS.pidFile);
29484
+ if ((0, import_node_fs16.existsSync)(PATHS.pidFile)) (0, import_node_fs16.unlinkSync)(PATHS.pidFile);
29002
29485
  } catch {
29003
29486
  }
29004
29487
  }
@@ -29010,7 +29493,7 @@ function procStatState(stat) {
29010
29493
  function isZombie(pid) {
29011
29494
  let stat;
29012
29495
  try {
29013
- stat = (0, import_node_fs14.readFileSync)(`/proc/${pid}/stat`, "utf-8");
29496
+ stat = (0, import_node_fs16.readFileSync)(`/proc/${pid}/stat`, "utf-8");
29014
29497
  } catch {
29015
29498
  return false;
29016
29499
  }
@@ -29136,24 +29619,24 @@ function formatUptime2(seconds) {
29136
29619
 
29137
29620
  // src/commands/modules.ts
29138
29621
  var import_node_child_process2 = require("child_process");
29139
- var import_node_fs16 = require("fs");
29140
- var import_node_path13 = require("path");
29622
+ var import_node_fs18 = require("fs");
29623
+ var import_node_path15 = require("path");
29141
29624
  var import_toml3 = __toESM(require_toml());
29142
29625
  init_paths();
29143
29626
 
29144
29627
  // 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");
29628
+ var import_node_crypto5 = require("crypto");
29629
+ var import_node_fs17 = require("fs");
29630
+ var import_node_path14 = require("path");
29148
29631
  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");
29632
+ var TRUST_FILE = (0, import_node_path14.join)(PATHS.configDir, "trusted-modules.json");
29633
+ var PUBLISHER_KEYS_FILE = (0, import_node_path14.join)(PATHS.configDir, "publisher-keys.json");
29151
29634
  var DIGEST_EXCLUDED_DIRS = /* @__PURE__ */ new Set([".git"]);
29152
29635
  function collectFiles(root, dir = root, out = []) {
29153
- for (const entry of (0, import_node_fs15.readdirSync)(dir, { withFileTypes: true }).sort(
29636
+ for (const entry of (0, import_node_fs17.readdirSync)(dir, { withFileTypes: true }).sort(
29154
29637
  (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0
29155
29638
  )) {
29156
- const full = (0, import_node_path12.join)(dir, entry.name);
29639
+ const full = (0, import_node_path14.join)(dir, entry.name);
29157
29640
  if (entry.isSymbolicLink()) {
29158
29641
  out.push({ path: full, isSymlink: true });
29159
29642
  } else if (entry.isDirectory()) {
@@ -29166,26 +29649,26 @@ function collectFiles(root, dir = root, out = []) {
29166
29649
  return out;
29167
29650
  }
29168
29651
  function computeModuleDigest(modulePath) {
29169
- const hash = (0, import_node_crypto4.createHash)("sha256");
29652
+ const hash = (0, import_node_crypto5.createHash)("sha256");
29170
29653
  for (const entry of collectFiles(modulePath)) {
29171
- const relPath = (0, import_node_path12.relative)(modulePath, entry.path).split(import_node_path12.sep).join("/");
29654
+ const relPath = (0, import_node_path14.relative)(modulePath, entry.path).split(import_node_path14.sep).join("/");
29172
29655
  hash.update(relPath);
29173
29656
  hash.update("\0");
29174
29657
  if (entry.isSymlink) {
29175
29658
  hash.update("symlink:");
29176
- hash.update((0, import_node_fs15.readlinkSync)(entry.path));
29659
+ hash.update((0, import_node_fs17.readlinkSync)(entry.path));
29177
29660
  } else {
29178
29661
  hash.update("file:");
29179
- hash.update((0, import_node_fs15.readFileSync)(entry.path));
29662
+ hash.update((0, import_node_fs17.readFileSync)(entry.path));
29180
29663
  }
29181
29664
  hash.update("\0");
29182
29665
  }
29183
29666
  return hash.digest("hex");
29184
29667
  }
29185
29668
  function readTrustFile() {
29186
- if (!(0, import_node_fs15.existsSync)(TRUST_FILE)) return { version: 1, modules: {} };
29669
+ if (!(0, import_node_fs17.existsSync)(TRUST_FILE)) return { version: 1, modules: {} };
29187
29670
  try {
29188
- const parsed = JSON.parse((0, import_node_fs15.readFileSync)(TRUST_FILE, "utf-8"));
29671
+ const parsed = JSON.parse((0, import_node_fs17.readFileSync)(TRUST_FILE, "utf-8"));
29189
29672
  if (parsed.version !== 1 || typeof parsed.modules !== "object" || !parsed.modules) {
29190
29673
  return { version: 1, modules: {} };
29191
29674
  }
@@ -29195,9 +29678,9 @@ function readTrustFile() {
29195
29678
  }
29196
29679
  }
29197
29680
  function writeTrustFile(file) {
29198
- (0, import_node_fs15.writeFileSync)(TRUST_FILE, JSON.stringify(file, null, 2) + "\n", { mode: 384 });
29681
+ (0, import_node_fs17.writeFileSync)(TRUST_FILE, JSON.stringify(file, null, 2) + "\n", { mode: 384 });
29199
29682
  try {
29200
- (0, import_node_fs15.chmodSync)(TRUST_FILE, 384);
29683
+ (0, import_node_fs17.chmodSync)(TRUST_FILE, 384);
29201
29684
  } catch {
29202
29685
  }
29203
29686
  }
@@ -29223,9 +29706,9 @@ function listTrustedModules() {
29223
29706
  return readTrustFile().modules;
29224
29707
  }
29225
29708
  function readPublisherKeys() {
29226
- if (!(0, import_node_fs15.existsSync)(PUBLISHER_KEYS_FILE)) return {};
29709
+ if (!(0, import_node_fs17.existsSync)(PUBLISHER_KEYS_FILE)) return {};
29227
29710
  try {
29228
- const parsed = JSON.parse((0, import_node_fs15.readFileSync)(PUBLISHER_KEYS_FILE, "utf-8"));
29711
+ const parsed = JSON.parse((0, import_node_fs17.readFileSync)(PUBLISHER_KEYS_FILE, "utf-8"));
29229
29712
  return parsed && typeof parsed === "object" ? parsed : {};
29230
29713
  } catch {
29231
29714
  return {};
@@ -29234,16 +29717,16 @@ function readPublisherKeys() {
29234
29717
  function verifyModuleSignature(modulePath, digest) {
29235
29718
  const keys = readPublisherKeys();
29236
29719
  const pinnedKeyIds = Object.keys(keys);
29237
- const sigPath = (0, import_node_path12.join)(modulePath, "mod.sig");
29720
+ const sigPath = (0, import_node_path14.join)(modulePath, "mod.sig");
29238
29721
  if (pinnedKeyIds.length === 0) {
29239
29722
  return { ok: true };
29240
29723
  }
29241
- if (!(0, import_node_fs15.existsSync)(sigPath)) {
29724
+ if (!(0, import_node_fs17.existsSync)(sigPath)) {
29242
29725
  return { ok: false, reason: "publisher keys are pinned but the module ships no mod.sig" };
29243
29726
  }
29244
29727
  let parsed;
29245
29728
  try {
29246
- parsed = JSON.parse((0, import_node_fs15.readFileSync)(sigPath, "utf-8"));
29729
+ parsed = JSON.parse((0, import_node_fs17.readFileSync)(sigPath, "utf-8"));
29247
29730
  } catch {
29248
29731
  return { ok: false, reason: "mod.sig is not valid JSON" };
29249
29732
  }
@@ -29255,7 +29738,7 @@ function verifyModuleSignature(modulePath, digest) {
29255
29738
  return { ok: false, reason: `mod.sig references unpinned key "${parsed.keyId}"` };
29256
29739
  }
29257
29740
  try {
29258
- const valid = (0, import_node_crypto4.verify)(
29741
+ const valid = (0, import_node_crypto5.verify)(
29259
29742
  null,
29260
29743
  Buffer.from(digest, "hex"),
29261
29744
  publicKey,
@@ -29304,7 +29787,7 @@ function safeModuleDirName(name, label = "module name") {
29304
29787
  return name;
29305
29788
  }
29306
29789
  function moduleDestination(dir, name, label) {
29307
- return (0, import_node_path13.join)(dir, safeModuleDirName(name, label));
29790
+ return (0, import_node_path15.join)(dir, safeModuleDirName(name, label));
29308
29791
  }
29309
29792
  function assertSafeTarballEntries(tarPath) {
29310
29793
  const listing = (0, import_node_child_process2.execFileSync)("tar", ["-tzf", tarPath], { encoding: "utf-8" });
@@ -29317,12 +29800,12 @@ function assertSafeTarballEntries(tarPath) {
29317
29800
  }
29318
29801
  }
29319
29802
  function validateManifest(modPath) {
29320
- const manifestPath = (0, import_node_path13.join)(modPath, "mod.toml");
29321
- if (!(0, import_node_fs16.existsSync)(manifestPath)) {
29803
+ const manifestPath = (0, import_node_path15.join)(modPath, "mod.toml");
29804
+ if (!(0, import_node_fs18.existsSync)(manifestPath)) {
29322
29805
  return { ok: false, error: `mod.toml not found at ${manifestPath}` };
29323
29806
  }
29324
29807
  try {
29325
- const raw = (0, import_node_fs16.readFileSync)(manifestPath, "utf-8");
29808
+ const raw = (0, import_node_fs18.readFileSync)(manifestPath, "utf-8");
29326
29809
  const parsed = import_toml3.default.parse(raw);
29327
29810
  const name = parsed.module?.name;
29328
29811
  const version = parsed.module?.version;
@@ -29384,8 +29867,8 @@ async function modulesInstallCommand(source) {
29384
29867
  console.log();
29385
29868
  const dir = modulesDir();
29386
29869
  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)) {
29870
+ const absPath = (0, import_node_path15.resolve)(source.startsWith("~") ? source.replace("~", process.env.HOME || "") : source);
29871
+ if (!(0, import_node_fs18.existsSync)(absPath)) {
29389
29872
  console.log(source_default.red(` \u2717 Path not found: ${absPath}
29390
29873
  `));
29391
29874
  return;
@@ -29404,7 +29887,7 @@ async function modulesInstallCommand(source) {
29404
29887
  `));
29405
29888
  return;
29406
29889
  }
29407
- if ((0, import_node_fs16.existsSync)(dest2)) {
29890
+ if ((0, import_node_fs18.existsSync)(dest2)) {
29408
29891
  console.log(source_default.yellow(` ! ${check.name} is already installed at ${dest2}`));
29409
29892
  console.log(source_default.dim(` Run ${source_default.white(`threatcrush modules remove ${check.name}`)} first.
29410
29893
  `));
@@ -29412,7 +29895,7 @@ async function modulesInstallCommand(source) {
29412
29895
  }
29413
29896
  const spinner2 = ora({ text: `Copying module files...`, color: "green" }).start();
29414
29897
  try {
29415
- (0, import_node_fs16.cpSync)(absPath, dest2, { recursive: true, dereference: true });
29898
+ (0, import_node_fs18.cpSync)(absPath, dest2, { recursive: true, dereference: true });
29416
29899
  spinner2.succeed(`Installed ${source_default.white(check.name)} v${check.version} \u2192 ${dest2}`);
29417
29900
  } catch (err) {
29418
29901
  spinner2.fail(`Copy failed: ${err.message}`);
@@ -29428,14 +29911,14 @@ async function modulesInstallCommand(source) {
29428
29911
  let name;
29429
29912
  let dest2;
29430
29913
  try {
29431
- name = safeModuleDirName((0, import_node_path13.basename)(gitUrl.replace(/\.git$/, "")), "repository name");
29914
+ name = safeModuleDirName((0, import_node_path15.basename)(gitUrl.replace(/\.git$/, "")), "repository name");
29432
29915
  dest2 = moduleDestination(dir, name);
29433
29916
  } catch (err) {
29434
29917
  console.log(source_default.red(` x ${err.message}
29435
29918
  `));
29436
29919
  return;
29437
29920
  }
29438
- if ((0, import_node_fs16.existsSync)(dest2)) {
29921
+ if ((0, import_node_fs18.existsSync)(dest2)) {
29439
29922
  console.log(source_default.yellow(` ! ${name} is already installed at ${dest2}`));
29440
29923
  console.log(source_default.dim(` Run ${source_default.white(`threatcrush modules remove ${name}`)} first.
29441
29924
  `));
@@ -29452,7 +29935,7 @@ async function modulesInstallCommand(source) {
29452
29935
  if (!check.ok) {
29453
29936
  spinner2.fail(check.error);
29454
29937
  try {
29455
- (0, import_node_fs16.rmSync)(dest2, { recursive: true, force: true });
29938
+ (0, import_node_fs18.rmSync)(dest2, { recursive: true, force: true });
29456
29939
  } catch {
29457
29940
  }
29458
29941
  return;
@@ -29499,7 +29982,7 @@ async function modulesInstallCommand(source) {
29499
29982
  `));
29500
29983
  return;
29501
29984
  }
29502
- if ((0, import_node_fs16.existsSync)(dest)) {
29985
+ if ((0, import_node_fs18.existsSync)(dest)) {
29503
29986
  console.log(source_default.yellow(` ! ${mod.slug} is already installed at ${dest}
29504
29987
  `));
29505
29988
  return;
@@ -29525,7 +30008,7 @@ async function modulesInstallCommand(source) {
29525
30008
  if (!check.ok) {
29526
30009
  cloneSpinner.fail(check.error);
29527
30010
  try {
29528
- (0, import_node_fs16.rmSync)(dest, { recursive: true, force: true });
30011
+ (0, import_node_fs18.rmSync)(dest, { recursive: true, force: true });
29529
30012
  } catch {
29530
30013
  }
29531
30014
  return;
@@ -29539,11 +30022,11 @@ async function modulesInstallCommand(source) {
29539
30022
  dlSpinner.fail(`HTTP ${res.status}`);
29540
30023
  return;
29541
30024
  }
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()));
30025
+ const tar = (0, import_node_path15.join)(dir, `${mod.slug}.tar.gz`);
30026
+ (0, import_node_fs18.writeFileSync)(tar, Buffer.from(await res.arrayBuffer()));
29544
30027
  assertSafeTarballEntries(tar);
29545
30028
  (0, import_node_child_process2.execFileSync)("tar", ["-xzf", tar, "-C", dir], { stdio: "pipe" });
29546
- (0, import_node_fs16.rmSync)(tar, { force: true });
30029
+ (0, import_node_fs18.rmSync)(tar, { force: true });
29547
30030
  const check = validateManifest(dest);
29548
30031
  if (!check.ok) {
29549
30032
  dlSpinner.fail(check.error);
@@ -29575,7 +30058,7 @@ async function modulesRemoveCommand(name) {
29575
30058
  `));
29576
30059
  return;
29577
30060
  }
29578
- if (!(0, import_node_fs16.existsSync)(target)) {
30061
+ if (!(0, import_node_fs18.existsSync)(target)) {
29579
30062
  console.log(source_default.yellow(` ! No module named "${name}" in ${dir}
29580
30063
  `));
29581
30064
  return;
@@ -29585,7 +30068,7 @@ async function modulesRemoveCommand(name) {
29585
30068
  console.log(source_default.yellow(` ! Directory name "${name}" does not match manifest name "${check.name}"`));
29586
30069
  }
29587
30070
  try {
29588
- (0, import_node_fs16.rmSync)(target, { recursive: true, force: true });
30071
+ (0, import_node_fs18.rmSync)(target, { recursive: true, force: true });
29589
30072
  untrustModule(name);
29590
30073
  console.log(source_default.green(` \u2713 Removed ${name} from ${dir}
29591
30074
  `));
@@ -29610,7 +30093,7 @@ async function modulesTrustCommand(name) {
29610
30093
  `));
29611
30094
  return;
29612
30095
  }
29613
- if (!(0, import_node_fs16.existsSync)(target)) {
30096
+ if (!(0, import_node_fs18.existsSync)(target)) {
29614
30097
  console.log(source_default.yellow(` ! No module named "${name}" in ${dir}
29615
30098
  `));
29616
30099
  return;
@@ -30045,7 +30528,7 @@ async function pentestCommand(targetUrl) {
30045
30528
  }
30046
30529
 
30047
30530
  // src/commands/ai-scan.ts
30048
- var import_node_fs17 = require("fs");
30531
+ var import_node_fs19 = require("fs");
30049
30532
 
30050
30533
  // src/aiscan/probes.ts
30051
30534
  function makeCanary() {
@@ -30322,7 +30805,7 @@ async function aiScanMoshCommand(file, args) {
30322
30805
  console.log();
30323
30806
  let source;
30324
30807
  try {
30325
- source = (0, import_node_fs17.readFileSync)(file, "utf-8");
30808
+ source = (0, import_node_fs19.readFileSync)(file, "utf-8");
30326
30809
  } catch (err) {
30327
30810
  logger.error(`Cannot read ${file}: ${err.message}`);
30328
30811
  process.exitCode = 1;
@@ -30343,21 +30826,21 @@ async function aiScanMoshCommand(file, args) {
30343
30826
 
30344
30827
  // src/commands/orgs.ts
30345
30828
  var import_node_os6 = require("os");
30346
- var import_node_fs18 = require("fs");
30347
- var import_node_path14 = require("path");
30829
+ var import_node_fs20 = require("fs");
30830
+ var import_node_path16 = require("path");
30348
30831
  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");
30832
+ var CONFIG_PATH = (0, import_node_path16.join)((0, import_node_os6.homedir)(), ".threatcrush", "config.json");
30350
30833
  function readConfig() {
30351
30834
  try {
30352
- return JSON.parse((0, import_node_fs18.readFileSync)(CONFIG_PATH, "utf-8"));
30835
+ return JSON.parse((0, import_node_fs20.readFileSync)(CONFIG_PATH, "utf-8"));
30353
30836
  } catch {
30354
30837
  return {};
30355
30838
  }
30356
30839
  }
30357
30840
  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));
30841
+ const dir = (0, import_node_path16.join)((0, import_node_os6.homedir)(), ".threatcrush");
30842
+ if (!(0, import_node_fs20.existsSync)(dir)) (0, import_node_fs20.mkdirSync)(dir, { recursive: true });
30843
+ (0, import_node_fs20.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2));
30361
30844
  }
30362
30845
  function getAuthHeaders() {
30363
30846
  const config = readConfig();
@@ -30558,9 +31041,9 @@ async function fetchOrgs() {
30558
31041
  }
30559
31042
  function askChoice(question) {
30560
31043
  const rl = import_node_readline3.default.createInterface({ input: process.stdin, output: process.stdout });
30561
- return new Promise((resolve5) => rl.question(question, (answer) => {
31044
+ return new Promise((resolve6) => rl.question(question, (answer) => {
30562
31045
  rl.close();
30563
- resolve5(answer.trim());
31046
+ resolve6(answer.trim());
30564
31047
  }));
30565
31048
  }
30566
31049
  async function chooseOrg(orgs, flag, ask2) {
@@ -30702,14 +31185,14 @@ function timeAgo(dateStr) {
30702
31185
 
30703
31186
  // src/commands/connect.ts
30704
31187
  var import_node_os8 = require("os");
30705
- var import_node_fs19 = require("fs");
30706
- var import_node_path15 = require("path");
31188
+ var import_node_fs21 = require("fs");
31189
+ var import_node_path17 = require("path");
30707
31190
  var import_node_child_process3 = require("child_process");
30708
31191
  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");
31192
+ var CONFIG_PATH2 = (0, import_node_path17.join)((0, import_node_os8.homedir)(), ".threatcrush", "config.json");
30710
31193
  function readConfig2() {
30711
31194
  try {
30712
- return JSON.parse((0, import_node_fs19.readFileSync)(CONFIG_PATH2, "utf-8"));
31195
+ return JSON.parse((0, import_node_fs21.readFileSync)(CONFIG_PATH2, "utf-8"));
30713
31196
  } catch {
30714
31197
  return {};
30715
31198
  }
@@ -30864,21 +31347,21 @@ async function sshConnect(options) {
30864
31347
 
30865
31348
  // src/commands/daemon.ts
30866
31349
  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");
31350
+ var import_node_fs33 = require("fs");
31351
+ var import_node_path24 = require("path");
31352
+ var import_node_fs34 = require("fs");
30870
31353
 
30871
31354
  // src/daemon/index.ts
30872
- var import_node_fs29 = require("fs");
31355
+ var import_node_fs32 = require("fs");
30873
31356
  var import_node_child_process10 = require("child_process");
30874
31357
  var import_node_os9 = require("os");
30875
- var import_node_path20 = require("path");
31358
+ var import_node_path23 = require("path");
30876
31359
  var import_node_util = require("util");
30877
31360
  init_paths();
30878
31361
 
30879
31362
  // src/daemon/ipc-server.ts
30880
31363
  var import_node_net2 = require("net");
30881
- var import_node_fs20 = require("fs");
31364
+ var import_node_fs22 = require("fs");
30882
31365
  init_paths();
30883
31366
  init_control_token();
30884
31367
 
@@ -30901,10 +31384,11 @@ bus.setMaxListeners(50);
30901
31384
  // src/daemon/ipc-server.ts
30902
31385
  init_backoff();
30903
31386
  var IpcServer = class {
30904
- constructor(version, moduleHost, remediation) {
31387
+ constructor(version, moduleHost, remediation, watchdog) {
30905
31388
  this.version = version;
30906
31389
  this.moduleHost = moduleHost;
30907
31390
  this.remediation = remediation;
31391
+ this.watchdog = watchdog;
30908
31392
  bus.on("event", (event) => {
30909
31393
  this.counters.events++;
30910
31394
  if (event.severity === "medium" || event.severity === "high" || event.severity === "critical") {
@@ -30922,6 +31406,7 @@ var IpcServer = class {
30922
31406
  version;
30923
31407
  moduleHost;
30924
31408
  remediation;
31409
+ watchdog;
30925
31410
  server = null;
30926
31411
  clients = /* @__PURE__ */ new Map();
30927
31412
  nextClientId = 1;
@@ -30930,13 +31415,13 @@ var IpcServer = class {
30930
31415
  controlToken = "";
30931
31416
  async start() {
30932
31417
  this.controlToken = issueControlToken();
30933
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) {
31418
+ if ((0, import_node_fs22.existsSync)(PATHS.socket)) {
30934
31419
  try {
30935
- (0, import_node_fs20.unlinkSync)(PATHS.socket);
31420
+ (0, import_node_fs22.unlinkSync)(PATHS.socket);
30936
31421
  } catch {
30937
31422
  }
30938
31423
  }
30939
- return new Promise((resolve5, reject) => {
31424
+ return new Promise((resolve6, reject) => {
30940
31425
  this.server = (0, import_node_net2.createServer)((sock) => this.handleClient(sock));
30941
31426
  this.server.on("error", reject);
30942
31427
  this.server.listen(PATHS.socket, () => {
@@ -30953,7 +31438,7 @@ var IpcServer = class {
30953
31438
  } catch {
30954
31439
  }
30955
31440
  }
30956
- resolve5();
31441
+ resolve6();
30957
31442
  });
30958
31443
  });
30959
31444
  }
@@ -30965,20 +31450,20 @@ var IpcServer = class {
30965
31450
  }
30966
31451
  }
30967
31452
  this.clients.clear();
30968
- return new Promise((resolve5) => {
31453
+ return new Promise((resolve6) => {
30969
31454
  if (!this.server) {
30970
31455
  try {
30971
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) (0, import_node_fs20.unlinkSync)(PATHS.socket);
31456
+ if ((0, import_node_fs22.existsSync)(PATHS.socket)) (0, import_node_fs22.unlinkSync)(PATHS.socket);
30972
31457
  } catch {
30973
31458
  }
30974
- return resolve5();
31459
+ return resolve6();
30975
31460
  }
30976
31461
  this.server.close(() => {
30977
31462
  try {
30978
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) (0, import_node_fs20.unlinkSync)(PATHS.socket);
31463
+ if ((0, import_node_fs22.existsSync)(PATHS.socket)) (0, import_node_fs22.unlinkSync)(PATHS.socket);
30979
31464
  } catch {
30980
31465
  }
30981
- resolve5();
31466
+ resolve6();
30982
31467
  });
30983
31468
  });
30984
31469
  }
@@ -31046,7 +31531,8 @@ var IpcServer = class {
31046
31531
  },
31047
31532
  modules: this.moduleHost.summary(),
31048
31533
  counters: { ...this.counters },
31049
- stateDb: isStateDbAvailable()
31534
+ stateDb: isStateDbAvailable(),
31535
+ ...this.watchdog ? { watchdog: this.watchdog() } : {}
31050
31536
  };
31051
31537
  return this.send(client, { id: req.id, ok: true, result: status });
31052
31538
  }
@@ -31156,14 +31642,14 @@ var IpcServer = class {
31156
31642
  };
31157
31643
 
31158
31644
  // src/daemon/module-host.ts
31159
- var import_node_fs24 = require("fs");
31160
- var import_node_path16 = require("path");
31645
+ var import_node_fs26 = require("fs");
31646
+ var import_node_path18 = require("path");
31161
31647
  var import_node_url = require("url");
31162
31648
  var import_toml4 = __toESM(require_toml());
31163
31649
  init_paths();
31164
31650
 
31165
31651
  // src/daemon/watchers/log-watcher.ts
31166
- var import_node_fs21 = require("fs");
31652
+ var import_node_fs23 = require("fs");
31167
31653
  var import_node_readline4 = require("readline");
31168
31654
  var DEFAULT_SOURCES = [
31169
31655
  { path: "/var/log/auth.log", module: "ssh-guard", category: "auth" },
@@ -31184,9 +31670,9 @@ var LogWatcher = class {
31184
31670
  start() {
31185
31671
  const started = [];
31186
31672
  for (const src of this.sources) {
31187
- if (!(0, import_node_fs21.existsSync)(src.path)) continue;
31673
+ if (!(0, import_node_fs23.existsSync)(src.path)) continue;
31188
31674
  try {
31189
- (0, import_node_fs21.accessSync)(src.path, import_node_fs21.constants.R_OK);
31675
+ (0, import_node_fs23.accessSync)(src.path, import_node_fs23.constants.R_OK);
31190
31676
  } catch {
31191
31677
  continue;
31192
31678
  }
@@ -31214,7 +31700,7 @@ var LogWatcher = class {
31214
31700
  }
31215
31701
  tail(src) {
31216
31702
  try {
31217
- this.positions.set(src.path, (0, import_node_fs21.statSync)(src.path).size);
31703
+ this.positions.set(src.path, (0, import_node_fs23.statSync)(src.path).size);
31218
31704
  } catch {
31219
31705
  this.positions.set(src.path, 0);
31220
31706
  }
@@ -31225,7 +31711,7 @@ var LogWatcher = class {
31225
31711
  poll(src) {
31226
31712
  let stat;
31227
31713
  try {
31228
- stat = (0, import_node_fs21.statSync)(src.path);
31714
+ stat = (0, import_node_fs23.statSync)(src.path);
31229
31715
  } catch {
31230
31716
  return;
31231
31717
  }
@@ -31235,7 +31721,7 @@ var LogWatcher = class {
31235
31721
  return;
31236
31722
  }
31237
31723
  if (stat.size === prev) return;
31238
- const stream = (0, import_node_fs21.createReadStream)(src.path, { start: prev, encoding: "utf-8" });
31724
+ const stream = (0, import_node_fs23.createReadStream)(src.path, { start: prev, encoding: "utf-8" });
31239
31725
  stream.on("error", () => this.positions.set(src.path, stat.size));
31240
31726
  const rl = (0, import_node_readline4.createInterface)({ input: stream });
31241
31727
  rl.on("error", () => {
@@ -31271,6 +31757,9 @@ var LogWatcher = class {
31271
31757
  const reqPath = (entry.fields.path || "").split("?")[0];
31272
31758
  if (reqPath) details.path = reqPath;
31273
31759
  if (entry.fields.user_agent) details.ua = entry.fields.user_agent;
31760
+ if (Number.isFinite(status)) details.status = status;
31761
+ if (entry.fields.method) details.method = entry.fields.method;
31762
+ if (entry.fields.path) details.url = entry.fields.path.slice(0, 2048);
31274
31763
  if (crs.score > 0) {
31275
31764
  Object.assign(details, {
31276
31765
  attack_type: crs.attackType,
@@ -31496,7 +31985,7 @@ function realtimeToDate(rt) {
31496
31985
 
31497
31986
  // src/modules/network-monitor/index.ts
31498
31987
  var import_node_child_process5 = require("child_process");
31499
- var import_node_fs22 = require("fs");
31988
+ var import_node_fs24 = require("fs");
31500
31989
  var NetworkMonitor = class {
31501
31990
  constructor(bus2) {
31502
31991
  this.bus = bus2;
@@ -31560,7 +32049,7 @@ var NetworkMonitor = class {
31560
32049
  hasConntrackOrSs() {
31561
32050
  const ss = (0, import_node_child_process5.spawnSync)("ss", ["--version"], { stdio: "pipe" });
31562
32051
  if (ss.status === 0) return true;
31563
- return (0, import_node_fs22.existsSync)("/proc/net/tcp");
32052
+ return (0, import_node_fs24.existsSync)("/proc/net/tcp");
31564
32053
  }
31565
32054
  /**
31566
32055
  * The TCP ports this host actually listens on.
@@ -31747,7 +32236,7 @@ var NetworkMonitor = class {
31747
32236
  };
31748
32237
 
31749
32238
  // src/modules/dns-monitor/index.ts
31750
- var import_node_fs23 = require("fs");
32239
+ var import_node_fs25 = require("fs");
31751
32240
  var import_node_child_process6 = require("child_process");
31752
32241
  var import_node_readline5 = require("readline");
31753
32242
  var DNS_LOG_SOURCES = [
@@ -31829,9 +32318,9 @@ var DnsMonitor = class {
31829
32318
  }
31830
32319
  start() {
31831
32320
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
31832
- if (!(0, import_node_fs23.existsSync)(p)) return false;
32321
+ if (!(0, import_node_fs25.existsSync)(p)) return false;
31833
32322
  try {
31834
- (0, import_node_fs23.accessSync)(p, import_node_fs23.constants.R_OK);
32323
+ (0, import_node_fs25.accessSync)(p, import_node_fs25.constants.R_OK);
31835
32324
  return true;
31836
32325
  } catch {
31837
32326
  return false;
@@ -31907,7 +32396,7 @@ var DnsMonitor = class {
31907
32396
  }
31908
32397
  tailLog(path) {
31909
32398
  try {
31910
- this.positions.set(path, (0, import_node_fs23.statSync)(path).size);
32399
+ this.positions.set(path, (0, import_node_fs25.statSync)(path).size);
31911
32400
  } catch {
31912
32401
  this.positions.set(path, 0);
31913
32402
  }
@@ -31917,7 +32406,7 @@ var DnsMonitor = class {
31917
32406
  pollLog(path) {
31918
32407
  let stat;
31919
32408
  try {
31920
- stat = (0, import_node_fs23.statSync)(path);
32409
+ stat = (0, import_node_fs25.statSync)(path);
31921
32410
  } catch {
31922
32411
  return;
31923
32412
  }
@@ -31927,7 +32416,7 @@ var DnsMonitor = class {
31927
32416
  return;
31928
32417
  }
31929
32418
  if (stat.size === prev) return;
31930
- const stream = (0, import_node_fs23.createReadStream)(path, { start: prev, encoding: "utf-8" });
32419
+ const stream = (0, import_node_fs25.createReadStream)(path, { start: prev, encoding: "utf-8" });
31931
32420
  stream.on("error", () => this.positions.set(path, stat.size));
31932
32421
  const rl = (0, import_node_readline5.createInterface)({ input: stream });
31933
32422
  rl.on("line", (line) => this.parseDnsLine(line));
@@ -32037,14 +32526,14 @@ var DnsMonitor = class {
32037
32526
  );
32038
32527
  }
32039
32528
  }
32040
- shannonEntropy(str2) {
32529
+ shannonEntropy(str3) {
32041
32530
  const freq = /* @__PURE__ */ new Map();
32042
- for (const ch of str2) {
32531
+ for (const ch of str3) {
32043
32532
  freq.set(ch, (freq.get(ch) || 0) + 1);
32044
32533
  }
32045
32534
  let entropy = 0;
32046
32535
  for (const count of freq.values()) {
32047
- const p = count / str2.length;
32536
+ const p = count / str3.length;
32048
32537
  if (p > 0) entropy -= p * Math.log2(p);
32049
32538
  }
32050
32539
  return entropy;
@@ -32186,15 +32675,15 @@ var ModuleHost = class {
32186
32675
  }
32187
32676
  }
32188
32677
  async discoverAndStartInstalled() {
32189
- if (!(0, import_node_fs24.existsSync)(PATHS.moduleDir)) return;
32678
+ if (!(0, import_node_fs26.existsSync)(PATHS.moduleDir)) return;
32190
32679
  const configs = loadModuleConfigs(PATHS.confD);
32191
- const entries = (0, import_node_fs24.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
32680
+ const entries = (0, import_node_fs26.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
32192
32681
  for (const entry of entries) {
32193
32682
  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;
32683
+ const manifestPath = (0, import_node_path18.join)(PATHS.moduleDir, entry.name, "mod.toml");
32684
+ if (!(0, import_node_fs26.existsSync)(manifestPath)) continue;
32196
32685
  try {
32197
- const manifest = import_toml4.default.parse((0, import_node_fs24.readFileSync)(manifestPath, "utf-8"));
32686
+ const manifest = import_toml4.default.parse((0, import_node_fs26.readFileSync)(manifestPath, "utf-8"));
32198
32687
  const name = manifest.module?.name || entry.name;
32199
32688
  const defaults = manifest.module?.config?.defaults || {};
32200
32689
  const config = {
@@ -32208,7 +32697,7 @@ var ModuleHost = class {
32208
32697
  source: "installed",
32209
32698
  status: config.enabled === false ? "disabled" : "loaded",
32210
32699
  events: 0,
32211
- path: (0, import_node_path16.join)(PATHS.moduleDir, entry.name),
32700
+ path: (0, import_node_path18.join)(PATHS.moduleDir, entry.name),
32212
32701
  config
32213
32702
  };
32214
32703
  this.modules.set(name, hosted);
@@ -32223,7 +32712,7 @@ var ModuleHost = class {
32223
32712
  status: "error",
32224
32713
  events: 0,
32225
32714
  detail: `manifest load failed: ${String(err.message || err)}`,
32226
- path: (0, import_node_path16.join)(PATHS.moduleDir, entry.name)
32715
+ path: (0, import_node_path18.join)(PATHS.moduleDir, entry.name)
32227
32716
  });
32228
32717
  }
32229
32718
  }
@@ -32262,17 +32751,17 @@ var ModuleHost = class {
32262
32751
  }
32263
32752
  }
32264
32753
  installedEntrypoint(modulePath) {
32265
- const packageJson = (0, import_node_path16.join)(modulePath, "package.json");
32754
+ const packageJson = (0, import_node_path18.join)(modulePath, "package.json");
32266
32755
  const candidates = [];
32267
- if ((0, import_node_fs24.existsSync)(packageJson)) {
32756
+ if ((0, import_node_fs26.existsSync)(packageJson)) {
32268
32757
  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));
32758
+ const pkg = JSON.parse((0, import_node_fs26.readFileSync)(packageJson, "utf-8"));
32759
+ if (pkg.main) candidates.push((0, import_node_path18.join)(modulePath, pkg.main));
32271
32760
  } catch {
32272
32761
  }
32273
32762
  }
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;
32763
+ candidates.push((0, import_node_path18.join)(modulePath, "dist", "index.js"), (0, import_node_path18.join)(modulePath, "index.js"));
32764
+ return candidates.find((candidate) => (0, import_node_fs26.existsSync)(candidate)) || null;
32276
32765
  }
32277
32766
  isThreatCrushModule(value) {
32278
32767
  return Boolean(
@@ -32316,7 +32805,7 @@ var ModuleHost = class {
32316
32805
  // src/daemon/alerts/smtp.ts
32317
32806
  var transporter = null;
32318
32807
  var nodemailer = null;
32319
- var SEVERITY_RANK = {
32808
+ var SEVERITY_RANK2 = {
32320
32809
  info: 0,
32321
32810
  low: 1,
32322
32811
  medium: 2,
@@ -32343,7 +32832,7 @@ async function ensureTransporter(config) {
32343
32832
  }
32344
32833
  function meetsSeverity(event, min) {
32345
32834
  if (!min) return true;
32346
- return (SEVERITY_RANK[event.severity] ?? 0) >= (SEVERITY_RANK[min] ?? 0);
32835
+ return (SEVERITY_RANK2[event.severity] ?? 0) >= (SEVERITY_RANK2[min] ?? 0);
32347
32836
  }
32348
32837
  function renderBody(event) {
32349
32838
  const ts = event.timestamp.toISOString();
@@ -32377,7 +32866,7 @@ function smtpChannel(config) {
32377
32866
  }
32378
32867
 
32379
32868
  // src/daemon/alerts/discord.ts
32380
- var SEVERITY_RANK2 = {
32869
+ var SEVERITY_RANK3 = {
32381
32870
  info: 0,
32382
32871
  low: 1,
32383
32872
  medium: 2,
@@ -32399,8 +32888,8 @@ var SEVERITY_COLORS2 = {
32399
32888
  function discordChannel(config) {
32400
32889
  return async (event) => {
32401
32890
  if (config.min_severity) {
32402
- const eventRank = SEVERITY_RANK2[event.severity] ?? 0;
32403
- const minRank = SEVERITY_RANK2[config.min_severity] ?? 0;
32891
+ const eventRank = SEVERITY_RANK3[event.severity] ?? 0;
32892
+ const minRank = SEVERITY_RANK3[config.min_severity] ?? 0;
32404
32893
  if (eventRank < minRank) return;
32405
32894
  }
32406
32895
  const embed = {
@@ -32423,7 +32912,7 @@ function discordChannel(config) {
32423
32912
  }
32424
32913
 
32425
32914
  // src/daemon/alerts/pagerduty.ts
32426
- var SEVERITY_RANK3 = {
32915
+ var SEVERITY_RANK4 = {
32427
32916
  info: 0,
32428
32917
  low: 1,
32429
32918
  medium: 2,
@@ -32440,8 +32929,8 @@ var PD_SEVERITY = {
32440
32929
  function pagerdutyChannel(config) {
32441
32930
  return async (event) => {
32442
32931
  if (config.min_severity) {
32443
- const eventRank = SEVERITY_RANK3[event.severity] ?? 0;
32444
- const minRank = SEVERITY_RANK3[config.min_severity] ?? 0;
32932
+ const eventRank = SEVERITY_RANK4[event.severity] ?? 0;
32933
+ const minRank = SEVERITY_RANK4[config.min_severity] ?? 0;
32445
32934
  if (eventRank < minRank) return;
32446
32935
  }
32447
32936
  const payload = {
@@ -32676,7 +33165,7 @@ var RunsWorker = class {
32676
33165
  };
32677
33166
 
32678
33167
  // src/core/cloud-events.ts
32679
- var import_node_crypto5 = require("crypto");
33168
+ var import_node_crypto6 = require("crypto");
32680
33169
  var import_node_net3 = require("net");
32681
33170
  function currentLink() {
32682
33171
  if (!hasSession()) return null;
@@ -32684,7 +33173,7 @@ function currentLink() {
32684
33173
  if (!cfg.server_id || !cfg.server_org_id) return null;
32685
33174
  return { serverId: cfg.server_id, orgId: cfg.server_org_id };
32686
33175
  }
32687
- var SEVERITY_RANK4 = {
33176
+ var SEVERITY_RANK5 = {
32688
33177
  info: 0,
32689
33178
  low: 1,
32690
33179
  medium: 2,
@@ -32721,7 +33210,7 @@ function trimMetadata(meta) {
32721
33210
  }
32722
33211
  return truncated ? { ...out, _truncated: true } : out;
32723
33212
  }
32724
- function str(value) {
33213
+ function str2(value) {
32725
33214
  return typeof value === "string" && value ? value : void 0;
32726
33215
  }
32727
33216
  function detectionEvent(serverId, event) {
@@ -32732,10 +33221,10 @@ function detectionEvent(serverId, event) {
32732
33221
  server_id: serverId,
32733
33222
  severity: event.severity,
32734
33223
  title: title.slice(0, MAX_TITLE_CHARS) || event.module,
32735
- rule_id: str(rule_id) ?? event.module,
32736
- description: str(description),
33224
+ rule_id: str2(rule_id) ?? event.module,
33225
+ description: str2(description),
32737
33226
  source_ip: event.source_ip && (0, import_node_net3.isIP)(event.source_ip) ? event.source_ip : void 0,
32738
- username: str(username) ?? str(user),
33227
+ username: str2(username) ?? str2(user),
32739
33228
  raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
32740
33229
  detected_at: event.timestamp.toISOString()
32741
33230
  };
@@ -32749,13 +33238,13 @@ function remediationEvent(serverId, event) {
32749
33238
  return {
32750
33239
  type: "remediation",
32751
33240
  server_id: serverId,
32752
- event_id: (0, import_node_crypto5.randomUUID)(),
33241
+ event_id: (0, import_node_crypto6.randomUUID)(),
32753
33242
  action_type: d.action,
32754
33243
  target_value: event.source_ip,
32755
33244
  status: d.failed === true ? "failed" : "executed",
32756
- rule_id: str(d.rule_id),
32757
- reason: str(d.reason),
32758
- error: str(d.error),
33245
+ rule_id: str2(d.rule_id),
33246
+ reason: str2(d.reason),
33247
+ error: str2(d.error),
32759
33248
  dry_run: d.dry_run === true,
32760
33249
  executed_at: at.toISOString(),
32761
33250
  expires_at: d.action === "block" && ttl !== null && d.failed !== true ? new Date(at.getTime() + ttl * 1e3).toISOString() : null
@@ -32775,16 +33264,16 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
32775
33264
  }
32776
33265
 
32777
33266
  // src/daemon/workers/cloud-spool.ts
32778
- var import_node_fs25 = require("fs");
33267
+ var import_node_fs27 = require("fs");
32779
33268
  var import_promises = require("fs/promises");
32780
- var import_node_path17 = require("path");
33269
+ var import_node_path19 = require("path");
32781
33270
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
32782
33271
  var CloudSpool = class {
32783
33272
  constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
32784
33273
  this.path = path;
32785
33274
  this.limits = limits;
32786
33275
  try {
32787
- (0, import_node_fs25.mkdirSync)((0, import_node_path17.dirname)(path), { recursive: true });
33276
+ (0, import_node_fs27.mkdirSync)((0, import_node_path19.dirname)(path), { recursive: true });
32788
33277
  } catch {
32789
33278
  }
32790
33279
  this.load();
@@ -32853,7 +33342,7 @@ var CloudSpool = class {
32853
33342
  load() {
32854
33343
  let raw;
32855
33344
  try {
32856
- raw = (0, import_node_fs25.readFileSync)(this.path, "utf-8");
33345
+ raw = (0, import_node_fs27.readFileSync)(this.path, "utf-8");
32857
33346
  } catch {
32858
33347
  return;
32859
33348
  }
@@ -32979,7 +33468,7 @@ var CloudSync = class {
32979
33468
  let out = null;
32980
33469
  if (event.module === "firewall-rules") {
32981
33470
  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]) {
33471
+ } 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
33472
  out = detectionEvent(link.serverId, event);
32984
33473
  }
32985
33474
  if (!out) return;
@@ -33558,8 +34047,8 @@ var RuleEngine = class {
33558
34047
  };
33559
34048
 
33560
34049
  // src/daemon/rules/loader.ts
33561
- var import_node_fs26 = require("fs");
33562
- var import_node_path18 = require("path");
34050
+ var import_node_fs28 = require("fs");
34051
+ var import_node_path20 = require("path");
33563
34052
 
33564
34053
  // src/daemon/rules/default-rules.ts
33565
34054
  var AT_CRS_THRESHOLD = { field: "severity", operator: "regex", value: "^(high|critical)$" };
@@ -33960,11 +34449,11 @@ var RULES_DIR = "/etc/threatcrush/rules.d";
33960
34449
  function loadAllRules(customDir) {
33961
34450
  const rules = [...DEFAULT_RULES];
33962
34451
  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"));
34452
+ if ((0, import_node_fs28.existsSync)(dir)) {
34453
+ const files = (0, import_node_fs28.readdirSync)(dir).filter((f) => f.endsWith(".json"));
33965
34454
  for (const file of files) {
33966
34455
  try {
33967
- const raw = (0, import_node_fs26.readFileSync)((0, import_node_path18.join)(dir, file), "utf-8");
34456
+ const raw = (0, import_node_fs28.readFileSync)((0, import_node_path20.join)(dir, file), "utf-8");
33968
34457
  const parsed = JSON.parse(raw);
33969
34458
  const customRules = Array.isArray(parsed) ? parsed : [parsed];
33970
34459
  for (const rule of customRules) {
@@ -33996,8 +34485,8 @@ function loadAllRules(customDir) {
33996
34485
 
33997
34486
  // src/daemon/firewall/adapters.ts
33998
34487
  var import_node_child_process8 = require("child_process");
33999
- var import_node_fs27 = require("fs");
34000
- var import_node_path19 = require("path");
34488
+ var import_node_fs29 = require("fs");
34489
+ var import_node_path21 = require("path");
34001
34490
  var import_node_net7 = require("net");
34002
34491
  function assertValidFirewallIp(ip) {
34003
34492
  if ((0, import_node_net7.isIP)(ip) !== 4) {
@@ -34010,9 +34499,9 @@ function assertBannableIp(ip) {
34010
34499
  }
34011
34500
  }
34012
34501
  function writeIfAbsent(path, contents) {
34013
- (0, import_node_fs27.mkdirSync)((0, import_node_path19.dirname)(path), { recursive: true });
34502
+ (0, import_node_fs29.mkdirSync)((0, import_node_path21.dirname)(path), { recursive: true });
34014
34503
  try {
34015
- (0, import_node_fs27.writeFileSync)(path, contents, { flag: "wx" });
34504
+ (0, import_node_fs29.writeFileSync)(path, contents, { flag: "wx" });
34016
34505
  } catch (err) {
34017
34506
  if (err.code !== "EEXIST") throw err;
34018
34507
  }
@@ -34267,7 +34756,7 @@ function detectFirewallAdapter(backend = "auto") {
34267
34756
  }
34268
34757
 
34269
34758
  // src/daemon/firewall/remediation.ts
34270
- var import_node_fs28 = require("fs");
34759
+ var import_node_fs30 = require("fs");
34271
34760
  var import_node_net8 = require("net");
34272
34761
  init_paths();
34273
34762
  init_backoff();
@@ -34328,7 +34817,7 @@ var DEFAULT_CONFIG2 = {
34328
34817
  protect_current_ssh_client: true,
34329
34818
  spare_verified_crawlers: true
34330
34819
  };
34331
- var SEVERITY_RANK5 = {
34820
+ var SEVERITY_RANK6 = {
34332
34821
  info: 0,
34333
34822
  low: 1,
34334
34823
  medium: 2,
@@ -34392,8 +34881,8 @@ var RemediationManager = class {
34392
34881
  }
34393
34882
  async handleDetection(event) {
34394
34883
  if (!this.config.enabled) return;
34395
- const eventRank = SEVERITY_RANK5[event.severity] ?? 0;
34396
- const minRank = SEVERITY_RANK5[this.config.min_severity] ?? 3;
34884
+ const eventRank = SEVERITY_RANK6[event.severity] ?? 0;
34885
+ const minRank = SEVERITY_RANK6[this.config.min_severity] ?? 3;
34397
34886
  if (eventRank < minRank) return;
34398
34887
  if (isSuccessfulAuth(event.message)) return;
34399
34888
  if (event.details?.rule_id) {
@@ -34677,7 +35166,7 @@ var RemediationManager = class {
34677
35166
  }
34678
35167
  logLine(line) {
34679
35168
  try {
34680
- (0, import_node_fs28.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
35169
+ (0, import_node_fs30.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
34681
35170
  `);
34682
35171
  } catch {
34683
35172
  }
@@ -34714,6 +35203,63 @@ function remediationSettings(section) {
34714
35203
  // src/daemon/index.ts
34715
35204
  init_backoff();
34716
35205
 
35206
+ // src/daemon/watchdog-service.ts
35207
+ var import_node_fs31 = require("fs");
35208
+ var import_node_path22 = require("path");
35209
+ function defaultShareGid() {
35210
+ const isRoot4 = process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0;
35211
+ if (!isRoot4) return void 0;
35212
+ try {
35213
+ return (0, import_node_fs31.statSync)("/var/log/auth.log").gid;
35214
+ } catch {
35215
+ return void 0;
35216
+ }
35217
+ }
35218
+ function startWatchdog(opts) {
35219
+ const dir = opts.config?.dir ?? (0, import_node_path22.join)(opts.stateDir, WATCHDOG_DIRNAME);
35220
+ const base = { dir, logged: 0, answered: 0, errored: 0 };
35221
+ if (opts.config?.enabled === false) {
35222
+ opts.log("[watchdog] off ([watchdog] enabled = false)");
35223
+ return { status: () => ({ enabled: false, ...base }), stop: () => {
35224
+ } };
35225
+ }
35226
+ let log;
35227
+ try {
35228
+ log = new WatchdogLog(dir, { shareGid: opts.shareGid ?? defaultShareGid() });
35229
+ } catch (err) {
35230
+ const error2 = err.message;
35231
+ opts.log(`[watchdog] cannot open ${dir}: ${error2}`);
35232
+ return { status: () => ({ enabled: false, ...base, error: error2 }), stop: () => {
35233
+ } };
35234
+ }
35235
+ let error;
35236
+ const onEvent = (event) => {
35237
+ log.record(event);
35238
+ };
35239
+ const flush = () => {
35240
+ try {
35241
+ log.flush();
35242
+ error = void 0;
35243
+ } catch (err) {
35244
+ const message = err.message;
35245
+ if (message !== error) opts.log(`[watchdog] write failed: ${message}`);
35246
+ error = message;
35247
+ }
35248
+ };
35249
+ opts.bus.on("event", onEvent);
35250
+ const timer = setInterval(flush, opts.flushMs ?? 1e3);
35251
+ timer.unref?.();
35252
+ opts.log(`[watchdog] logging attacks to ${log.file}`);
35253
+ return {
35254
+ status: () => ({ enabled: true, dir, ...log.stats, ...error ? { error } : {} }),
35255
+ stop: () => {
35256
+ clearInterval(timer);
35257
+ opts.bus.off("event", onEvent);
35258
+ flush();
35259
+ }
35260
+ };
35261
+ }
35262
+
34717
35263
  // src/core/telemetry.ts
34718
35264
  var ready = false;
34719
35265
  var sentry = null;
@@ -34782,7 +35328,7 @@ function versionOfNode(path) {
34782
35328
  // src/daemon/index.ts
34783
35329
  function readVersion2() {
34784
35330
  try {
34785
- const pkg = JSON.parse((0, import_node_fs29.readFileSync)((0, import_node_path20.join)(__dirname, "..", "package.json"), "utf-8"));
35331
+ const pkg = JSON.parse((0, import_node_fs32.readFileSync)((0, import_node_path23.join)(__dirname, "..", "package.json"), "utf-8"));
34786
35332
  return pkg.version || "0.0.0";
34787
35333
  } catch {
34788
35334
  return "0.0.0";
@@ -34791,7 +35337,7 @@ function readVersion2() {
34791
35337
  async function runHardeningChecks() {
34792
35338
  const { stdout } = await (0, import_node_util.promisify)(import_node_child_process10.execFile)(
34793
35339
  process.execPath,
34794
- [(0, import_node_path20.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
35340
+ [(0, import_node_path23.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
34795
35341
  { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
34796
35342
  );
34797
35343
  const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
@@ -34799,7 +35345,7 @@ async function runHardeningChecks() {
34799
35345
  }
34800
35346
  function logLine(line) {
34801
35347
  try {
34802
- (0, import_node_fs29.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
35348
+ (0, import_node_fs32.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
34803
35349
  `);
34804
35350
  } catch {
34805
35351
  }
@@ -34841,7 +35387,7 @@ async function runDaemon() {
34841
35387
  } catch (err) {
34842
35388
  logLine(`[daemon] state db unavailable: ${err.message}`);
34843
35389
  }
34844
- const config = loadConfig((0, import_node_fs29.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
35390
+ const config = loadConfig((0, import_node_fs32.existsSync)(PATHS.configFile) ? PATHS.configFile : void 0);
34845
35391
  configureAttackDetection(config.detection);
34846
35392
  bus.on("event", (event) => {
34847
35393
  logLine(`[event] ${event.severity} ${event.module} ${event.message}`);
@@ -34908,7 +35454,7 @@ async function runDaemon() {
34908
35454
  version,
34909
35455
  hostname: (0, import_node_os9.hostname)(),
34910
35456
  minSeverity,
34911
- spoolPath: (0, import_node_path20.join)(PATHS.stateDir, "cloud-spool.jsonl"),
35457
+ spoolPath: (0, import_node_path23.join)(PATHS.stateDir, "cloud-spool.jsonl"),
34912
35458
  log: logLine,
34913
35459
  ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
34914
35460
  runHardening: runHardeningChecks
@@ -34921,7 +35467,8 @@ async function runDaemon() {
34921
35467
  const link = currentLink();
34922
35468
  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
35469
  }
34924
- const ipc = new IpcServer(version, moduleHost, remediation);
35470
+ const watchdog = startWatchdog({ bus, config: config.watchdog, stateDir: PATHS.stateDir, log: logLine });
35471
+ const ipc = new IpcServer(version, moduleHost, remediation, () => watchdog.status());
34925
35472
  await ipc.start();
34926
35473
  logLine(`[daemon] ipc listening on ${PATHS.socket}`);
34927
35474
  const shutdown = async (signal) => {
@@ -34950,6 +35497,10 @@ async function runDaemon() {
34950
35497
  await moduleHost.stop();
34951
35498
  } catch {
34952
35499
  }
35500
+ try {
35501
+ watchdog.stop();
35502
+ } catch {
35503
+ }
34953
35504
  try {
34954
35505
  await ipc.stop();
34955
35506
  } catch {
@@ -34985,7 +35536,7 @@ var SYSTEM_SOCKET = "/var/run/threatcrush/threatcrushd.sock";
34985
35536
  function isRoot2() {
34986
35537
  return typeof process.getuid === "function" && process.getuid() === 0;
34987
35538
  }
34988
- var DAEMON_ENTRY = (0, import_node_path21.join)(__dirname, "daemon.js");
35539
+ var DAEMON_ENTRY = (0, import_node_path24.join)(__dirname, "daemon.js");
34989
35540
  async function daemonForeground() {
34990
35541
  await runDaemon();
34991
35542
  }
@@ -35006,7 +35557,7 @@ async function daemonStart() {
35006
35557
  return;
35007
35558
  }
35008
35559
  ensureRuntimeDirs();
35009
- if (!(0, import_node_fs30.existsSync)(DAEMON_ENTRY)) {
35560
+ if (!(0, import_node_fs33.existsSync)(DAEMON_ENTRY)) {
35010
35561
  console.log(source_default.red(` Daemon entry not found at ${DAEMON_ENTRY}.`));
35011
35562
  console.log(source_default.dim(" Reinstall with `threatcrush update` or `pnpm run build` in the cli package."));
35012
35563
  return;
@@ -35014,8 +35565,8 @@ async function daemonStart() {
35014
35565
  let out;
35015
35566
  let err;
35016
35567
  try {
35017
- out = (0, import_node_fs31.openSync)(PATHS.logFile, "a");
35018
- err = (0, import_node_fs31.openSync)(PATHS.logFile, "a");
35568
+ out = (0, import_node_fs34.openSync)(PATHS.logFile, "a");
35569
+ err = (0, import_node_fs34.openSync)(PATHS.logFile, "a");
35019
35570
  } catch (e) {
35020
35571
  const code = e.code;
35021
35572
  console.log(source_default.red(` \u2717 Cannot write daemon log at ${PATHS.logFile} (${code ?? "error"}).`));
@@ -35103,12 +35654,12 @@ async function waitForExit(pid, timeoutMs) {
35103
35654
  }
35104
35655
  async function releaseStaleSocket() {
35105
35656
  const deadline = Date.now() + 2e3;
35106
- while ((0, import_node_fs30.existsSync)(PATHS.socket) && Date.now() < deadline) {
35657
+ while ((0, import_node_fs33.existsSync)(PATHS.socket) && Date.now() < deadline) {
35107
35658
  await new Promise((r) => setTimeout(r, 50));
35108
35659
  }
35109
- if ((0, import_node_fs30.existsSync)(PATHS.socket)) {
35660
+ if ((0, import_node_fs33.existsSync)(PATHS.socket)) {
35110
35661
  try {
35111
- (0, import_node_fs30.unlinkSync)(PATHS.socket);
35662
+ (0, import_node_fs33.unlinkSync)(PATHS.socket);
35112
35663
  } catch {
35113
35664
  }
35114
35665
  }
@@ -35116,26 +35667,26 @@ async function releaseStaleSocket() {
35116
35667
 
35117
35668
  // src/commands/service.ts
35118
35669
  var import_node_child_process12 = require("child_process");
35119
- var import_node_fs32 = require("fs");
35120
- var import_node_path22 = require("path");
35670
+ var import_node_fs35 = require("fs");
35671
+ var import_node_path25 = require("path");
35121
35672
  var import_node_os10 = require("os");
35122
35673
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
35123
35674
  var DAEMON_UNIT_NAME = "threatcrushd.service";
35124
35675
  function resolveTemplate() {
35125
- const templatePath = (0, import_node_path22.join)(__dirname, "systemd", "threatcrushd.service");
35126
- if (!(0, import_node_fs32.existsSync)(templatePath)) {
35676
+ const templatePath = (0, import_node_path25.join)(__dirname, "systemd", "threatcrushd.service");
35677
+ if (!(0, import_node_fs35.existsSync)(templatePath)) {
35127
35678
  throw new Error(`systemd unit template not found at ${templatePath}`);
35128
35679
  }
35129
- return (0, import_node_fs32.readFileSync)(templatePath, "utf-8");
35680
+ return (0, import_node_fs35.readFileSync)(templatePath, "utf-8");
35130
35681
  }
35131
35682
  function stableBinPath(binPath) {
35132
35683
  const stable = binPath.replace(/\/\.pnpm\/[^/]+\/node_modules\//, "/node_modules/");
35133
35684
  if (stable === binPath) return binPath;
35134
- return (0, import_node_fs32.existsSync)(stable) ? stable : binPath;
35685
+ return (0, import_node_fs35.existsSync)(stable) ? stable : binPath;
35135
35686
  }
35136
35687
  function resolveBinPath() {
35137
35688
  const arg = process.argv[1];
35138
- if (arg && (0, import_node_fs32.existsSync)(arg)) return stableBinPath(arg);
35689
+ if (arg && (0, import_node_fs35.existsSync)(arg)) return stableBinPath(arg);
35139
35690
  try {
35140
35691
  return (0, import_node_child_process12.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
35141
35692
  } catch {
@@ -35145,11 +35696,11 @@ function resolveBinPath() {
35145
35696
  function stableNodePath(execPath) {
35146
35697
  const stable = execPath.replace(/(\/installs\/node\/)[^/]+\//, "$1latest/");
35147
35698
  if (stable === execPath) return execPath;
35148
- return (0, import_node_fs32.existsSync)(stable) ? stable : execPath;
35699
+ return (0, import_node_fs35.existsSync)(stable) ? stable : execPath;
35149
35700
  }
35150
35701
  function looksLikeNodeScript(path) {
35151
35702
  try {
35152
- const head = (0, import_node_fs32.readFileSync)(path, "utf-8").slice(0, 120);
35703
+ const head = (0, import_node_fs35.readFileSync)(path, "utf-8").slice(0, 120);
35153
35704
  return /^#!.*\bnode\b/.test(head);
35154
35705
  } catch {
35155
35706
  return false;
@@ -35189,7 +35740,7 @@ function callerHome() {
35189
35740
  try {
35190
35741
  const line = (0, import_node_child_process12.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
35191
35742
  const home = line.split(":")[5];
35192
- return home && (0, import_node_fs32.existsSync)(home) ? home : null;
35743
+ return home && (0, import_node_fs35.existsSync)(home) ? home : null;
35193
35744
  } catch {
35194
35745
  return null;
35195
35746
  }
@@ -35197,13 +35748,13 @@ function callerHome() {
35197
35748
  function stopUserModeDaemon() {
35198
35749
  const home = callerHome();
35199
35750
  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;
35751
+ const runDir = (0, import_node_path25.join)(home, ".threatcrush", "run");
35752
+ const pidFile = (0, import_node_path25.join)(runDir, "threatcrushd.pid");
35753
+ const socket = (0, import_node_path25.join)(runDir, "threatcrushd.sock");
35754
+ if (!(0, import_node_fs35.existsSync)(pidFile) && !(0, import_node_fs35.existsSync)(socket)) return;
35204
35755
  let pid = null;
35205
35756
  try {
35206
- pid = Number.parseInt((0, import_node_fs32.readFileSync)(pidFile, "utf-8").trim(), 10);
35757
+ pid = Number.parseInt((0, import_node_fs35.readFileSync)(pidFile, "utf-8").trim(), 10);
35207
35758
  } catch {
35208
35759
  pid = null;
35209
35760
  }
@@ -35216,7 +35767,7 @@ function stopUserModeDaemon() {
35216
35767
  }
35217
35768
  for (const path of [socket, pidFile]) {
35218
35769
  try {
35219
- if ((0, import_node_fs32.existsSync)(path)) (0, import_node_fs32.rmSync)(path);
35770
+ if ((0, import_node_fs35.existsSync)(path)) (0, import_node_fs35.rmSync)(path);
35220
35771
  } catch {
35221
35772
  }
35222
35773
  }
@@ -35234,7 +35785,7 @@ async function installServiceCommand() {
35234
35785
  }
35235
35786
  const noSystemd = systemdUnavailableReason({
35236
35787
  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")
35788
+ booted: (0, import_node_fs35.existsSync)("/run/systemd/system")
35238
35789
  });
35239
35790
  if (noSystemd) {
35240
35791
  console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
@@ -35256,7 +35807,7 @@ async function installServiceCommand() {
35256
35807
  const isNodeScript = looksLikeNodeScript(binPath);
35257
35808
  let nodePath = stableNodePath(process.execPath);
35258
35809
  if (isNodeScript && nodeVersionDir(binPath)) {
35259
- binPath = (0, import_node_fs32.realpathSync)(binPath);
35810
+ binPath = (0, import_node_fs35.realpathSync)(binPath);
35260
35811
  nodePath = process.execPath;
35261
35812
  }
35262
35813
  if (isNodeScript) {
@@ -35269,9 +35820,9 @@ async function installServiceCommand() {
35269
35820
  }
35270
35821
  }
35271
35822
  const exec = execStartCommand(binPath, nodePath, isNodeScript);
35272
- const configDir = (0, import_node_path22.join)((0, import_node_os10.homedir)(), ".threatcrush");
35823
+ const configDir = (0, import_node_path25.join)((0, import_node_os10.homedir)(), ".threatcrush");
35273
35824
  const unit = renderUnit(resolveTemplate(), { exec, binPath, configDir });
35274
- (0, import_node_fs32.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
35825
+ (0, import_node_fs35.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
35275
35826
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
35276
35827
  console.log(source_default.dim(` ExecStart=${exec}`));
35277
35828
  const nodeDir = nodeVersionDir(nodePath);
@@ -35320,20 +35871,20 @@ function ensureSystemDirs(configDir) {
35320
35871
  ];
35321
35872
  let admGid = null;
35322
35873
  try {
35323
- admGid = (0, import_node_fs32.statSync)("/var/log/auth.log").gid;
35874
+ admGid = (0, import_node_fs35.statSync)("/var/log/auth.log").gid;
35324
35875
  } catch {
35325
35876
  }
35326
35877
  for (const { path, groupWritable, sticky } of dirs) {
35327
35878
  try {
35328
- (0, import_node_fs32.mkdirSync)(path, { recursive: true });
35879
+ (0, import_node_fs35.mkdirSync)(path, { recursive: true });
35329
35880
  } catch {
35330
35881
  }
35331
35882
  try {
35332
35883
  if (groupWritable && admGid !== null) {
35333
- (0, import_node_fs32.chmodSync)(path, sticky ? 1533 : 509);
35884
+ (0, import_node_fs35.chmodSync)(path, sticky ? 1533 : 509);
35334
35885
  (0, import_node_child_process12.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
35335
35886
  } else {
35336
- (0, import_node_fs32.chmodSync)(path, 493);
35887
+ (0, import_node_fs35.chmodSync)(path, 493);
35337
35888
  }
35338
35889
  } catch {
35339
35890
  }
@@ -35361,7 +35912,7 @@ async function uninstallServiceCommand() {
35361
35912
  } catch {
35362
35913
  }
35363
35914
  try {
35364
- if ((0, import_node_fs32.existsSync)(UNIT_PATH)) {
35915
+ if ((0, import_node_fs35.existsSync)(UNIT_PATH)) {
35365
35916
  (0, import_node_child_process12.execSync)(`rm -f ${UNIT_PATH}`);
35366
35917
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
35367
35918
  }
@@ -35375,7 +35926,7 @@ async function uninstallServiceCommand() {
35375
35926
  }
35376
35927
 
35377
35928
  // src/commands/save.ts
35378
- var import_node_fs33 = require("fs");
35929
+ var import_node_fs36 = require("fs");
35379
35930
  var import_toml5 = __toESM(require_toml());
35380
35931
  init_paths();
35381
35932
  var SECRET_KEY = /pass(word)?|secret|token|api_?key|private|webhook|dsn|url|routing_key|auth/i;
@@ -35413,9 +35964,9 @@ async function saveCommand(opts = {}) {
35413
35964
  }
35414
35965
  const path = opts.config ?? PATHS.configFile;
35415
35966
  let config = {};
35416
- if ((0, import_node_fs33.existsSync)(path)) {
35967
+ if ((0, import_node_fs36.existsSync)(path)) {
35417
35968
  try {
35418
- config = import_toml5.default.parse((0, import_node_fs33.readFileSync)(path, "utf-8"));
35969
+ config = import_toml5.default.parse((0, import_node_fs36.readFileSync)(path, "utf-8"));
35419
35970
  } catch (err) {
35420
35971
  console.log(source_default.red(` \u2717 ${path} is not valid TOML: ${err.message}
35421
35972
  `));
@@ -35527,16 +36078,16 @@ function welcomeCommand() {
35527
36078
  }
35528
36079
 
35529
36080
  // src/commands/properties.ts
35530
- var import_node_fs34 = require("fs");
35531
- var import_node_path23 = require("path");
36081
+ var import_node_fs37 = require("fs");
36082
+ var import_node_path26 = require("path");
35532
36083
  var import_node_readline6 = __toESM(require("readline"));
35533
36084
  var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
35534
36085
  var KINDS = ["url", "api", "domain", "ip", "repo"];
35535
36086
  function prompt(question) {
35536
36087
  const rl = import_node_readline6.default.createInterface({ input: process.stdin, output: process.stdout });
35537
- return new Promise((resolve5) => rl.question(question, (answer) => {
36088
+ return new Promise((resolve6) => rl.question(question, (answer) => {
35538
36089
  rl.close();
35539
- resolve5(answer.trim());
36090
+ resolve6(answer.trim());
35540
36091
  }));
35541
36092
  }
35542
36093
  async function requireAuth() {
@@ -35857,8 +36408,8 @@ async function propertiesRunsCommand(opts) {
35857
36408
  }
35858
36409
  }
35859
36410
  function parseImportFile(path) {
35860
- const ext = (0, import_node_path23.extname)(path).toLowerCase();
35861
- const raw = (0, import_node_fs34.readFileSync)(path, "utf-8");
36411
+ const ext = (0, import_node_path26.extname)(path).toLowerCase();
36412
+ const raw = (0, import_node_fs37.readFileSync)(path, "utf-8");
35862
36413
  if (ext === ".json") {
35863
36414
  const parsed = JSON.parse(raw);
35864
36415
  if (!Array.isArray(parsed)) throw new Error("JSON must be an array of objects");
@@ -36053,7 +36604,7 @@ async function rulesCommand(opts) {
36053
36604
  }
36054
36605
 
36055
36606
  // src/commands/harden.ts
36056
- var import_node_fs35 = require("fs");
36607
+ var import_node_fs38 = require("fs");
36057
36608
  var import_node_child_process13 = require("child_process");
36058
36609
  function tryExec(cmd) {
36059
36610
  try {
@@ -36064,7 +36615,7 @@ function tryExec(cmd) {
36064
36615
  }
36065
36616
  function tryRead(path) {
36066
36617
  try {
36067
- return (0, import_node_fs35.readFileSync)(path, "utf-8");
36618
+ return (0, import_node_fs38.readFileSync)(path, "utf-8");
36068
36619
  } catch {
36069
36620
  return null;
36070
36621
  }
@@ -36168,8 +36719,8 @@ function checkSshWeakConfig() {
36168
36719
  };
36169
36720
  }
36170
36721
  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");
36722
+ const unattended = (0, import_node_fs38.existsSync)("/etc/apt/apt.conf.d/20auto-upgrades") || (0, import_node_fs38.existsSync)("/etc/apt/apt.conf.d/50unattended-upgrades");
36723
+ const dnfAuto = (0, import_node_fs38.existsSync)("/etc/dnf/automatic.conf");
36173
36724
  if (unattended || dnfAuto) {
36174
36725
  return {
36175
36726
  key: "auto-updates",
@@ -36295,7 +36846,7 @@ function checkFail2ban() {
36295
36846
  explanation: "fail2ban is installed and running."
36296
36847
  };
36297
36848
  }
36298
- if ((0, import_node_fs35.existsSync)("/etc/fail2ban/fail2ban.conf")) {
36849
+ if ((0, import_node_fs38.existsSync)("/etc/fail2ban/fail2ban.conf")) {
36299
36850
  return {
36300
36851
  key: checkKey,
36301
36852
  status: "warn",
@@ -36743,7 +37294,7 @@ ${source_default.dim(" C R U S H")}
36743
37294
  var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
36744
37295
  var PKG_NAME = "@profullstack/threatcrush";
36745
37296
  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");
37297
+ var INSTALL_CONFIG_PATH = (0, import_node_path27.join)((0, import_node_os11.homedir)(), ".threatcrush", "install.json");
36747
37298
  function detectPackageManager() {
36748
37299
  try {
36749
37300
  const npmGlobal = (0, import_node_child_process15.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
@@ -36769,7 +37320,7 @@ function detectPackageManager() {
36769
37320
  }
36770
37321
  function readInstallConfig() {
36771
37322
  try {
36772
- return JSON.parse((0, import_node_fs36.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
37323
+ return JSON.parse((0, import_node_fs39.readFileSync)(INSTALL_CONFIG_PATH, "utf-8"));
36773
37324
  } catch {
36774
37325
  return {};
36775
37326
  }
@@ -36906,6 +37457,7 @@ program2.name("threatcrush").description(
36906
37457
  ${source_default.dim("Examples:")}
36907
37458
  ${source_default.green("$")} threatcrush monitor ${source_default.dim("# Real-time monitoring")}
36908
37459
  ${source_default.green("$")} threatcrush tui ${source_default.dim("# Interactive dashboard")}
37460
+ ${source_default.green("$")} threatcrush watchdog ${source_default.dim("# Triage logged attacks: hole or not?")}
36909
37461
  ${source_default.green("$")} threatcrush scan ./src ${source_default.dim("# Scan code for vulns")}
36910
37462
  ${source_default.green("$")} threatcrush pentest URL ${source_default.dim("# Quick web checks on a URL")}
36911
37463
  ${source_default.green("$")} threatcrush ai-scan URL ${source_default.dim("# Red-team your AI/LLM endpoint (OWASP LLM Top 10)")}
@@ -36936,6 +37488,24 @@ program2.command("monitor").description("Watch nginx, auth and syslog for attack
36936
37488
  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
37489
  await monitorCommand({ tui: true, demo: opts.demo });
36938
37490
  });
37491
+ 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) => {
37492
+ watchdogListCommand(opts);
37493
+ });
37494
+ 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) => {
37495
+ watchdogListCommand(cmd.optsWithGlobals());
37496
+ });
37497
+ watchdogCmd.command("show <id>").description("Every detail of one finding: samples, sources, a repro command").option("--json", "Output as JSON").action((id, _opts, cmd) => {
37498
+ watchdogShowCommand(id, cmd.optsWithGlobals());
37499
+ });
37500
+ 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) => {
37501
+ watchdogBriefCommand(id, cmd.optsWithGlobals());
37502
+ });
37503
+ 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) => {
37504
+ watchdogMarkCommand(id, status, cmd.optsWithGlobals());
37505
+ });
37506
+ watchdogCmd.command("path").description("Print the watchdog log directory").action((_opts, cmd) => {
37507
+ watchdogPathCommand(cmd.optsWithGlobals());
37508
+ });
36939
37509
  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
37510
  await initCommand({ yes: opts.yes, offline: opts.offline });
36941
37511
  });
@@ -37043,7 +37613,7 @@ program2.command("uninstall-service").description("Remove the threatcrushd syste
37043
37613
  program2.command("logs").description("Tail daemon logs").action(async () => {
37044
37614
  console.log(LOGO2);
37045
37615
  const logPath = PATHS.logFile;
37046
- if (!(0, import_node_fs36.existsSync)(logPath)) {
37616
+ if (!(0, import_node_fs39.existsSync)(logPath)) {
37047
37617
  console.log(source_default.yellow(` No log file found at ${logPath}`));
37048
37618
  console.log(source_default.dim(" Start the daemon first with `threatcrush start`\n"));
37049
37619
  return;
@@ -37111,10 +37681,10 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
37111
37681
  program2.command("remove").description("Uninstall ThreatCrush and the installed bundle").alias("uninstall").action(async () => {
37112
37682
  console.log(LOGO2);
37113
37683
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
37114
- const confirm = await new Promise((resolve5) => {
37684
+ const confirm = await new Promise((resolve6) => {
37115
37685
  rl.question(source_default.yellow(" Are you sure you want to uninstall ThreatCrush? (y/N): "), (answer) => {
37116
37686
  rl.close();
37117
- resolve5(answer.trim().toLowerCase());
37687
+ resolve6(answer.trim().toLowerCase());
37118
37688
  });
37119
37689
  });
37120
37690
  if (confirm !== "y" && confirm !== "yes") {
@@ -37216,19 +37786,19 @@ storeCmd.command("search <query>").description("Search for modules in the store"
37216
37786
  });
37217
37787
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
37218
37788
  console.log(LOGO2);
37219
- const configPath = (0, import_node_path24.join)((0, import_node_os11.homedir)(), ".threatcrush", "config.json");
37789
+ const configPath = (0, import_node_path27.join)((0, import_node_os11.homedir)(), ".threatcrush", "config.json");
37220
37790
  let email = "";
37221
37791
  try {
37222
- const config = JSON.parse((0, import_node_fs36.readFileSync)(configPath, "utf-8"));
37792
+ const config = JSON.parse((0, import_node_fs39.readFileSync)(configPath, "utf-8"));
37223
37793
  email = config.email || "";
37224
37794
  } catch {
37225
37795
  }
37226
37796
  if (!email) {
37227
37797
  const rl2 = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
37228
- email = await new Promise((resolve5) => {
37798
+ email = await new Promise((resolve6) => {
37229
37799
  rl2.question(source_default.green(" Enter your email: "), (answer) => {
37230
37800
  rl2.close();
37231
- resolve5(answer.trim());
37801
+ resolve6(answer.trim());
37232
37802
  });
37233
37803
  });
37234
37804
  if (!email || !email.includes("@")) {
@@ -37236,9 +37806,9 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
37236
37806
  return;
37237
37807
  }
37238
37808
  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));
37809
+ const dir = (0, import_node_path27.join)((0, import_node_os11.homedir)(), ".threatcrush");
37810
+ if (!(0, import_node_fs39.existsSync)(dir)) (0, import_node_fs39.mkdirSync)(dir, { recursive: true });
37811
+ (0, import_node_fs39.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
37242
37812
  console.log(source_default.dim(` Saved email to ${configPath}`));
37243
37813
  } catch {
37244
37814
  }
@@ -37282,10 +37852,10 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
37282
37852
  }
37283
37853
  console.log();
37284
37854
  const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
37285
- const confirm = await new Promise((resolve5) => {
37855
+ const confirm = await new Promise((resolve6) => {
37286
37856
  rl.question(source_default.yellow(" Publish this module? (y/N): "), (answer) => {
37287
37857
  rl.close();
37288
- resolve5(answer.trim().toLowerCase());
37858
+ resolve6(answer.trim().toLowerCase());
37289
37859
  });
37290
37860
  });
37291
37861
  if (confirm !== "y" && confirm !== "yes") {