@profullstack/threatcrush 0.13.9 → 0.13.10

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(str) {
602
- return stripColor(str).length;
601
+ displayWidth(str2) {
602
+ return stripColor(str2).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(str) {
611
- return str;
610
+ styleTitle(str2) {
611
+ return str2;
612
612
  }
613
- styleUsage(str) {
614
- return str.split(" ").map((word) => {
613
+ styleUsage(str2) {
614
+ return str2.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(str) {
623
- return this.styleDescriptionText(str);
622
+ styleCommandDescription(str2) {
623
+ return this.styleDescriptionText(str2);
624
624
  }
625
- styleOptionDescription(str) {
626
- return this.styleDescriptionText(str);
625
+ styleOptionDescription(str2) {
626
+ return this.styleDescriptionText(str2);
627
627
  }
628
- styleSubcommandDescription(str) {
629
- return this.styleDescriptionText(str);
628
+ styleSubcommandDescription(str2) {
629
+ return this.styleDescriptionText(str2);
630
630
  }
631
- styleArgumentDescription(str) {
632
- return this.styleDescriptionText(str);
631
+ styleArgumentDescription(str2) {
632
+ return this.styleDescriptionText(str2);
633
633
  }
634
- styleDescriptionText(str) {
635
- return str;
634
+ styleDescriptionText(str2) {
635
+ return str2;
636
636
  }
637
- styleOptionTerm(str) {
638
- return this.styleOptionText(str);
637
+ styleOptionTerm(str2) {
638
+ return this.styleOptionText(str2);
639
639
  }
640
- styleSubcommandTerm(str) {
641
- return str.split(" ").map((word) => {
640
+ styleSubcommandTerm(str2) {
641
+ return str2.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(str) {
649
- return this.styleArgumentText(str);
648
+ styleArgumentTerm(str2) {
649
+ return this.styleArgumentText(str2);
650
650
  }
651
- styleOptionText(str) {
652
- return str;
651
+ styleOptionText(str2) {
652
+ return str2;
653
653
  }
654
- styleArgumentText(str) {
655
- return str;
654
+ styleArgumentText(str2) {
655
+ return str2;
656
656
  }
657
- styleSubcommandText(str) {
658
- return str;
657
+ styleSubcommandText(str2) {
658
+ return str2;
659
659
  }
660
- styleCommandText(str) {
661
- return str;
660
+ styleCommandText(str2) {
661
+ return str2;
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(str) {
685
- return /\n[^\S\r\n]/.test(str);
684
+ preformatted(str2) {
685
+ return /\n[^\S\r\n]/.test(str2);
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(str, width) {
732
- if (width < this.minWidthToWrap) return str;
733
- const rawLines = str.split(/\r\n|\n/);
731
+ boxWrap(str2, width) {
732
+ if (width < this.minWidthToWrap) return str2;
733
+ const rawLines = str2.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(str) {
761
+ function stripColor(str2) {
762
762
  const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
763
- return str.replace(sgrPattern, "");
763
+ return str2.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(str) {
1024
- return str.split("-").reduce((str2, word) => {
1025
- return str2 + word[0].toUpperCase() + word.slice(1);
1023
+ function camelcase(str2) {
1024
+ return str2.split("-").reduce((str3, word) => {
1025
+ return str3 + 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: (str) => process10.stdout.write(str),
1209
- writeErr: (str) => process10.stderr.write(str),
1210
- outputError: (str, write) => write(str),
1208
+ writeOut: (str2) => process10.stdout.write(str2),
1209
+ writeErr: (str2) => process10.stderr.write(str2),
1210
+ outputError: (str2, write) => write(str2),
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: (str) => stripColor(str)
1215
+ stripColor: (str2) => stripColor(str2)
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(str, flags, description) {
2922
- if (str === void 0) return this._version;
2923
- this._version = str;
2921
+ version(str2, flags, description) {
2922
+ if (str2 === void 0) return this._version;
2923
+ this._version = str2;
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(`${str}
2930
+ this._outputConfiguration.writeOut(`${str2}
2931
2931
  `);
2932
- this._exit(0, "commander.version", str);
2932
+ this._exit(0, "commander.version", str2);
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(str, argsDescription) {
2944
- if (str === void 0 && argsDescription === void 0)
2943
+ description(str2, argsDescription) {
2944
+ if (str2 === void 0 && argsDescription === void 0)
2945
2945
  return this._description;
2946
- this._description = str;
2946
+ this._description = str2;
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(str) {
2959
- if (str === void 0) return this._summary;
2960
- this._summary = str;
2958
+ summary(str2) {
2959
+ if (str2 === void 0) return this._summary;
2960
+ this._summary = str2;
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(str) {
3009
- if (str === void 0) {
3008
+ usage(str2) {
3009
+ if (str2 === 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 = str;
3020
+ this._usage = str2;
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(str) {
3030
- if (str === void 0) return this._name;
3031
- this._name = str;
3029
+ name(str2) {
3030
+ if (str2 === void 0) return this._name;
3031
+ this._name = str2;
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 = (str) => this._outputConfiguration.writeErr(str);
3102
+ baseWrite = (str2) => this._outputConfiguration.writeErr(str2);
3103
3103
  hasColors = this._outputConfiguration.getErrHasColors();
3104
3104
  helpWidth = this._outputConfiguration.getErrHelpWidth();
3105
3105
  } else {
3106
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
3106
+ baseWrite = (str2) => this._outputConfiguration.writeOut(str2);
3107
3107
  hasColors = this._outputConfiguration.getOutHasColors();
3108
3108
  helpWidth = this._outputConfiguration.getOutHelpWidth();
3109
3109
  }
3110
- const write = (str) => {
3111
- if (!hasColors) str = this._outputConfiguration.stripColor(str);
3112
- return baseWrite(str);
3110
+ const write = (str2) => {
3111
+ if (!hasColors) str2 = this._outputConfiguration.stripColor(str2);
3112
+ return baseWrite(str2);
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(str) {
3374
- if (str.length === 0 || str.length == null) return;
3375
- this._buf = String(str);
3373
+ parse(str2) {
3374
+ if (str2.length === 0 || str2.length == null) return;
3375
+ this._buf = String(str2);
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(str) {
4923
- if (global.Buffer && global.Buffer.isBuffer(str)) {
4924
- str = str.toString("utf8");
4922
+ function parseString(str2) {
4923
+ if (global.Buffer && global.Buffer.isBuffer(str2)) {
4924
+ str2 = str2.toString("utf8");
4925
4925
  }
4926
4926
  const parser = new TOMLParser();
4927
4927
  try {
4928
- parser.parse(str);
4928
+ parser.parse(str2);
4929
4929
  return parser.finish();
4930
4930
  } catch (err) {
4931
- throw prettyError(err, str);
4931
+ throw prettyError(err, str2);
4932
4932
  }
4933
4933
  }
4934
4934
  }
@@ -4941,7 +4941,7 @@ 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(str, opts) {
4944
+ function parseAsync(str2, opts) {
4945
4945
  if (!opts) opts = {};
4946
4946
  const index = 0;
4947
4947
  const blocksize = opts.blocksize || 40960;
@@ -4950,18 +4950,18 @@ var require_parse_async = __commonJS({
4950
4950
  setImmediate(parseAsyncNext, index, blocksize, resolve5, reject);
4951
4951
  });
4952
4952
  function parseAsyncNext(index2, blocksize2, resolve5, reject) {
4953
- if (index2 >= str.length) {
4953
+ if (index2 >= str2.length) {
4954
4954
  try {
4955
4955
  return resolve5(parser.finish());
4956
4956
  } catch (err) {
4957
- return reject(prettyError(err, str));
4957
+ return reject(prettyError(err, str2));
4958
4958
  }
4959
4959
  }
4960
4960
  try {
4961
- parser.parse(str.slice(index2, index2 + blocksize2));
4961
+ parser.parse(str2.slice(index2, index2 + blocksize2));
4962
4962
  setImmediate(parseAsyncNext, index2 + blocksize2, blocksize2, resolve5, reject);
4963
4963
  } catch (err) {
4964
- reject(prettyError(err, str));
4964
+ reject(prettyError(err, str2));
4965
4965
  }
4966
4966
  }
4967
4967
  }
@@ -5167,22 +5167,22 @@ var require_stringify = __commonJS({
5167
5167
  return stringifyBasicString(keyStr);
5168
5168
  }
5169
5169
  }
5170
- function stringifyBasicString(str) {
5171
- return '"' + escapeString(str).replace(/"/g, '\\"') + '"';
5170
+ function stringifyBasicString(str2) {
5171
+ return '"' + escapeString(str2).replace(/"/g, '\\"') + '"';
5172
5172
  }
5173
- function stringifyLiteralString(str) {
5174
- return "'" + str + "'";
5173
+ function stringifyLiteralString(str2) {
5174
+ return "'" + str2 + "'";
5175
5175
  }
5176
- function numpad(num, str) {
5177
- while (str.length < num) str = "0" + str;
5178
- return str;
5176
+ function numpad(num, str2) {
5177
+ while (str2.length < num) str2 = "0" + str2;
5178
+ return str2;
5179
5179
  }
5180
- function escapeString(str) {
5181
- return str.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(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)));
5182
5182
  }
5183
- function stringifyMultilineString(str) {
5184
- let escaped = str.split(/\n/).map((str2) => {
5185
- return escapeString(str2).replace(/"(?="")/g, '\\"');
5183
+ function stringifyMultilineString(str2) {
5184
+ let escaped = str2.split(/\n/).map((str3) => {
5185
+ return escapeString(str3).replace(/"(?="")/g, '\\"');
5186
5186
  }).join("\n");
5187
5187
  if (escaped.slice(-1) === '"') escaped += "\\\n";
5188
5188
  return '"""\n' + escaped + '"""';
@@ -15911,10 +15911,10 @@ var source_default = chalk;
15911
15911
 
15912
15912
  // src/index.ts
15913
15913
  var import_readline = __toESM(require("readline"));
15914
- var import_node_child_process13 = require("child_process");
15914
+ var import_node_child_process14 = require("child_process");
15915
15915
  var import_node_fs34 = require("fs");
15916
15916
  var import_node_path24 = require("path");
15917
- var import_node_os8 = require("os");
15917
+ var import_node_os9 = require("os");
15918
15918
 
15919
15919
  // src/commands/monitor.ts
15920
15920
  var import_node_fs7 = require("fs");
@@ -22717,6 +22717,7 @@ function loadConfig(configPath) {
22717
22717
  modules: { ...DEFAULT_CONFIG.modules, ...parsed.modules },
22718
22718
  remediation: parsed.remediation,
22719
22719
  detection: parsed.detection,
22720
+ cloud: parsed.cloud,
22720
22721
  license: parsed.license
22721
22722
  };
22722
22723
  } catch {
@@ -22746,7 +22747,10 @@ function generateDefaultConfig(detectedServices) {
22746
22747
  const config = {
22747
22748
  daemon: DEFAULT_CONFIG.daemon,
22748
22749
  api: DEFAULT_CONFIG.api,
22749
- modules: DEFAULT_CONFIG.modules
22750
+ modules: DEFAULT_CONFIG.modules,
22751
+ // Written out so the opt-out is discoverable; these are also the defaults
22752
+ // when the section is absent.
22753
+ cloud: { enabled: true, min_severity: "medium" }
22750
22754
  };
22751
22755
  return import_toml.default.stringify(config);
22752
22756
  }
@@ -26747,7 +26751,7 @@ function isTestPath(relativePath) {
26747
26751
  function rustCodeLines(lines) {
26748
26752
  const out = [];
26749
26753
  let commentDepth = 0;
26750
- let str = null;
26754
+ let str2 = null;
26751
26755
  for (const line of lines) {
26752
26756
  let code = "";
26753
26757
  let i = 0;
@@ -26771,15 +26775,15 @@ function rustCodeLines(lines) {
26771
26775
  i += 1;
26772
26776
  continue;
26773
26777
  }
26774
- if (str) {
26775
- if (str.raw) {
26778
+ if (str2) {
26779
+ if (str2.raw) {
26776
26780
  if (c === '"') {
26777
26781
  let hashes = 0;
26778
26782
  while (line[i + 1 + hashes] === "#") hashes += 1;
26779
- if (hashes >= str.hashes) {
26780
- code += " ".repeat(1 + str.hashes);
26781
- i += 1 + str.hashes;
26782
- str = null;
26783
+ if (hashes >= str2.hashes) {
26784
+ code += " ".repeat(1 + str2.hashes);
26785
+ i += 1 + str2.hashes;
26786
+ str2 = null;
26783
26787
  continue;
26784
26788
  }
26785
26789
  }
@@ -26793,7 +26797,7 @@ function rustCodeLines(lines) {
26793
26797
  continue;
26794
26798
  }
26795
26799
  if (c === '"') {
26796
- str = null;
26800
+ str2 = null;
26797
26801
  code += " ";
26798
26802
  i += 1;
26799
26803
  continue;
@@ -26815,14 +26819,14 @@ function rustCodeLines(lines) {
26815
26819
  if (i === 0 || !/[A-Za-z0-9_]/.test(line[i - 1])) {
26816
26820
  const raw = /^b?r(#*)"/.exec(line.slice(i));
26817
26821
  if (raw) {
26818
- str = { raw: true, hashes: raw[1].length };
26822
+ str2 = { raw: true, hashes: raw[1].length };
26819
26823
  code += " ".repeat(raw[0].length);
26820
26824
  i += raw[0].length;
26821
26825
  continue;
26822
26826
  }
26823
26827
  }
26824
26828
  if (c === '"') {
26825
- str = { raw: false, hashes: 0 };
26829
+ str2 = { raw: false, hashes: 0 };
26826
26830
  code += " ";
26827
26831
  i += 1;
26828
26832
  continue;
@@ -27838,7 +27842,6 @@ function printHuman(outcome) {
27838
27842
  // src/commands/init.ts
27839
27843
  var import_node_fs12 = require("fs");
27840
27844
  var import_node_child_process = require("child_process");
27841
- var import_node_readline3 = __toESM(require("readline"));
27842
27845
 
27843
27846
  // src/core/cli-config.ts
27844
27847
  var import_node_fs11 = require("fs");
@@ -27846,6 +27849,9 @@ var import_node_path10 = require("path");
27846
27849
  var import_node_os4 = require("os");
27847
27850
  var CLI_CONFIG_DIR = (0, import_node_path10.join)((0, import_node_os4.homedir)(), ".threatcrush");
27848
27851
  var CLI_CONFIG_PATH = (0, import_node_path10.join)(CLI_CONFIG_DIR, "config.json");
27852
+ function apiUrl() {
27853
+ return process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
27854
+ }
27849
27855
  function readCliConfig() {
27850
27856
  try {
27851
27857
  return JSON.parse((0, import_node_fs11.readFileSync)(CLI_CONFIG_PATH, "utf-8"));
@@ -27882,46 +27888,157 @@ function isLoggedIn() {
27882
27888
  if (cfg.expires_at && cfg.expires_at * 1e3 < Date.now()) return false;
27883
27889
  return true;
27884
27890
  }
27891
+ function hasSession() {
27892
+ const cfg = readCliConfig();
27893
+ return Boolean(cfg.token || cfg.refresh_token);
27894
+ }
27885
27895
  function authHeaders() {
27886
27896
  const cfg = readCliConfig();
27887
27897
  const headers = { "Content-Type": "application/json" };
27888
27898
  if (cfg.token) headers["Authorization"] = `Bearer ${cfg.token}`;
27889
27899
  return headers;
27890
27900
  }
27901
+ var refreshInFlight = null;
27902
+ function refreshSession() {
27903
+ refreshInFlight ??= doRefresh().finally(() => {
27904
+ refreshInFlight = null;
27905
+ });
27906
+ return refreshInFlight;
27907
+ }
27908
+ async function doRefresh() {
27909
+ const sent = readCliConfig().refresh_token;
27910
+ if (!sent) return "unavailable";
27911
+ let res;
27912
+ try {
27913
+ res = await fetch(`${apiUrl()}/api/auth/refresh`, {
27914
+ method: "POST",
27915
+ headers: { "Content-Type": "application/json" },
27916
+ body: JSON.stringify({ refresh_token: sent }),
27917
+ signal: AbortSignal.timeout(15e3)
27918
+ });
27919
+ } catch {
27920
+ return "unavailable";
27921
+ }
27922
+ if (res.ok) {
27923
+ const data = await res.json().catch(() => null);
27924
+ const session = data?.session;
27925
+ if (!session?.access_token || !session.refresh_token) return "unavailable";
27926
+ updateCliConfig({
27927
+ token: session.access_token,
27928
+ refresh_token: session.refresh_token,
27929
+ expires_at: session.expires_at ?? void 0
27930
+ });
27931
+ return "refreshed";
27932
+ }
27933
+ if (res.status === 401 || res.status === 400) {
27934
+ return readCliConfig().refresh_token !== sent ? "refreshed" : "dead";
27935
+ }
27936
+ return "unavailable";
27937
+ }
27938
+ var EXPIRY_SKEW_SECONDS = 60;
27939
+ async function cloudFetch(path, init = {}) {
27940
+ const cfg = readCliConfig();
27941
+ if (cfg.refresh_token && cfg.expires_at && cfg.expires_at - EXPIRY_SKEW_SECONDS < Date.now() / 1e3) {
27942
+ await refreshSession();
27943
+ }
27944
+ const send = () => fetch(`${apiUrl()}${path}`, {
27945
+ method: init.method ?? "GET",
27946
+ headers: authHeaders(),
27947
+ body: init.body,
27948
+ signal: AbortSignal.timeout(init.timeoutMs ?? 3e4)
27949
+ });
27950
+ const res = await send();
27951
+ if (res.status !== 401) return res;
27952
+ if (await refreshSession() !== "refreshed") return res;
27953
+ return send();
27954
+ }
27891
27955
 
27892
- // src/commands/login.ts
27956
+ // src/core/prompt.ts
27893
27957
  var import_node_readline2 = __toESM(require("readline"));
27894
27958
  var import_node_stream = require("stream");
27895
- var API_URL = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
27896
- function prompt(question) {
27897
- const rl = import_node_readline2.default.createInterface({ input: process.stdin, output: process.stdout });
27898
- return new Promise((resolve5) => rl.question(question, (answer) => {
27899
- rl.close();
27900
- resolve5(answer.trim());
27901
- }));
27959
+ function stdinIsInteractive() {
27960
+ return Boolean(process.stdin.isTTY);
27961
+ }
27962
+ var piped = null;
27963
+ function pipedReader() {
27964
+ if (piped) return piped;
27965
+ const rl = import_node_readline2.default.createInterface({ input: process.stdin, terminal: false });
27966
+ const reader = { rl, lines: [], waiting: null, ended: false };
27967
+ rl.on("line", (line) => {
27968
+ const waiting = reader.waiting;
27969
+ if (waiting) {
27970
+ reader.waiting = null;
27971
+ waiting(line);
27972
+ } else {
27973
+ reader.lines.push(line);
27974
+ }
27975
+ });
27976
+ rl.on("close", () => {
27977
+ reader.ended = true;
27978
+ const waiting = reader.waiting;
27979
+ reader.waiting = null;
27980
+ waiting?.(null);
27981
+ });
27982
+ piped = reader;
27983
+ return reader;
27984
+ }
27985
+ function askPiped(question, mask) {
27986
+ process.stdout.write(question);
27987
+ const reader = pipedReader();
27988
+ const settle = (line) => {
27989
+ if (mask || line === null) process.stdout.write("\n");
27990
+ if (!reader.ended) reader.rl.pause();
27991
+ return line;
27992
+ };
27993
+ if (reader.lines.length > 0) return Promise.resolve(settle(reader.lines.shift()));
27994
+ if (reader.ended) return Promise.resolve(settle(null));
27995
+ reader.rl.resume();
27996
+ return new Promise((resolve5) => {
27997
+ reader.waiting = (line) => resolve5(settle(line));
27998
+ });
27902
27999
  }
27903
- function promptPassword(question) {
28000
+ function askTerminal(question, mask) {
28001
+ const output = mask ? new import_node_stream.Writable({ write(_chunk, _enc, cb) {
28002
+ cb();
28003
+ } }) : process.stdout;
28004
+ const rl = import_node_readline2.default.createInterface({ input: process.stdin, output, terminal: true });
27904
28005
  return new Promise((resolve5) => {
27905
- const muted = new import_node_stream.Writable({
27906
- write(_chunk, _enc, cb) {
27907
- cb();
27908
- }
28006
+ let settled = false;
28007
+ rl.on("close", () => {
28008
+ if (settled) return;
28009
+ settled = true;
28010
+ process.stdout.write("\n");
28011
+ resolve5(null);
27909
28012
  });
27910
- const rl = import_node_readline2.default.createInterface({ input: process.stdin, output: muted, terminal: true });
27911
- process.stdout.write(question);
27912
- rl.question("", (answer) => {
28013
+ if (mask) process.stdout.write(question);
28014
+ rl.question(mask ? "" : question, (answer) => {
28015
+ settled = true;
27913
28016
  rl.close();
27914
- process.stdout.write("\n");
28017
+ if (mask) process.stdout.write("\n");
27915
28018
  resolve5(answer);
27916
28019
  });
27917
28020
  });
27918
28021
  }
28022
+ function ask(question, opts = {}) {
28023
+ const mask = opts.mask ?? false;
28024
+ return stdinIsInteractive() ? askTerminal(question, mask) : askPiped(question, mask);
28025
+ }
28026
+
28027
+ // src/commands/login.ts
28028
+ var API_URL = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
28029
+ var INPUT_CLOSED = {
28030
+ ok: false,
28031
+ error: "No credentials entered (stdin closed).",
28032
+ inputClosed: true
28033
+ };
27919
28034
  async function login(options = {}) {
27920
- const email = options.email || await prompt(source_default.green(" Email: "));
28035
+ const email = options.email || (await ask(source_default.green(" Email: ")))?.trim();
28036
+ if (email === void 0) return INPUT_CLOSED;
27921
28037
  if (!email || !email.includes("@")) {
27922
28038
  return { ok: false, error: "A valid email is required." };
27923
28039
  }
27924
- const password = options.password || await promptPassword(source_default.green(" Password: "));
28040
+ const password = options.password || await ask(source_default.green(" Password: "), { mask: true });
28041
+ if (password === null) return INPUT_CLOSED;
27925
28042
  if (!password) {
27926
28043
  return { ok: false, error: "Password is required." };
27927
28044
  }
@@ -27968,9 +28085,10 @@ async function loginCommand(opts = {}) {
27968
28085
  console.log(source_default.red(`
27969
28086
  \u2717 ${result.error}
27970
28087
  `));
27971
- console.log(source_default.dim(` Forgot password? ${API_URL}/auth/forgot-password`));
28088
+ console.log(source_default.dim(` Forgot password? ${API_URL}/auth/login`));
27972
28089
  console.log(source_default.dim(` No account yet? ${API_URL}/auth/signup
27973
28090
  `));
28091
+ process.exitCode = 1;
27974
28092
  return;
27975
28093
  }
27976
28094
  console.log(source_default.green(`
@@ -28105,17 +28223,32 @@ function findLogPath(paths) {
28105
28223
  return paths.find((p) => (0, import_node_fs12.existsSync)(p));
28106
28224
  }
28107
28225
  async function promptYesNo(question, fallback2) {
28108
- const rl = import_node_readline3.default.createInterface({ input: process.stdin, output: process.stdout });
28109
28226
  const hint = fallback2 ? "(Y/n)" : "(y/N)";
28110
- return new Promise((resolve5) => rl.question(`${question} ${hint}: `, (answer) => {
28111
- rl.close();
28112
- const trimmed = answer.trim().toLowerCase();
28113
- if (!trimmed) return resolve5(fallback2);
28114
- resolve5(trimmed === "y" || trimmed === "yes");
28115
- }));
28227
+ const answer = await ask(`${question} ${hint}: `);
28228
+ if (answer === null) return null;
28229
+ const trimmed = answer.trim().toLowerCase();
28230
+ if (!trimmed) return fallback2;
28231
+ return trimmed === "y" || trimmed === "yes";
28232
+ }
28233
+ function signInStep(o) {
28234
+ if (o.loggedIn) return "signed-in";
28235
+ if (o.offline) return "skip-offline";
28236
+ if (!o.interactive) return "skip-noninteractive";
28237
+ return o.yes ? "sign-in" : "ask";
28238
+ }
28239
+ function continueOffline(reason) {
28240
+ console.log(source_default.yellow(` ${reason} \u2014 continuing setup offline.`));
28241
+ console.log(source_default.dim(` Sign in later with ${source_default.white("threatcrush login")}.
28242
+ `));
28116
28243
  }
28117
- async function ensureLoggedIn() {
28118
- if (isLoggedIn()) {
28244
+ async function ensureLoggedIn(opts) {
28245
+ const step = signInStep({
28246
+ loggedIn: isLoggedIn(),
28247
+ offline: opts.offline,
28248
+ yes: opts.yes,
28249
+ interactive: stdinIsInteractive()
28250
+ });
28251
+ if (step === "signed-in") {
28119
28252
  const cfg = readCliConfig();
28120
28253
  console.log(source_default.green(` \u2713 Signed in as ${source_default.white(cfg.email || cfg.user_id || "unknown")}
28121
28254
  `));
@@ -28123,11 +28256,23 @@ async function ensureLoggedIn() {
28123
28256
  }
28124
28257
  console.log(source_default.green.bold(" Step 1 \u2014 Sign in to threatcrush.com"));
28125
28258
  console.log(source_default.gray(" " + "\u2500".repeat(60)));
28259
+ if (step === "skip-offline") {
28260
+ continueOffline("--offline given, skipping sign-in");
28261
+ return;
28262
+ }
28263
+ if (step === "skip-noninteractive") {
28264
+ continueOffline("stdin is not a terminal, so there is nobody to sign in");
28265
+ return;
28266
+ }
28126
28267
  console.log(source_default.dim(" Your license, organizations, and module store access live on"));
28127
28268
  console.log(source_default.dim(" threatcrush.com. You can skip this and sign in later with"));
28128
28269
  console.log(source_default.dim(` ${source_default.white("threatcrush login")}.
28129
28270
  `));
28130
- const wantsLogin = await promptYesNo(source_default.green(" Sign in now?"), true);
28271
+ const wantsLogin = step === "sign-in" || await promptYesNo(source_default.green(" Sign in now?"), true);
28272
+ if (wantsLogin === null) {
28273
+ continueOffline("No answer (stdin closed)");
28274
+ return;
28275
+ }
28131
28276
  if (!wantsLogin) {
28132
28277
  console.log(source_default.yellow("\n Skipped login \u2014 running setup in offline mode.\n"));
28133
28278
  return;
@@ -28144,8 +28289,9 @@ async function ensureLoggedIn() {
28144
28289
  attempts++;
28145
28290
  console.log(source_default.red(`
28146
28291
  \u2717 ${result.error}`));
28292
+ if (result.inputClosed) break;
28147
28293
  if (attempts < 3) {
28148
- const retry = await promptYesNo(source_default.yellow(" Try again?"), true);
28294
+ const retry = opts.yes || await promptYesNo(source_default.yellow(" Try again?"), true);
28149
28295
  if (!retry) break;
28150
28296
  }
28151
28297
  }
@@ -28153,10 +28299,10 @@ async function ensureLoggedIn() {
28153
28299
  console.log(source_default.dim(` ${source_default.white("threatcrush login")} at any time.
28154
28300
  `));
28155
28301
  }
28156
- async function initCommand() {
28302
+ async function initCommand(opts = {}) {
28157
28303
  banner();
28158
28304
  logger.info("Initializing ThreatCrush...\n");
28159
- await ensureLoggedIn();
28305
+ await ensureLoggedIn(opts);
28160
28306
  console.log(source_default.green.bold(" Step 2 \u2014 Detect services and write config"));
28161
28307
  console.log(source_default.gray(" " + "\u2500".repeat(60)));
28162
28308
  const spinner = ora({ text: "Detecting services...", color: "green" }).start();
@@ -28258,6 +28404,15 @@ function checkWriteAccess(dir) {
28258
28404
  }
28259
28405
  }
28260
28406
 
28407
+ // src/core/builtin-modules.ts
28408
+ var BUILTIN_MODULES = [
28409
+ { name: "log-watcher", version: "0.1.0", description: "Web and system log attacks (nginx, syslog)" },
28410
+ { name: "ssh-guard", version: "0.1.0", description: "SSH brute force (auth.log or the sshd journal)" },
28411
+ { name: "user-journal", version: "0.1.0", description: "Events from the systemd journal" },
28412
+ { name: "network-monitor", version: "0.1.0", description: "Inbound connections and port scans" },
28413
+ { name: "dns-monitor", version: "0.1.0", description: "DNS tunneling and DGA indicators" }
28414
+ ];
28415
+
28261
28416
  // src/core/module-loader.ts
28262
28417
  var import_node_fs13 = require("fs");
28263
28418
  var import_node_path11 = require("path");
@@ -28327,14 +28482,29 @@ function removePidFile() {
28327
28482
  } catch {
28328
28483
  }
28329
28484
  }
28485
+ function procStatState(stat) {
28486
+ const close = stat.lastIndexOf(")");
28487
+ if (close === -1) return null;
28488
+ return stat.slice(close + 1).trim().charAt(0) || null;
28489
+ }
28490
+ function isZombie(pid) {
28491
+ let stat;
28492
+ try {
28493
+ stat = (0, import_node_fs14.readFileSync)(`/proc/${pid}/stat`, "utf-8");
28494
+ } catch {
28495
+ return false;
28496
+ }
28497
+ const state = procStatState(stat);
28498
+ return state === "Z" || state === "X";
28499
+ }
28330
28500
  function isProcessAlive(pid) {
28331
28501
  try {
28332
28502
  process.kill(pid, 0);
28333
- return true;
28334
28503
  } catch (err) {
28335
28504
  const code = err.code;
28336
- return code === "EPERM";
28505
+ if (code !== "EPERM") return false;
28337
28506
  }
28507
+ return !isZombie(pid);
28338
28508
  }
28339
28509
  function findRunningDaemon() {
28340
28510
  const pid = readPidFile();
@@ -28384,18 +28554,29 @@ async function statusCommand() {
28384
28554
  console.log(` ${dot} ${source_default.white.bold(mod.name.padEnd(18))} ${source_default.gray(mod.status.padEnd(10))} ${source_default.dim(`${mod.events} events`)}`);
28385
28555
  }
28386
28556
  } else {
28387
- const modules = discoverModules();
28388
- if (modules.length === 0) {
28389
- console.log(source_default.gray(" No modules discovered. Run `threatcrush init`."));
28390
- } else {
28391
- for (const mod of modules) {
28392
- const enabled = mod.config.enabled !== false;
28393
- const status = enabled ? source_default.green("\u25CF enabled ") : source_default.gray("\u25CB disabled");
28394
- console.log(` ${status} ${source_default.white.bold(mod.manifest.name.padEnd(18))} ${source_default.gray("v" + mod.manifest.version)}`);
28395
- }
28557
+ for (const mod of BUILTIN_MODULES) {
28558
+ console.log(` ${source_default.cyan("\u25CB")} ${source_default.white.bold(mod.name.padEnd(18))} ${source_default.gray("built-in")}`);
28559
+ }
28560
+ for (const mod of discoverModules()) {
28561
+ if (BUILTIN_MODULES.some((b) => b.name === mod.manifest.name)) continue;
28562
+ const enabled = mod.config.enabled !== false;
28563
+ const status = enabled ? source_default.green("\u25CF enabled ") : source_default.gray("\u25CB disabled");
28564
+ console.log(` ${status} ${source_default.white.bold(mod.manifest.name.padEnd(18))} ${source_default.gray("v" + mod.manifest.version)}`);
28396
28565
  }
28397
28566
  }
28398
28567
  console.log();
28568
+ const cli = readCliConfig();
28569
+ console.log(source_default.green.bold(" Dashboard"));
28570
+ console.log(source_default.gray(" " + "\u2500".repeat(60)));
28571
+ if (!hasSession()) {
28572
+ console.log(` Link: ${source_default.gray("\u25CB not logged in")} ${source_default.dim("threatcrush login")}`);
28573
+ } else if (cli.server_id) {
28574
+ console.log(` Link: ${source_default.green("\u25CF linked")} ${source_default.white(cli.server_id)}`);
28575
+ console.log(` Org: ${source_default.white(cli.server_org_id ?? "-")}`);
28576
+ } else {
28577
+ console.log(` Link: ${source_default.gray("\u25CB not linked")} ${source_default.dim("threatcrush servers link")}`);
28578
+ }
28579
+ console.log();
28399
28580
  try {
28400
28581
  if (!live) initStateDB(PATHS.stateDb);
28401
28582
  const total = live ? live.counters.events : getEventCount();
@@ -28645,34 +28826,36 @@ function notifyDaemonIfRunning() {
28645
28826
  }
28646
28827
  async function modulesListCommand() {
28647
28828
  banner();
28648
- const modules = discoverModules();
28649
- console.log(source_default.green.bold(" Installed Modules"));
28829
+ const installed = discoverModules().filter((m) => !BUILTIN_MODULES.some((b) => b.name === m.manifest.name));
28830
+ console.log(source_default.green.bold(" Modules"));
28650
28831
  console.log(source_default.gray(" " + "\u2500".repeat(60)));
28651
28832
  console.log(source_default.dim(` module dir: ${PATHS.moduleDir}
28652
28833
  `));
28653
- if (modules.length === 0) {
28654
- console.log(source_default.gray(" No modules installed."));
28655
- console.log();
28656
- console.log(source_default.gray(" Browse available modules:"));
28657
- console.log(source_default.white(" threatcrush store"));
28658
- console.log();
28659
- console.log(source_default.gray(" Or install from the marketplace:"));
28660
- console.log(source_default.white(" threatcrush modules install <name>"));
28661
- console.log();
28662
- return;
28663
- }
28664
28834
  console.log(
28665
28835
  source_default.gray(" ") + source_default.white.bold("Name".padEnd(22)) + source_default.white.bold("Version".padEnd(12)) + source_default.white.bold("Status".padEnd(12)) + source_default.white.bold("Description")
28666
28836
  );
28667
28837
  console.log(source_default.gray(" " + "\u2500".repeat(60)));
28668
- for (const mod of modules) {
28838
+ for (const mod of BUILTIN_MODULES) {
28839
+ console.log(
28840
+ source_default.gray(" ") + source_default.white(mod.name.padEnd(22)) + source_default.gray(mod.version.padEnd(12)) + source_default.cyan("built-in".padEnd(12)) + source_default.gray(mod.description)
28841
+ );
28842
+ }
28843
+ for (const mod of installed) {
28669
28844
  const enabled = mod.config.enabled !== false;
28670
- const status = enabled ? source_default.green("enabled") : source_default.gray("disabled");
28845
+ const status = enabled ? source_default.green("enabled".padEnd(12)) : source_default.gray("disabled".padEnd(12));
28671
28846
  console.log(
28672
- source_default.gray(" ") + source_default.white(mod.manifest.name.padEnd(22)) + source_default.gray(mod.manifest.version.padEnd(12)) + status.padEnd(21) + source_default.gray(mod.manifest.description || "\u2014")
28847
+ source_default.gray(" ") + source_default.white(mod.manifest.name.padEnd(22)) + source_default.gray(mod.manifest.version.padEnd(12)) + status + source_default.gray(mod.manifest.description || "\u2014")
28673
28848
  );
28674
28849
  }
28675
28850
  console.log();
28851
+ if (installed.length === 0) {
28852
+ console.log(source_default.gray(" No store modules installed. Browse available modules:"));
28853
+ console.log(source_default.white(" threatcrush store"));
28854
+ console.log();
28855
+ console.log(source_default.gray(" Or install from the marketplace:"));
28856
+ console.log(source_default.white(" threatcrush modules install <name>"));
28857
+ console.log();
28858
+ }
28676
28859
  }
28677
28860
  async function modulesInstallCommand(source) {
28678
28861
  banner();
@@ -28770,7 +28953,8 @@ async function modulesInstallCommand(source) {
28770
28953
  });
28771
28954
  if (!res.ok) {
28772
28955
  const err = await res.json().catch(() => ({ error: res.statusText }));
28773
- spinner.fail(`Module not found: ${err.error || source}`);
28956
+ const message = err.error || source;
28957
+ spinner.fail(res.status === 404 ? `Module not found: ${message}` : `Cannot install ${source}: ${message}`);
28774
28958
  console.log(source_default.gray(` Browse: ${API_URL2}/store
28775
28959
  `));
28776
28960
  return;
@@ -29491,40 +29675,113 @@ async function useOrganization(slug) {
29491
29675
  }
29492
29676
 
29493
29677
  // src/commands/servers.ts
29678
+ var import_node_readline3 = __toESM(require("readline"));
29494
29679
  var import_node_os6 = require("os");
29495
- var import_node_fs18 = require("fs");
29496
- var import_node_path15 = require("path");
29497
- var API_URL4 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
29498
- var CONFIG_PATH2 = (0, import_node_path15.join)((0, import_node_os6.homedir)(), ".threatcrush", "config.json");
29499
- function readConfig2() {
29500
- try {
29501
- return JSON.parse((0, import_node_fs18.readFileSync)(CONFIG_PATH2, "utf-8"));
29502
- } catch {
29503
- return {};
29504
- }
29505
- }
29506
- function getAuthHeaders2() {
29507
- const config = readConfig2();
29508
- const headers = { "Content-Type": "application/json" };
29509
- if (config.token) headers["Authorization"] = `Bearer ${config.token}`;
29510
- return headers;
29511
- }
29512
29680
  async function serversCommand(options) {
29513
29681
  const { action, name, org } = options;
29514
29682
  if (action === "list" || !action) {
29515
29683
  await listServers(org);
29516
29684
  return;
29517
29685
  }
29686
+ if (action === "link") {
29687
+ await linkCommand({ org, name });
29688
+ return;
29689
+ }
29690
+ if (action === "unlink") {
29691
+ unlinkCommand();
29692
+ return;
29693
+ }
29518
29694
  if (action === "add") {
29519
29695
  console.log(source_default.red(" Interactive server add is not yet implemented."));
29520
29696
  console.log(source_default.dim(" Use the web dashboard to add servers: https://threatcrush.com/dashboard\n"));
29521
29697
  return;
29522
29698
  }
29523
29699
  console.log(source_default.red(` Unknown action: ${action}`));
29524
- console.log(source_default.dim(" Available: list\n"));
29700
+ console.log(source_default.dim(" Available: list, link, unlink\n"));
29701
+ }
29702
+ async function fetchOrgs() {
29703
+ const res = await cloudFetch("/api/orgs");
29704
+ if (res.status === 401) throw new Error("Not authenticated. Run: threatcrush login");
29705
+ if (!res.ok) throw new Error(`Failed to fetch organizations (${res.status})`);
29706
+ const data = await res.json();
29707
+ return data.organizations || [];
29708
+ }
29709
+ function askChoice(question) {
29710
+ const rl = import_node_readline3.default.createInterface({ input: process.stdin, output: process.stdout });
29711
+ return new Promise((resolve5) => rl.question(question, (answer) => {
29712
+ rl.close();
29713
+ resolve5(answer.trim());
29714
+ }));
29715
+ }
29716
+ async function chooseOrg(orgs, flag, ask2) {
29717
+ if (flag) {
29718
+ const org2 = orgs.find((o) => o.id === flag || o.slug === flag);
29719
+ if (!org2) throw new Error(`Organization "${flag}" not found among yours.`);
29720
+ return org2;
29721
+ }
29722
+ const current = orgs.find((o) => o.id === readCliConfig().current_org_id);
29723
+ if (current) return current;
29724
+ if (orgs.length === 1) return orgs[0];
29725
+ if (orgs.length === 0) throw new Error("You are not in any organization. Create one: threatcrush orgs create <name>");
29726
+ if (!process.stdin.isTTY) {
29727
+ throw new Error(`You are in ${orgs.length} organizations; pick one with --org <${orgs.map((o) => o.slug).join("|")}>`);
29728
+ }
29729
+ orgs.forEach((o, i) => console.log(` ${i + 1}) ${o.name} ${source_default.gray(`(/${o.slug})`)}`));
29730
+ const answer = await ask2(source_default.green(` Link to which organization? [1-${orgs.length}]: `));
29731
+ const org = orgs[Number(answer) - 1];
29732
+ if (!org) throw new Error("No organization chosen.");
29733
+ return org;
29734
+ }
29735
+ async function linkServer(opts = {}, ask2 = askChoice) {
29736
+ if (!hasSession()) throw new Error("Not logged in. Run: threatcrush login");
29737
+ const org = await chooseOrg(await fetchOrgs(), opts.org, ask2);
29738
+ const host = opts.hostname ?? (0, import_node_os6.hostname)();
29739
+ const listRes = await cloudFetch(`/api/orgs/${org.id}/servers`);
29740
+ if (!listRes.ok) throw new Error(`Failed to list servers in /${org.slug} (${listRes.status})`);
29741
+ const { servers = [] } = await listRes.json();
29742
+ const matches2 = servers.filter((s) => s.hostname?.toLowerCase() === host.toLowerCase());
29743
+ let server = matches2.find((s) => opts.name && s.name === opts.name) ?? matches2[0];
29744
+ let created = false;
29745
+ if (!server) {
29746
+ const res = await cloudFetch(`/api/orgs/${org.id}/servers`, {
29747
+ method: "POST",
29748
+ body: JSON.stringify({ name: opts.name || host, hostname: host })
29749
+ });
29750
+ const data = await res.json().catch(() => ({}));
29751
+ if (!res.ok || !data.server) {
29752
+ throw new Error(`Could not register this server in /${org.slug}: ${data.error || res.status}`);
29753
+ }
29754
+ server = data.server;
29755
+ created = true;
29756
+ }
29757
+ updateCliConfig({ server_id: server.id, server_org_id: org.id });
29758
+ return { org, server, created };
29759
+ }
29760
+ async function linkCommand(opts) {
29761
+ try {
29762
+ const { org, server, created } = await linkServer(opts);
29763
+ console.log(source_default.green(` \u2713 ${created ? "Registered and linked" : "Linked"} ${source_default.bold(server.name)} in /${org.slug}`));
29764
+ console.log(source_default.dim(` server id: ${server.id} hostname: ${server.hostname ?? "-"}`));
29765
+ console.log(source_default.dim(" A running daemon starts reporting within a minute; no restart needed."));
29766
+ console.log(source_default.dim(" Opt out in threatcrushd.conf: [cloud] enabled = false\n"));
29767
+ } catch (err) {
29768
+ console.log(source_default.red(` \u2717 ${err.message}
29769
+ `));
29770
+ process.exitCode = 1;
29771
+ }
29772
+ }
29773
+ function unlinkCommand() {
29774
+ const cfg = readCliConfig();
29775
+ if (!cfg.server_id) {
29776
+ console.log(source_default.gray(" This machine is not linked to a dashboard server.\n"));
29777
+ return;
29778
+ }
29779
+ clearCliConfig(["server_id", "server_org_id"]);
29780
+ console.log(source_default.green(` \u2713 Unlinked from server ${cfg.server_id}.`));
29781
+ console.log(source_default.dim(" The daemon stops reporting within a minute. The server stays on the dashboard until you delete it there.\n"));
29525
29782
  }
29526
29783
  async function listServers(orgSlug) {
29527
- const config = readConfig2();
29784
+ const config = readCliConfig();
29528
29785
  if (!config.current_org_id && !orgSlug) {
29529
29786
  console.log(source_default.yellow(" No current organization set."));
29530
29787
  console.log(source_default.dim(" Set one with: threatcrush orgs use <slug>\n"));
@@ -29534,14 +29791,7 @@ async function listServers(orgSlug) {
29534
29791
  try {
29535
29792
  let orgId = config.current_org_id;
29536
29793
  if (orgSlug) {
29537
- const orgsRes = await fetch(`${API_URL4}/api/orgs`, { headers: getAuthHeaders2() });
29538
- if (!orgsRes.ok) {
29539
- console.log(source_default.red(` Failed to fetch organizations: ${orgsRes.statusText}
29540
- `));
29541
- return;
29542
- }
29543
- const orgsData = await orgsRes.json();
29544
- const org = (orgsData.organizations || []).find((o) => o.slug === orgSlug);
29794
+ const org = (await fetchOrgs()).find((o) => o.slug === orgSlug);
29545
29795
  if (!org) {
29546
29796
  console.log(source_default.red(` Organization "/${orgSlug}" not found.
29547
29797
  `));
@@ -29553,7 +29803,7 @@ async function listServers(orgSlug) {
29553
29803
  console.log(source_default.red(" Could not resolve organization.\n"));
29554
29804
  return;
29555
29805
  }
29556
- const res = await fetch(`${API_URL4}/api/orgs/${orgId}/servers`, { headers: getAuthHeaders2() });
29806
+ const res = await cloudFetch(`/api/orgs/${orgId}/servers`);
29557
29807
  if (!res.ok) {
29558
29808
  console.log(source_default.red(` Failed to list servers: ${res.statusText}
29559
29809
  `));
@@ -29563,13 +29813,14 @@ async function listServers(orgSlug) {
29563
29813
  const servers = data.servers || [];
29564
29814
  if (servers.length === 0) {
29565
29815
  console.log(source_default.yellow(" No servers registered."));
29566
- console.log(source_default.dim(" Add servers via the web dashboard.\n"));
29816
+ console.log(source_default.dim(" Link this machine: threatcrush servers link\n"));
29567
29817
  return;
29568
29818
  }
29569
29819
  for (const server of servers) {
29570
29820
  const statusColor = server.status === "online" ? source_default.green : server.status === "unreachable" ? source_default.red : source_default.gray;
29571
29821
  const statusDot = server.status === "online" ? "\u25CF" : "\u25CB";
29572
- console.log(` ${statusColor(statusDot)} ${source_default.bold(server.name)}`);
29822
+ const self = server.id === config.server_id ? source_default.cyan(" (this machine)") : "";
29823
+ console.log(` ${statusColor(statusDot)} ${source_default.bold(server.name)}${self}`);
29573
29824
  console.log(` ${source_default.dim(`${server.hostname || server.ip_address}:${server.port}`)}`);
29574
29825
  console.log(` Status: ${statusColor(server.status)}`);
29575
29826
  if (server.last_seen) {
@@ -29601,20 +29852,20 @@ function timeAgo(dateStr) {
29601
29852
 
29602
29853
  // src/commands/connect.ts
29603
29854
  var import_node_os7 = require("os");
29604
- var import_node_fs19 = require("fs");
29605
- var import_node_path16 = require("path");
29855
+ var import_node_fs18 = require("fs");
29856
+ var import_node_path15 = require("path");
29606
29857
  var import_node_child_process3 = require("child_process");
29607
- var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
29608
- var CONFIG_PATH3 = (0, import_node_path16.join)((0, import_node_os7.homedir)(), ".threatcrush", "config.json");
29609
- function readConfig3() {
29858
+ var API_URL4 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
29859
+ var CONFIG_PATH2 = (0, import_node_path15.join)((0, import_node_os7.homedir)(), ".threatcrush", "config.json");
29860
+ function readConfig2() {
29610
29861
  try {
29611
- return JSON.parse((0, import_node_fs19.readFileSync)(CONFIG_PATH3, "utf-8"));
29862
+ return JSON.parse((0, import_node_fs18.readFileSync)(CONFIG_PATH2, "utf-8"));
29612
29863
  } catch {
29613
29864
  return {};
29614
29865
  }
29615
29866
  }
29616
- function getAuthHeaders3() {
29617
- const config = readConfig3();
29867
+ function getAuthHeaders2() {
29868
+ const config = readConfig2();
29618
29869
  const headers = { "Content-Type": "application/json" };
29619
29870
  if (config.token) headers["Authorization"] = `Bearer ${config.token}`;
29620
29871
  return headers;
@@ -29648,9 +29899,9 @@ async function connectCommand(options) {
29648
29899
  }
29649
29900
  }
29650
29901
  async function interactiveConnect(orgSlug) {
29651
- const config = readConfig3();
29902
+ const config = readConfig2();
29652
29903
  try {
29653
- const orgsRes = await fetch(`${API_URL5}/api/orgs`, { headers: getAuthHeaders3() });
29904
+ const orgsRes = await fetch(`${API_URL4}/api/orgs`, { headers: getAuthHeaders2() });
29654
29905
  if (!orgsRes.ok) {
29655
29906
  console.log(source_default.red(" Failed to fetch organizations. Are you logged in?\n"));
29656
29907
  return;
@@ -29672,7 +29923,7 @@ async function interactiveConnect(orgSlug) {
29672
29923
  if (!orgId) {
29673
29924
  orgId = orgs[0].id;
29674
29925
  }
29675
- const serversRes = await fetch(`${API_URL5}/api/orgs/${orgId}/servers`, { headers: getAuthHeaders3() });
29926
+ const serversRes = await fetch(`${API_URL4}/api/orgs/${orgId}/servers`, { headers: getAuthHeaders2() });
29676
29927
  if (!serversRes.ok) {
29677
29928
  console.log(source_default.red(" Failed to fetch servers.\n"));
29678
29929
  return;
@@ -29701,11 +29952,11 @@ async function interactiveConnect(orgSlug) {
29701
29952
  }
29702
29953
  }
29703
29954
  async function resolveServer(nameOrSlug, orgSlug) {
29704
- const config = readConfig3();
29955
+ const config = readConfig2();
29705
29956
  try {
29706
29957
  let orgId = config.current_org_id;
29707
29958
  if (orgSlug) {
29708
- const orgsRes = await fetch(`${API_URL5}/api/orgs`, { headers: getAuthHeaders3() });
29959
+ const orgsRes = await fetch(`${API_URL4}/api/orgs`, { headers: getAuthHeaders2() });
29709
29960
  if (!orgsRes.ok) return null;
29710
29961
  const orgsData = await orgsRes.json();
29711
29962
  const org = (orgsData.organizations || []).find((o) => o.slug === orgSlug);
@@ -29713,13 +29964,13 @@ async function resolveServer(nameOrSlug, orgSlug) {
29713
29964
  orgId = org.id;
29714
29965
  }
29715
29966
  if (!orgId) {
29716
- const orgsRes = await fetch(`${API_URL5}/api/orgs`, { headers: getAuthHeaders3() });
29967
+ const orgsRes = await fetch(`${API_URL4}/api/orgs`, { headers: getAuthHeaders2() });
29717
29968
  if (!orgsRes.ok) return null;
29718
29969
  const orgsData = await orgsRes.json();
29719
29970
  orgId = (orgsData.organizations || [])[0]?.id;
29720
29971
  if (!orgId) return null;
29721
29972
  }
29722
- const serversRes = await fetch(`${API_URL5}/api/orgs/${orgId}/servers`, { headers: getAuthHeaders3() });
29973
+ const serversRes = await fetch(`${API_URL4}/api/orgs/${orgId}/servers`, { headers: getAuthHeaders2() });
29723
29974
  if (!serversRes.ok) return null;
29724
29975
  const serversData = await serversRes.json();
29725
29976
  const servers = serversData.servers || [];
@@ -29730,20 +29981,20 @@ async function resolveServer(nameOrSlug, orgSlug) {
29730
29981
  }
29731
29982
  }
29732
29983
  async function sshConnect(options) {
29733
- const { hostname, port, username, identity } = options;
29734
- if (!hostname) {
29984
+ const { hostname: hostname2, port, username, identity } = options;
29985
+ if (!hostname2) {
29735
29986
  console.log(source_default.red(" No hostname available for this server.\n"));
29736
29987
  return;
29737
29988
  }
29738
29989
  const user = username || "root";
29739
- console.log(source_default.green(` Connecting to ${user}@${hostname}:${port}...
29990
+ console.log(source_default.green(` Connecting to ${user}@${hostname2}:${port}...
29740
29991
  `));
29741
29992
  console.log(source_default.dim(" (Spawning SSH session \u2014 exit with Ctrl+D or type 'exit')\n"));
29742
29993
  const sshArgs = ["-p", String(port)];
29743
29994
  if (identity) {
29744
29995
  sshArgs.push("-i", identity);
29745
29996
  }
29746
- sshArgs.push(`${user}@${hostname}`);
29997
+ sshArgs.push(`${user}@${hostname2}`);
29747
29998
  const ssh = (0, import_node_child_process3.spawn)("ssh", sshArgs, { stdio: "inherit" });
29748
29999
  ssh.on("error", (err) => {
29749
30000
  console.log(source_default.red(`
@@ -29762,19 +30013,22 @@ async function sshConnect(options) {
29762
30013
  }
29763
30014
 
29764
30015
  // src/commands/daemon.ts
29765
- var import_node_child_process9 = require("child_process");
30016
+ var import_node_child_process10 = require("child_process");
29766
30017
  var import_node_fs29 = require("fs");
29767
30018
  var import_node_path21 = require("path");
29768
30019
  var import_node_fs30 = require("fs");
29769
30020
 
29770
30021
  // src/daemon/index.ts
29771
30022
  var import_node_fs28 = require("fs");
30023
+ var import_node_child_process9 = require("child_process");
30024
+ var import_node_os8 = require("os");
29772
30025
  var import_node_path20 = require("path");
30026
+ var import_node_util = require("util");
29773
30027
  init_paths();
29774
30028
 
29775
30029
  // src/daemon/ipc-server.ts
29776
30030
  var import_node_net2 = require("net");
29777
- var import_node_fs20 = require("fs");
30031
+ var import_node_fs19 = require("fs");
29778
30032
  init_paths();
29779
30033
  init_control_token();
29780
30034
 
@@ -29826,9 +30080,9 @@ var IpcServer = class {
29826
30080
  controlToken = "";
29827
30081
  async start() {
29828
30082
  this.controlToken = issueControlToken();
29829
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) {
30083
+ if ((0, import_node_fs19.existsSync)(PATHS.socket)) {
29830
30084
  try {
29831
- (0, import_node_fs20.unlinkSync)(PATHS.socket);
30085
+ (0, import_node_fs19.unlinkSync)(PATHS.socket);
29832
30086
  } catch {
29833
30087
  }
29834
30088
  }
@@ -29864,14 +30118,14 @@ var IpcServer = class {
29864
30118
  return new Promise((resolve5) => {
29865
30119
  if (!this.server) {
29866
30120
  try {
29867
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) (0, import_node_fs20.unlinkSync)(PATHS.socket);
30121
+ if ((0, import_node_fs19.existsSync)(PATHS.socket)) (0, import_node_fs19.unlinkSync)(PATHS.socket);
29868
30122
  } catch {
29869
30123
  }
29870
30124
  return resolve5();
29871
30125
  }
29872
30126
  this.server.close(() => {
29873
30127
  try {
29874
- if ((0, import_node_fs20.existsSync)(PATHS.socket)) (0, import_node_fs20.unlinkSync)(PATHS.socket);
30128
+ if ((0, import_node_fs19.existsSync)(PATHS.socket)) (0, import_node_fs19.unlinkSync)(PATHS.socket);
29875
30129
  } catch {
29876
30130
  }
29877
30131
  resolve5();
@@ -30052,14 +30306,14 @@ var IpcServer = class {
30052
30306
  };
30053
30307
 
30054
30308
  // src/daemon/module-host.ts
30055
- var import_node_fs24 = require("fs");
30056
- var import_node_path17 = require("path");
30309
+ var import_node_fs23 = require("fs");
30310
+ var import_node_path16 = require("path");
30057
30311
  var import_node_url = require("url");
30058
30312
  var import_toml4 = __toESM(require_toml());
30059
30313
  init_paths();
30060
30314
 
30061
30315
  // src/daemon/watchers/log-watcher.ts
30062
- var import_node_fs21 = require("fs");
30316
+ var import_node_fs20 = require("fs");
30063
30317
  var import_node_readline4 = require("readline");
30064
30318
  var DEFAULT_SOURCES = [
30065
30319
  { path: "/var/log/auth.log", module: "ssh-guard", category: "auth" },
@@ -30080,9 +30334,9 @@ var LogWatcher = class {
30080
30334
  start() {
30081
30335
  const started = [];
30082
30336
  for (const src of this.sources) {
30083
- if (!(0, import_node_fs21.existsSync)(src.path)) continue;
30337
+ if (!(0, import_node_fs20.existsSync)(src.path)) continue;
30084
30338
  try {
30085
- (0, import_node_fs21.accessSync)(src.path, import_node_fs21.constants.R_OK);
30339
+ (0, import_node_fs20.accessSync)(src.path, import_node_fs20.constants.R_OK);
30086
30340
  } catch {
30087
30341
  continue;
30088
30342
  }
@@ -30110,7 +30364,7 @@ var LogWatcher = class {
30110
30364
  }
30111
30365
  tail(src) {
30112
30366
  try {
30113
- this.positions.set(src.path, (0, import_node_fs21.statSync)(src.path).size);
30367
+ this.positions.set(src.path, (0, import_node_fs20.statSync)(src.path).size);
30114
30368
  } catch {
30115
30369
  this.positions.set(src.path, 0);
30116
30370
  }
@@ -30121,7 +30375,7 @@ var LogWatcher = class {
30121
30375
  poll(src) {
30122
30376
  let stat;
30123
30377
  try {
30124
- stat = (0, import_node_fs21.statSync)(src.path);
30378
+ stat = (0, import_node_fs20.statSync)(src.path);
30125
30379
  } catch {
30126
30380
  return;
30127
30381
  }
@@ -30131,7 +30385,7 @@ var LogWatcher = class {
30131
30385
  return;
30132
30386
  }
30133
30387
  if (stat.size === prev) return;
30134
- const stream = (0, import_node_fs21.createReadStream)(src.path, { start: prev, encoding: "utf-8" });
30388
+ const stream = (0, import_node_fs20.createReadStream)(src.path, { start: prev, encoding: "utf-8" });
30135
30389
  stream.on("error", () => this.positions.set(src.path, stat.size));
30136
30390
  const rl = (0, import_node_readline4.createInterface)({ input: stream });
30137
30391
  rl.on("error", () => {
@@ -30392,7 +30646,7 @@ function realtimeToDate(rt) {
30392
30646
 
30393
30647
  // src/modules/network-monitor/index.ts
30394
30648
  var import_node_child_process5 = require("child_process");
30395
- var import_node_fs22 = require("fs");
30649
+ var import_node_fs21 = require("fs");
30396
30650
  var NetworkMonitor = class {
30397
30651
  constructor(bus2) {
30398
30652
  this.bus = bus2;
@@ -30456,7 +30710,7 @@ var NetworkMonitor = class {
30456
30710
  hasConntrackOrSs() {
30457
30711
  const ss = (0, import_node_child_process5.spawnSync)("ss", ["--version"], { stdio: "pipe" });
30458
30712
  if (ss.status === 0) return true;
30459
- return (0, import_node_fs22.existsSync)("/proc/net/tcp");
30713
+ return (0, import_node_fs21.existsSync)("/proc/net/tcp");
30460
30714
  }
30461
30715
  /**
30462
30716
  * The TCP ports this host actually listens on.
@@ -30643,7 +30897,7 @@ var NetworkMonitor = class {
30643
30897
  };
30644
30898
 
30645
30899
  // src/modules/dns-monitor/index.ts
30646
- var import_node_fs23 = require("fs");
30900
+ var import_node_fs22 = require("fs");
30647
30901
  var import_node_child_process6 = require("child_process");
30648
30902
  var import_node_readline5 = require("readline");
30649
30903
  var DNS_LOG_SOURCES = [
@@ -30725,9 +30979,9 @@ var DnsMonitor = class {
30725
30979
  }
30726
30980
  start() {
30727
30981
  const sources = [...DNS_LOG_SOURCES, ...this.extraPaths].filter((p) => {
30728
- if (!(0, import_node_fs23.existsSync)(p)) return false;
30982
+ if (!(0, import_node_fs22.existsSync)(p)) return false;
30729
30983
  try {
30730
- (0, import_node_fs23.accessSync)(p, import_node_fs23.constants.R_OK);
30984
+ (0, import_node_fs22.accessSync)(p, import_node_fs22.constants.R_OK);
30731
30985
  return true;
30732
30986
  } catch {
30733
30987
  return false;
@@ -30803,7 +31057,7 @@ var DnsMonitor = class {
30803
31057
  }
30804
31058
  tailLog(path) {
30805
31059
  try {
30806
- this.positions.set(path, (0, import_node_fs23.statSync)(path).size);
31060
+ this.positions.set(path, (0, import_node_fs22.statSync)(path).size);
30807
31061
  } catch {
30808
31062
  this.positions.set(path, 0);
30809
31063
  }
@@ -30813,7 +31067,7 @@ var DnsMonitor = class {
30813
31067
  pollLog(path) {
30814
31068
  let stat;
30815
31069
  try {
30816
- stat = (0, import_node_fs23.statSync)(path);
31070
+ stat = (0, import_node_fs22.statSync)(path);
30817
31071
  } catch {
30818
31072
  return;
30819
31073
  }
@@ -30823,7 +31077,7 @@ var DnsMonitor = class {
30823
31077
  return;
30824
31078
  }
30825
31079
  if (stat.size === prev) return;
30826
- const stream = (0, import_node_fs23.createReadStream)(path, { start: prev, encoding: "utf-8" });
31080
+ const stream = (0, import_node_fs22.createReadStream)(path, { start: prev, encoding: "utf-8" });
30827
31081
  stream.on("error", () => this.positions.set(path, stat.size));
30828
31082
  const rl = (0, import_node_readline5.createInterface)({ input: stream });
30829
31083
  rl.on("line", (line) => this.parseDnsLine(line));
@@ -30933,14 +31187,14 @@ var DnsMonitor = class {
30933
31187
  );
30934
31188
  }
30935
31189
  }
30936
- shannonEntropy(str) {
31190
+ shannonEntropy(str2) {
30937
31191
  const freq = /* @__PURE__ */ new Map();
30938
- for (const ch of str) {
31192
+ for (const ch of str2) {
30939
31193
  freq.set(ch, (freq.get(ch) || 0) + 1);
30940
31194
  }
30941
31195
  let entropy = 0;
30942
31196
  for (const count of freq.values()) {
30943
- const p = count / str.length;
31197
+ const p = count / str2.length;
30944
31198
  if (p > 0) entropy -= p * Math.log2(p);
30945
31199
  }
30946
31200
  return entropy;
@@ -31077,25 +31331,20 @@ var ModuleHost = class {
31077
31331
  }));
31078
31332
  }
31079
31333
  registerBuiltins() {
31080
- const builtins = [
31081
- { name: "log-watcher", version: "0.1.0", source: "builtin", status: "loaded", events: 0 },
31082
- { name: "ssh-guard", version: "0.1.0", source: "builtin", status: "loaded", events: 0 },
31083
- { name: "user-journal", version: "0.1.0", source: "builtin", status: "loaded", events: 0 },
31084
- { name: "network-monitor", version: "0.1.0", source: "builtin", status: "loaded", events: 0 },
31085
- { name: "dns-monitor", version: "0.1.0", source: "builtin", status: "loaded", events: 0 }
31086
- ];
31087
- for (const m of builtins) this.modules.set(m.name, m);
31334
+ for (const { name, version } of BUILTIN_MODULES) {
31335
+ this.modules.set(name, { name, version, source: "builtin", status: "loaded", events: 0 });
31336
+ }
31088
31337
  }
31089
31338
  async discoverAndStartInstalled() {
31090
- if (!(0, import_node_fs24.existsSync)(PATHS.moduleDir)) return;
31339
+ if (!(0, import_node_fs23.existsSync)(PATHS.moduleDir)) return;
31091
31340
  const configs = loadModuleConfigs(PATHS.confD);
31092
- const entries = (0, import_node_fs24.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
31341
+ const entries = (0, import_node_fs23.readdirSync)(PATHS.moduleDir, { withFileTypes: true });
31093
31342
  for (const entry of entries) {
31094
31343
  if (!entry.isDirectory()) continue;
31095
- const manifestPath = (0, import_node_path17.join)(PATHS.moduleDir, entry.name, "mod.toml");
31096
- if (!(0, import_node_fs24.existsSync)(manifestPath)) continue;
31344
+ const manifestPath = (0, import_node_path16.join)(PATHS.moduleDir, entry.name, "mod.toml");
31345
+ if (!(0, import_node_fs23.existsSync)(manifestPath)) continue;
31097
31346
  try {
31098
- const manifest = import_toml4.default.parse((0, import_node_fs24.readFileSync)(manifestPath, "utf-8"));
31347
+ const manifest = import_toml4.default.parse((0, import_node_fs23.readFileSync)(manifestPath, "utf-8"));
31099
31348
  const name = manifest.module?.name || entry.name;
31100
31349
  const defaults = manifest.module?.config?.defaults || {};
31101
31350
  const config = {
@@ -31109,7 +31358,7 @@ var ModuleHost = class {
31109
31358
  source: "installed",
31110
31359
  status: config.enabled === false ? "disabled" : "loaded",
31111
31360
  events: 0,
31112
- path: (0, import_node_path17.join)(PATHS.moduleDir, entry.name),
31361
+ path: (0, import_node_path16.join)(PATHS.moduleDir, entry.name),
31113
31362
  config
31114
31363
  };
31115
31364
  this.modules.set(name, hosted);
@@ -31124,7 +31373,7 @@ var ModuleHost = class {
31124
31373
  status: "error",
31125
31374
  events: 0,
31126
31375
  detail: `manifest load failed: ${String(err.message || err)}`,
31127
- path: (0, import_node_path17.join)(PATHS.moduleDir, entry.name)
31376
+ path: (0, import_node_path16.join)(PATHS.moduleDir, entry.name)
31128
31377
  });
31129
31378
  }
31130
31379
  }
@@ -31163,17 +31412,17 @@ var ModuleHost = class {
31163
31412
  }
31164
31413
  }
31165
31414
  installedEntrypoint(modulePath) {
31166
- const packageJson = (0, import_node_path17.join)(modulePath, "package.json");
31415
+ const packageJson = (0, import_node_path16.join)(modulePath, "package.json");
31167
31416
  const candidates = [];
31168
- if ((0, import_node_fs24.existsSync)(packageJson)) {
31417
+ if ((0, import_node_fs23.existsSync)(packageJson)) {
31169
31418
  try {
31170
- const pkg = JSON.parse((0, import_node_fs24.readFileSync)(packageJson, "utf-8"));
31171
- if (pkg.main) candidates.push((0, import_node_path17.join)(modulePath, pkg.main));
31419
+ const pkg = JSON.parse((0, import_node_fs23.readFileSync)(packageJson, "utf-8"));
31420
+ if (pkg.main) candidates.push((0, import_node_path16.join)(modulePath, pkg.main));
31172
31421
  } catch {
31173
31422
  }
31174
31423
  }
31175
- candidates.push((0, import_node_path17.join)(modulePath, "dist", "index.js"), (0, import_node_path17.join)(modulePath, "index.js"));
31176
- return candidates.find((candidate) => (0, import_node_fs24.existsSync)(candidate)) || null;
31424
+ candidates.push((0, import_node_path16.join)(modulePath, "dist", "index.js"), (0, import_node_path16.join)(modulePath, "index.js"));
31425
+ return candidates.find((candidate) => (0, import_node_fs23.existsSync)(candidate)) || null;
31177
31426
  }
31178
31427
  isThreatCrushModule(value) {
31179
31428
  return Boolean(
@@ -31445,7 +31694,6 @@ function slackChannel(webhookUrl) {
31445
31694
  }
31446
31695
 
31447
31696
  // src/daemon/workers/runs-worker.ts
31448
- var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
31449
31697
  var POLL_INTERVAL_MS = 3e4;
31450
31698
  var SCHEDULE_INTERVAL_MS = 12e4;
31451
31699
  var RunsWorker = class {
@@ -31458,7 +31706,7 @@ var RunsWorker = class {
31458
31706
  running = false;
31459
31707
  orgIds = [];
31460
31708
  async start() {
31461
- if (!isLoggedIn()) return;
31709
+ if (!hasSession()) return;
31462
31710
  try {
31463
31711
  await this.refreshOrgs();
31464
31712
  } catch {
@@ -31477,15 +31725,12 @@ var RunsWorker = class {
31477
31725
  this.bus.announceModule("runs-worker", "stopped");
31478
31726
  }
31479
31727
  async scheduleTick() {
31480
- if (!isLoggedIn()) return;
31728
+ if (!hasSession()) return;
31481
31729
  try {
31482
31730
  if (this.orgIds.length === 0) await this.refreshOrgs();
31483
31731
  for (const orgId of this.orgIds) {
31484
31732
  try {
31485
- await fetch(`${API_URL6}/api/orgs/${orgId}/schedules/tick`, {
31486
- method: "POST",
31487
- headers: authHeaders()
31488
- });
31733
+ await cloudFetch(`/api/orgs/${orgId}/schedules/tick`, { method: "POST" });
31489
31734
  } catch {
31490
31735
  }
31491
31736
  }
@@ -31494,7 +31739,7 @@ var RunsWorker = class {
31494
31739
  }
31495
31740
  async tick() {
31496
31741
  if (this.running) return;
31497
- if (!isLoggedIn()) return;
31742
+ if (!hasSession()) return;
31498
31743
  this.running = true;
31499
31744
  try {
31500
31745
  if (this.orgIds.length === 0) await this.refreshOrgs();
@@ -31510,16 +31755,15 @@ var RunsWorker = class {
31510
31755
  }
31511
31756
  }
31512
31757
  async refreshOrgs() {
31513
- const res = await fetch(`${API_URL6}/api/orgs`, { headers: authHeaders() });
31758
+ const res = await cloudFetch("/api/orgs");
31514
31759
  if (!res.ok) return;
31515
31760
  const data = await res.json();
31516
31761
  this.orgIds = (data.organizations || []).map((o) => o.id);
31517
31762
  }
31518
31763
  async claimOne(orgId) {
31519
31764
  try {
31520
- const res = await fetch(`${API_URL6}/api/orgs/${orgId}/runs/pending`, {
31765
+ const res = await cloudFetch(`/api/orgs/${orgId}/runs/pending`, {
31521
31766
  method: "POST",
31522
- headers: authHeaders(),
31523
31767
  body: JSON.stringify({ worker_id: workerId() })
31524
31768
  });
31525
31769
  if (!res.ok) return null;
@@ -31558,11 +31802,10 @@ var RunsWorker = class {
31558
31802
  }
31559
31803
  async finalize(orgId, claimed, result) {
31560
31804
  try {
31561
- await fetch(
31562
- `${API_URL6}/api/orgs/${orgId}/properties/${claimed.property_id}/runs/${claimed.id}`,
31805
+ await cloudFetch(
31806
+ `/api/orgs/${orgId}/properties/${claimed.property_id}/runs/${claimed.id}`,
31563
31807
  {
31564
31808
  method: "PATCH",
31565
- headers: authHeaders(),
31566
31809
  body: JSON.stringify({
31567
31810
  status: result.error ? "failed" : "succeeded",
31568
31811
  findings_count: result.findings.length,
@@ -31582,6 +31825,756 @@ var RunsWorker = class {
31582
31825
  }
31583
31826
  };
31584
31827
 
31828
+ // src/core/cloud-events.ts
31829
+ var import_node_crypto4 = require("crypto");
31830
+ var import_node_net3 = require("net");
31831
+ function currentLink() {
31832
+ if (!hasSession()) return null;
31833
+ const cfg = readCliConfig();
31834
+ if (!cfg.server_id || !cfg.server_org_id) return null;
31835
+ return { serverId: cfg.server_id, orgId: cfg.server_org_id };
31836
+ }
31837
+ var SEVERITY_RANK4 = {
31838
+ info: 0,
31839
+ low: 1,
31840
+ medium: 2,
31841
+ high: 3,
31842
+ critical: 4
31843
+ };
31844
+ var MAX_TITLE_CHARS = 300;
31845
+ var MAX_METADATA_BYTES = 16 * 1024;
31846
+ var MAX_STRING_CHARS = 1024;
31847
+ function jsonBytes(value) {
31848
+ try {
31849
+ return Buffer.byteLength(JSON.stringify(value) ?? "");
31850
+ } catch {
31851
+ return Infinity;
31852
+ }
31853
+ }
31854
+ function trimMetadata(meta) {
31855
+ const entries = [];
31856
+ for (const [key, value] of Object.entries(meta)) {
31857
+ if (value === void 0 || typeof value === "function") continue;
31858
+ const cut = typeof value === "string" && value.length > MAX_STRING_CHARS ? `${value.slice(0, MAX_STRING_CHARS)}\u2026` : value;
31859
+ if (jsonBytes(cut) === Infinity) continue;
31860
+ entries.push([key, cut]);
31861
+ }
31862
+ let out = Object.fromEntries(entries);
31863
+ let truncated = entries.length !== Object.keys(meta).length;
31864
+ if (jsonBytes(out) > MAX_METADATA_BYTES) {
31865
+ truncated = true;
31866
+ const bySize = [...entries].sort((a, b) => jsonBytes(a[1]) - jsonBytes(b[1]));
31867
+ while (bySize.length > 0 && jsonBytes({ ...Object.fromEntries(bySize), _truncated: true }) > MAX_METADATA_BYTES) {
31868
+ bySize.pop();
31869
+ }
31870
+ out = Object.fromEntries(bySize);
31871
+ }
31872
+ return truncated ? { ...out, _truncated: true } : out;
31873
+ }
31874
+ function str(value) {
31875
+ return typeof value === "string" && value ? value : void 0;
31876
+ }
31877
+ function detectionEvent(serverId, event) {
31878
+ const { rule_id, username, user, description, ...rest } = event.details ?? {};
31879
+ const title = event.module === "rule-engine" ? event.message.replace(/^\[DETECTION\]\s*/, "") : event.message;
31880
+ return {
31881
+ type: "detection",
31882
+ server_id: serverId,
31883
+ severity: event.severity,
31884
+ title: title.slice(0, MAX_TITLE_CHARS) || event.module,
31885
+ rule_id: str(rule_id) ?? event.module,
31886
+ description: str(description),
31887
+ source_ip: event.source_ip && (0, import_node_net3.isIP)(event.source_ip) ? event.source_ip : void 0,
31888
+ username: str(username) ?? str(user),
31889
+ raw_metadata: trimMetadata({ module: event.module, category: event.category, ...rest }),
31890
+ detected_at: event.timestamp.toISOString()
31891
+ };
31892
+ }
31893
+ function remediationEvent(serverId, event) {
31894
+ const d = event.details ?? {};
31895
+ if (d.action !== "block" && d.action !== "unblock") return null;
31896
+ if (d.origin === "cloud" || !event.source_ip) return null;
31897
+ const at = event.timestamp;
31898
+ const ttl = typeof d.ttl_seconds === "number" ? d.ttl_seconds : null;
31899
+ return {
31900
+ type: "remediation",
31901
+ server_id: serverId,
31902
+ event_id: (0, import_node_crypto4.randomUUID)(),
31903
+ action_type: d.action,
31904
+ target_value: event.source_ip,
31905
+ status: d.failed === true ? "failed" : "executed",
31906
+ rule_id: str(d.rule_id),
31907
+ reason: str(d.reason),
31908
+ error: str(d.error),
31909
+ dry_run: d.dry_run === true,
31910
+ executed_at: at.toISOString(),
31911
+ expires_at: d.action === "block" && ttl !== null && d.failed !== true ? new Date(at.getTime() + ttl * 1e3).toISOString() : null
31912
+ };
31913
+ }
31914
+ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date()) {
31915
+ return results.map((r) => ({
31916
+ type: "hardening_finding",
31917
+ server_id: serverId,
31918
+ finding_key: r.key,
31919
+ status: r.status,
31920
+ severity: r.severity,
31921
+ title: r.title.slice(0, MAX_TITLE_CHARS),
31922
+ recommendation: r.recommendation,
31923
+ observed_at: observedAt.toISOString()
31924
+ }));
31925
+ }
31926
+
31927
+ // src/daemon/workers/cloud-spool.ts
31928
+ var import_node_fs24 = require("fs");
31929
+ var import_promises = require("fs/promises");
31930
+ var import_node_path17 = require("path");
31931
+ var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
31932
+ var CloudSpool = class {
31933
+ constructor(path, limits = DEFAULT_SPOOL_LIMITS) {
31934
+ this.path = path;
31935
+ this.limits = limits;
31936
+ try {
31937
+ (0, import_node_fs24.mkdirSync)((0, import_node_path17.dirname)(path), { recursive: true });
31938
+ } catch {
31939
+ }
31940
+ this.load();
31941
+ }
31942
+ path;
31943
+ limits;
31944
+ lines = [];
31945
+ bytes = 0;
31946
+ pendingAppend = [];
31947
+ needsRewrite = false;
31948
+ scheduled = false;
31949
+ writes = Promise.resolve();
31950
+ droppedSinceReport = 0;
31951
+ get size() {
31952
+ return this.lines.length;
31953
+ }
31954
+ push(event) {
31955
+ const line = JSON.stringify(event);
31956
+ this.lines.push(line);
31957
+ this.bytes += Buffer.byteLength(line) + 1;
31958
+ this.pendingAppend.push(line);
31959
+ this.enforceLimits();
31960
+ this.schedule();
31961
+ }
31962
+ /** Up to `maxEvents` of the oldest events whose JSON fits in `maxBytes`. */
31963
+ peek(maxEvents, maxBytes) {
31964
+ const out = [];
31965
+ let bytes = 0;
31966
+ for (const line of this.lines) {
31967
+ if (out.length >= maxEvents) break;
31968
+ const size = Buffer.byteLength(line) + 1;
31969
+ if (out.length > 0 && bytes + size > maxBytes) break;
31970
+ bytes += size;
31971
+ out.push(JSON.parse(line));
31972
+ }
31973
+ return out;
31974
+ }
31975
+ /** Forget the `count` oldest events: they were delivered or will never be. */
31976
+ ack(count) {
31977
+ if (count <= 0) return;
31978
+ for (const line of this.lines.splice(0, count)) this.bytes -= Buffer.byteLength(line) + 1;
31979
+ this.needsRewrite = true;
31980
+ this.schedule();
31981
+ }
31982
+ /** Events dropped by the bound since the last call, for a single log line. */
31983
+ takeDropped() {
31984
+ const n = this.droppedSinceReport;
31985
+ this.droppedSinceReport = 0;
31986
+ return n;
31987
+ }
31988
+ /** Resolves once everything queued so far is on disk. */
31989
+ settled() {
31990
+ return this.writes;
31991
+ }
31992
+ enforceLimits() {
31993
+ let dropped = 0;
31994
+ while (this.lines.length > 0 && (this.lines.length > this.limits.maxEvents || this.bytes > this.limits.maxBytes)) {
31995
+ this.bytes -= Buffer.byteLength(this.lines.shift()) + 1;
31996
+ dropped++;
31997
+ }
31998
+ if (dropped > 0) {
31999
+ this.droppedSinceReport += dropped;
32000
+ this.needsRewrite = true;
32001
+ }
32002
+ }
32003
+ load() {
32004
+ let raw;
32005
+ try {
32006
+ raw = (0, import_node_fs24.readFileSync)(this.path, "utf-8");
32007
+ } catch {
32008
+ return;
32009
+ }
32010
+ let invalid = false;
32011
+ for (const line of raw.split("\n")) {
32012
+ if (!line.trim()) continue;
32013
+ try {
32014
+ JSON.parse(line);
32015
+ } catch {
32016
+ invalid = true;
32017
+ continue;
32018
+ }
32019
+ this.lines.push(line);
32020
+ this.bytes += Buffer.byteLength(line) + 1;
32021
+ }
32022
+ this.enforceLimits();
32023
+ if (invalid) this.needsRewrite = true;
32024
+ if (this.needsRewrite) this.schedule();
32025
+ }
32026
+ schedule() {
32027
+ if (this.scheduled) return;
32028
+ this.scheduled = true;
32029
+ this.writes = this.writes.then(async () => {
32030
+ this.scheduled = false;
32031
+ if (this.needsRewrite) {
32032
+ this.needsRewrite = false;
32033
+ this.pendingAppend = [];
32034
+ const body = this.lines.length > 0 ? `${this.lines.join("\n")}
32035
+ ` : "";
32036
+ const tmp = `${this.path}.tmp`;
32037
+ await (0, import_promises.writeFile)(tmp, body, { mode: 384 });
32038
+ await (0, import_promises.rename)(tmp, this.path);
32039
+ } else if (this.pendingAppend.length > 0) {
32040
+ const chunk = `${this.pendingAppend.join("\n")}
32041
+ `;
32042
+ this.pendingAppend = [];
32043
+ await (0, import_promises.appendFile)(this.path, chunk, { mode: 384 });
32044
+ }
32045
+ }).catch(() => {
32046
+ this.needsRewrite = true;
32047
+ });
32048
+ }
32049
+ };
32050
+
32051
+ // src/daemon/workers/cloud-sync.ts
32052
+ var MAX_BATCH_BYTES = 900 * 1024;
32053
+ var CloudSync = class {
32054
+ constructor(opts) {
32055
+ this.opts = opts;
32056
+ this.spool = new CloudSpool(opts.spoolPath, opts.spoolLimits ?? DEFAULT_SPOOL_LIMITS);
32057
+ this.batchSize = opts.batchSize ?? 100;
32058
+ this.flushMs = opts.flushMs ?? 1e4;
32059
+ this.heartbeatMs = opts.heartbeatMs ?? 6e4;
32060
+ this.baseBackoffMs = opts.baseBackoffMs ?? 5e3;
32061
+ this.maxBackoffMs = opts.maxBackoffMs ?? 3e5;
32062
+ }
32063
+ opts;
32064
+ spool;
32065
+ batchSize;
32066
+ flushMs;
32067
+ heartbeatMs;
32068
+ baseBackoffMs;
32069
+ maxBackoffMs;
32070
+ timers = [];
32071
+ flushing = null;
32072
+ backoffMs = 0;
32073
+ retryAt = 0;
32074
+ link = null;
32075
+ lastProblem = "";
32076
+ onEvent = (event) => this.capture(event);
32077
+ start() {
32078
+ this.link = currentLink();
32079
+ this.opts.bus.on("event", this.onEvent);
32080
+ const every = (ms, fn) => {
32081
+ const timer = setInterval(fn, ms);
32082
+ timer.unref?.();
32083
+ this.timers.push(timer);
32084
+ };
32085
+ every(this.flushMs, () => void this.flush());
32086
+ every(this.heartbeatMs, () => void this.heartbeat());
32087
+ void this.heartbeat();
32088
+ if (this.opts.runHardening) {
32089
+ const first = setTimeout(() => void this.reportHardening(), this.opts.hardeningDelayMs ?? 6e4);
32090
+ first.unref?.();
32091
+ this.timers.push(first);
32092
+ every(this.opts.hardeningIntervalMs ?? 864e5, () => void this.reportHardening());
32093
+ }
32094
+ if (this.spool.size > 0) {
32095
+ this.opts.log(`[cloud] ${this.spool.size} event(s) waiting in the spool from before`);
32096
+ void this.flush();
32097
+ }
32098
+ }
32099
+ async stop() {
32100
+ this.opts.bus.off("event", this.onEvent);
32101
+ for (const timer of this.timers) clearInterval(timer);
32102
+ this.timers = [];
32103
+ await this.spool.settled();
32104
+ }
32105
+ get queued() {
32106
+ return this.spool.size;
32107
+ }
32108
+ /** Queue hardening results for upload (the CLI posts its own directly). */
32109
+ enqueueFindings(results) {
32110
+ const link = this.refreshLink();
32111
+ if (!link) return 0;
32112
+ for (const event of findingEvents(link.serverId, results)) this.spool.push(event);
32113
+ this.kick();
32114
+ return results.length;
32115
+ }
32116
+ /**
32117
+ * Upload everything queued, oldest first, until the spool is empty or the
32118
+ * dashboard stops answering. Concurrent calls share one run.
32119
+ */
32120
+ flush() {
32121
+ this.flushing ??= this.drain().finally(() => {
32122
+ this.flushing = null;
32123
+ });
32124
+ return this.flushing;
32125
+ }
32126
+ capture(event) {
32127
+ const link = this.link;
32128
+ if (!link) return;
32129
+ let out = null;
32130
+ if (event.module === "firewall-rules") {
32131
+ out = remediationEvent(link.serverId, event);
32132
+ } 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]) {
32133
+ out = detectionEvent(link.serverId, event);
32134
+ }
32135
+ if (!out) return;
32136
+ this.spool.push(out);
32137
+ if (this.spool.size >= this.batchSize) this.kick();
32138
+ }
32139
+ /** Flush soon, off the caller's stack, unless we are backing off. */
32140
+ kick() {
32141
+ if (Date.now() < this.retryAt) return;
32142
+ setImmediate(() => void this.flush());
32143
+ }
32144
+ refreshLink() {
32145
+ this.link = currentLink();
32146
+ return this.link;
32147
+ }
32148
+ async drain() {
32149
+ this.reportDropped();
32150
+ if (Date.now() < this.retryAt) return;
32151
+ if (!this.refreshLink()) return;
32152
+ while (this.spool.size > 0) {
32153
+ const batch = this.spool.peek(this.batchSize, MAX_BATCH_BYTES);
32154
+ const outcome = await this.post(batch);
32155
+ if (outcome === "retry") return;
32156
+ this.spool.ack(batch.length);
32157
+ }
32158
+ }
32159
+ async post(events) {
32160
+ let res;
32161
+ try {
32162
+ res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events }) });
32163
+ } catch (err) {
32164
+ this.backOff(`dashboard unreachable (${err.message})`);
32165
+ return "retry";
32166
+ }
32167
+ if (res.ok) {
32168
+ const body = await res.json().catch(() => ({}));
32169
+ const rejected = body.rejected ?? [];
32170
+ if (rejected.length > 0) {
32171
+ const sample = rejected.slice(0, 3).map((r) => `#${r.index}: ${r.error}`).join("; ");
32172
+ this.opts.log(`[cloud] ingest rejected ${rejected.length} of ${events.length} event(s): ${sample}`);
32173
+ }
32174
+ if (this.backoffMs > 0 || this.lastProblem) {
32175
+ this.opts.log(`[cloud] dashboard reachable again; uploading ${this.spool.size} queued event(s)`);
32176
+ }
32177
+ this.backoffMs = 0;
32178
+ this.retryAt = 0;
32179
+ this.lastProblem = "";
32180
+ return "sent";
32181
+ }
32182
+ if (res.status === 401) {
32183
+ this.backOff("session expired and could not be refreshed \u2014 run `threatcrush login`");
32184
+ return "retry";
32185
+ }
32186
+ if (res.status === 429 || res.status >= 500) {
32187
+ this.backOff(`dashboard answered ${res.status}`);
32188
+ return "retry";
32189
+ }
32190
+ const detail = await res.text().catch(() => "");
32191
+ this.opts.log(`[cloud] ingest refused a batch (${res.status} ${detail.slice(0, 200)}); dropped ${events.length} event(s)`);
32192
+ return "dropped";
32193
+ }
32194
+ backOff(problem) {
32195
+ this.backoffMs = this.backoffMs === 0 ? this.baseBackoffMs : Math.min(this.backoffMs * 2, this.maxBackoffMs);
32196
+ this.retryAt = Date.now() + this.backoffMs;
32197
+ if (problem !== this.lastProblem) {
32198
+ this.opts.log(`[cloud] ${problem}; ${this.spool.size} event(s) spooled, retrying with backoff`);
32199
+ this.lastProblem = problem;
32200
+ }
32201
+ }
32202
+ reportDropped() {
32203
+ const dropped = this.spool.takeDropped();
32204
+ if (dropped > 0) {
32205
+ this.opts.log(`[cloud] spool full: dropped the ${dropped} oldest event(s)`);
32206
+ }
32207
+ }
32208
+ /**
32209
+ * Proof of life for the dashboard's online/offline badge. Not spooled: a
32210
+ * heartbeat replayed late would claim the box was up when nobody knew. A
32211
+ * heartbeat that gets through also ends a backoff early.
32212
+ */
32213
+ async heartbeat() {
32214
+ const link = this.refreshLink();
32215
+ if (!link) return;
32216
+ const event = {
32217
+ type: "heartbeat",
32218
+ server_id: link.serverId,
32219
+ version: this.opts.version,
32220
+ hostname: this.opts.hostname
32221
+ };
32222
+ try {
32223
+ const res = await cloudFetch("/api/ingest", { method: "POST", body: JSON.stringify({ events: [event] }) });
32224
+ if (res.ok && this.retryAt > 0) {
32225
+ this.retryAt = 0;
32226
+ void this.flush();
32227
+ }
32228
+ } catch {
32229
+ }
32230
+ }
32231
+ async reportHardening() {
32232
+ if (!this.refreshLink() || !this.opts.runHardening) return;
32233
+ try {
32234
+ const results = await this.opts.runHardening();
32235
+ const n = this.enqueueFindings(results);
32236
+ this.opts.log(`[cloud] hardening checks: queued ${n} finding(s) for upload`);
32237
+ } catch (err) {
32238
+ this.opts.log(`[cloud] hardening checks failed: ${err.message}`);
32239
+ }
32240
+ }
32241
+ };
32242
+
32243
+ // src/daemon/workers/remediation-consumer.ts
32244
+ var import_node_net6 = require("net");
32245
+
32246
+ // src/daemon/firewall/protected.ts
32247
+ var import_node_child_process7 = require("child_process");
32248
+ var import_node_net4 = require("net");
32249
+ var DEFAULT_PROTECTED = [
32250
+ "127.0.0.0/8",
32251
+ "::1/128",
32252
+ "10.0.0.0/8",
32253
+ "172.16.0.0/12",
32254
+ "192.168.0.0/16",
32255
+ "169.254.0.0/16",
32256
+ "fc00::/7",
32257
+ "fe80::/10"
32258
+ ];
32259
+ function ipToBytes(ip) {
32260
+ const version = (0, import_node_net4.isIP)(ip);
32261
+ if (version === 4) return v4ToBytes(ip);
32262
+ if (version === 6) return v6ToBytes(ip);
32263
+ return null;
32264
+ }
32265
+ function v4ToBytes(ip) {
32266
+ const parts = ip.split(".");
32267
+ if (parts.length !== 4) return null;
32268
+ const bytes = new Uint8Array(4);
32269
+ for (let i = 0; i < 4; i++) {
32270
+ const n = Number(parts[i]);
32271
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
32272
+ bytes[i] = n;
32273
+ }
32274
+ return bytes;
32275
+ }
32276
+ function v6ToBytes(ip) {
32277
+ const bare = ip.split("%")[0];
32278
+ const [headText, tailText] = bare.split("::", 2);
32279
+ const head = headText ? headText.split(":") : [];
32280
+ const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
32281
+ const groups = [];
32282
+ const pushGroup = (group) => {
32283
+ if (group.includes(".")) {
32284
+ const v4 = v4ToBytes(group);
32285
+ if (!v4) return false;
32286
+ groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
32287
+ return true;
32288
+ }
32289
+ if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
32290
+ groups.push(parseInt(group, 16));
32291
+ return true;
32292
+ };
32293
+ for (const group of head) if (!pushGroup(group)) return null;
32294
+ const headCount = groups.length;
32295
+ if (tail === null) {
32296
+ if (headCount !== 8) return null;
32297
+ } else {
32298
+ const tailGroups = [];
32299
+ const saved = groups.length;
32300
+ for (const group of tail) if (!pushGroup(group)) return null;
32301
+ tailGroups.push(...groups.splice(saved));
32302
+ const zeros = 8 - headCount - tailGroups.length;
32303
+ if (zeros < 0) return null;
32304
+ for (let i = 0; i < zeros; i++) groups.push(0);
32305
+ groups.push(...tailGroups);
32306
+ }
32307
+ if (groups.length !== 8) return null;
32308
+ const bytes = new Uint8Array(16);
32309
+ for (let i = 0; i < 8; i++) {
32310
+ bytes[i * 2] = groups[i] >> 8 & 255;
32311
+ bytes[i * 2 + 1] = groups[i] & 255;
32312
+ }
32313
+ return bytes;
32314
+ }
32315
+ function ipMatches(ip, entry) {
32316
+ const [network, prefixText] = entry.trim().split("/");
32317
+ const target = ipToBytes(ip);
32318
+ const base = ipToBytes(network);
32319
+ if (!target || !base || target.length !== base.length) return false;
32320
+ const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
32321
+ if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
32322
+ const wholeBytes = Math.floor(bits / 8);
32323
+ for (let i = 0; i < wholeBytes; i++) {
32324
+ if (target[i] !== base[i]) return false;
32325
+ }
32326
+ const remainder = bits % 8;
32327
+ if (remainder === 0) return true;
32328
+ const mask = 255 << 8 - remainder & 255;
32329
+ return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
32330
+ }
32331
+ function isProtected(ip, list) {
32332
+ return list.some((entry) => ipMatches(ip, entry));
32333
+ }
32334
+ function currentSshClient(env2 = process.env) {
32335
+ const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
32336
+ if (!source) return null;
32337
+ const ip = source.trim().split(/\s+/)[0];
32338
+ return ip && (0, import_node_net4.isIP)(ip) ? ip : null;
32339
+ }
32340
+ function establishedSshPeers() {
32341
+ const peers = /* @__PURE__ */ new Set();
32342
+ try {
32343
+ const out = (0, import_node_child_process7.execFileSync)("ss", ["-tnpH"], {
32344
+ encoding: "utf-8",
32345
+ stdio: ["ignore", "pipe", "ignore"],
32346
+ timeout: 3e3
32347
+ });
32348
+ for (const line of out.split("\n")) {
32349
+ if (!/users:\(\("sshd/.test(line)) continue;
32350
+ const parts = line.trim().split(/\s+/);
32351
+ const peer = parts[4];
32352
+ if (!peer) continue;
32353
+ const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
32354
+ if (ip && (0, import_node_net4.isIP)(ip)) peers.add(ip);
32355
+ }
32356
+ } catch {
32357
+ }
32358
+ return [...peers];
32359
+ }
32360
+ function defaultGateways() {
32361
+ const found = /* @__PURE__ */ new Set();
32362
+ for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
32363
+ try {
32364
+ const out = (0, import_node_child_process7.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
32365
+ for (const line of out.split("\n")) {
32366
+ const match = line.match(/\bvia\s+(\S+)/);
32367
+ if (match && (0, import_node_net4.isIP)(match[1])) found.add(match[1]);
32368
+ }
32369
+ } catch {
32370
+ }
32371
+ }
32372
+ return [...found];
32373
+ }
32374
+
32375
+ // src/daemon/workers/allowlist-sync.ts
32376
+ var import_node_net5 = require("net");
32377
+ function isAddressOrCidr(value) {
32378
+ const [network, prefix, extra] = value.split("/");
32379
+ const family = (0, import_node_net5.isIP)(network);
32380
+ if (family === 0 || extra !== void 0) return false;
32381
+ if (prefix === void 0) return true;
32382
+ if (!/^\d{1,3}$/.test(prefix)) return false;
32383
+ return Number(prefix) <= (family === 4 ? 32 : 128);
32384
+ }
32385
+ var AllowlistSync = class {
32386
+ constructor(manager, opts) {
32387
+ this.manager = manager;
32388
+ this.opts = opts;
32389
+ }
32390
+ manager;
32391
+ opts;
32392
+ timer = null;
32393
+ owned = /* @__PURE__ */ new Set();
32394
+ start() {
32395
+ this.timer = setInterval(() => void this.sync(), this.opts.intervalMs ?? 3e5);
32396
+ this.timer.unref?.();
32397
+ void this.sync();
32398
+ }
32399
+ stop() {
32400
+ if (this.timer) clearInterval(this.timer);
32401
+ this.timer = null;
32402
+ }
32403
+ async sync() {
32404
+ const link = currentLink();
32405
+ if (!link) return;
32406
+ let entries;
32407
+ try {
32408
+ const res = await cloudFetch(`/api/orgs/${link.orgId}/allowlists`);
32409
+ if (!res.ok) return;
32410
+ const data = await res.json();
32411
+ if (!Array.isArray(data.entries)) return;
32412
+ entries = data.entries;
32413
+ } catch {
32414
+ return;
32415
+ }
32416
+ const wanted = /* @__PURE__ */ new Set();
32417
+ for (const entry of entries) {
32418
+ if (entry.type !== "ip" && entry.type !== "cidr") continue;
32419
+ const value = String(entry.value ?? "").trim();
32420
+ if (isAddressOrCidr(value)) wanted.add(value);
32421
+ }
32422
+ const added = [];
32423
+ const protectedNow = new Set(this.manager.getProtected());
32424
+ for (const value of wanted) {
32425
+ if (this.owned.has(value) || protectedNow.has(value)) continue;
32426
+ this.manager.addToAllowlist(value);
32427
+ this.owned.add(value);
32428
+ added.push(value);
32429
+ }
32430
+ const removed = [];
32431
+ for (const value of this.owned) {
32432
+ if (wanted.has(value)) continue;
32433
+ this.manager.removeFromAllowlist(value);
32434
+ this.owned.delete(value);
32435
+ removed.push(value);
32436
+ }
32437
+ if (added.length > 0 || removed.length > 0) {
32438
+ this.opts.log(
32439
+ `[cloud] org allowlist: +${added.length} -${removed.length} (${[...added.map((v) => `+${v}`), ...removed.map((v) => `-${v}`)].slice(0, 10).join(" ")})`
32440
+ );
32441
+ }
32442
+ }
32443
+ };
32444
+
32445
+ // src/daemon/workers/remediation-consumer.ts
32446
+ var MAX_UNSENT = 200;
32447
+ var RemediationConsumer = class {
32448
+ constructor(manager, opts) {
32449
+ this.manager = manager;
32450
+ this.opts = opts;
32451
+ }
32452
+ manager;
32453
+ opts;
32454
+ timer = null;
32455
+ running = false;
32456
+ lastError = "";
32457
+ unsent = /* @__PURE__ */ new Map();
32458
+ start() {
32459
+ this.timer = setInterval(() => void this.tick(), this.opts.pollMs ?? 15e3);
32460
+ this.timer.unref?.();
32461
+ void this.tick();
32462
+ }
32463
+ stop() {
32464
+ if (this.timer) clearInterval(this.timer);
32465
+ this.timer = null;
32466
+ }
32467
+ async tick() {
32468
+ if (this.running) return;
32469
+ const link = currentLink();
32470
+ if (!link) return;
32471
+ this.running = true;
32472
+ try {
32473
+ for (const [id, { orgId, result }] of [...this.unsent]) {
32474
+ if (await this.report(orgId, id, result)) this.unsent.delete(id);
32475
+ }
32476
+ for (const action of await this.claim(link)) {
32477
+ const result = await this.execute(action);
32478
+ this.opts.log(
32479
+ `[cloud] dashboard ${action.action_type} ${action.target_value} \u2192 ${result.status}${result.dry_run ? " (dry-run)" : ""}${result.error ? `: ${result.error}` : ""}`
32480
+ );
32481
+ if (!await this.report(link.orgId, action.id, result) && this.unsent.size < MAX_UNSENT) {
32482
+ this.unsent.set(action.id, { orgId: link.orgId, result });
32483
+ }
32484
+ }
32485
+ } catch (err) {
32486
+ const message = err.message;
32487
+ if (message !== this.lastError) this.opts.log(`[cloud] remediation poll failed: ${message}`);
32488
+ this.lastError = message;
32489
+ } finally {
32490
+ this.running = false;
32491
+ }
32492
+ }
32493
+ async claim(link) {
32494
+ const res = await cloudFetch(
32495
+ `/api/orgs/${link.orgId}/servers/${link.serverId}/remediations/claim`,
32496
+ { method: "POST", body: "{}" }
32497
+ );
32498
+ this.lastError = "";
32499
+ if (!res.ok) return [];
32500
+ const data = await res.json().catch(() => ({}));
32501
+ return Array.isArray(data.actions) ? data.actions : [];
32502
+ }
32503
+ /** True once the dashboard has the result, or can never take it (409/404). */
32504
+ async report(orgId, id, result) {
32505
+ try {
32506
+ const res = await cloudFetch(`/api/orgs/${orgId}/remediations/${id}`, {
32507
+ method: "PATCH",
32508
+ body: JSON.stringify(result)
32509
+ });
32510
+ if (res.ok) return true;
32511
+ if (res.status === 409 || res.status === 404 || res.status === 400) {
32512
+ this.opts.log(`[cloud] dashboard would not take the result for ${id} (${res.status})`);
32513
+ return true;
32514
+ }
32515
+ return false;
32516
+ } catch {
32517
+ return false;
32518
+ }
32519
+ }
32520
+ async execute(action) {
32521
+ const executed_at = (/* @__PURE__ */ new Date()).toISOString();
32522
+ const failed = (error) => ({ status: "failed", error, executed_at });
32523
+ const target = String(action.target_value ?? "").trim();
32524
+ const meta = action.metadata ?? {};
32525
+ try {
32526
+ switch (action.action_type) {
32527
+ case "block": {
32528
+ if ((0, import_node_net6.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
32529
+ let ttlSeconds = this.manager.status().max_ban_seconds;
32530
+ if (action.expires_at) {
32531
+ const until = Date.parse(action.expires_at);
32532
+ if (Number.isNaN(until)) return failed(`unreadable expires_at: ${action.expires_at}`);
32533
+ ttlSeconds = Math.ceil((until - Date.now()) / 1e3);
32534
+ if (ttlSeconds <= 0) return failed("expired before this server picked it up");
32535
+ }
32536
+ const reason = typeof meta.reason === "string" && meta.reason ? meta.reason : "blocked from the ThreatCrush dashboard";
32537
+ const result = await this.manager.ban(target, reason, {
32538
+ ttlSeconds,
32539
+ source: "manual",
32540
+ origin: "cloud",
32541
+ ruleId: typeof meta.rule_id === "string" ? meta.rule_id : void 0
32542
+ });
32543
+ if (!result.ok) return failed(result.error ?? "block failed");
32544
+ return { status: "executed", dry_run: result.entry?.dry_run === true, executed_at };
32545
+ }
32546
+ case "unblock": {
32547
+ if ((0, import_node_net6.isIP)(target) === 0) return failed(`not an IP address: ${target}`);
32548
+ const wasBanned = this.manager.getBlocklist().some((b) => b.ip === target);
32549
+ const result = await this.manager.unban(target, {
32550
+ forget: true,
32551
+ origin: "cloud",
32552
+ reason: "unblocked from the ThreatCrush dashboard"
32553
+ });
32554
+ if (!result.ok && wasBanned) {
32555
+ return failed(result.error ?? "unblock failed");
32556
+ }
32557
+ return { status: "executed", dry_run: this.manager.status().dry_run, executed_at };
32558
+ }
32559
+ case "allowlist_add":
32560
+ if (!isAddressOrCidr(target)) return failed(`not an IP address or CIDR: ${target}`);
32561
+ this.manager.addToAllowlist(target);
32562
+ return { status: "executed", executed_at };
32563
+ case "allowlist_remove":
32564
+ if (DEFAULT_PROTECTED.includes(target)) {
32565
+ return failed(`${target} is a built-in protected range and cannot be removed`);
32566
+ }
32567
+ this.manager.removeFromAllowlist(target);
32568
+ return { status: "executed", executed_at };
32569
+ default:
32570
+ return failed(`unsupported action_type: ${action.action_type}`);
32571
+ }
32572
+ } catch (err) {
32573
+ return failed(err.message);
32574
+ }
32575
+ }
32576
+ };
32577
+
31585
32578
  // src/daemon/rules/engine.ts
31586
32579
  var RuleEngine = class {
31587
32580
  constructor(onDetection) {
@@ -32100,17 +33093,17 @@ function loadAllRules(customDir) {
32100
33093
  }
32101
33094
 
32102
33095
  // src/daemon/firewall/adapters.ts
32103
- var import_node_child_process7 = require("child_process");
33096
+ var import_node_child_process8 = require("child_process");
32104
33097
  var import_node_fs26 = require("fs");
32105
33098
  var import_node_path19 = require("path");
32106
- var import_node_net3 = require("net");
33099
+ var import_node_net7 = require("net");
32107
33100
  function assertValidFirewallIp(ip) {
32108
- if ((0, import_node_net3.isIP)(ip) !== 4) {
33101
+ if ((0, import_node_net7.isIP)(ip) !== 4) {
32109
33102
  throw new Error(`Invalid IPv4 address: ${ip}`);
32110
33103
  }
32111
33104
  }
32112
33105
  function assertBannableIp(ip) {
32113
- if ((0, import_node_net3.isIP)(ip) === 0) {
33106
+ if ((0, import_node_net7.isIP)(ip) === 0) {
32114
33107
  throw new Error(`Invalid IP address: ${ip}`);
32115
33108
  }
32116
33109
  }
@@ -32136,11 +33129,11 @@ var Fail2banAdapter = class {
32136
33129
  enforces = true;
32137
33130
  jailReady = false;
32138
33131
  isAvailable() {
32139
- const result = (0, import_node_child_process7.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
33132
+ const result = (0, import_node_child_process8.spawnSync)("fail2ban-client", ["ping"], { stdio: "pipe" });
32140
33133
  return result.status === 0;
32141
33134
  }
32142
33135
  client(args) {
32143
- return (0, import_node_child_process7.execFileSync)("fail2ban-client", args, {
33136
+ return (0, import_node_child_process8.execFileSync)("fail2ban-client", args, {
32144
33137
  encoding: "utf-8",
32145
33138
  stdio: ["ignore", "pipe", "pipe"]
32146
33139
  });
@@ -32212,7 +33205,7 @@ var Fail2banAdapter = class {
32212
33205
  const status = this.client(["status", this.jail]);
32213
33206
  const line = status.split("\n").find((l) => /Banned IP list:/i.test(l));
32214
33207
  if (!line) return [];
32215
- return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net3.isIP)(s) !== 0);
33208
+ return line.split(":").slice(1).join(":").trim().split(/\s+/).filter((s) => (0, import_node_net7.isIP)(s) !== 0);
32216
33209
  } catch {
32217
33210
  return [];
32218
33211
  }
@@ -32222,45 +33215,45 @@ var Fail2banAdapter = class {
32222
33215
  function parseBannedList(output) {
32223
33216
  const found = [];
32224
33217
  for (const match of output.matchAll(/['"]([^'"]+)['"]/g)) {
32225
- if ((0, import_node_net3.isIP)(match[1]) !== 0) found.push(match[1]);
33218
+ if ((0, import_node_net7.isIP)(match[1]) !== 0) found.push(match[1]);
32226
33219
  }
32227
33220
  if (found.length > 0) return found;
32228
- return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net3.isIP)(s) !== 0);
33221
+ return output.replace(/[[\],]/g, " ").split(/\s+/).filter((s) => (0, import_node_net7.isIP)(s) !== 0);
32229
33222
  }
32230
33223
  var NftablesAdapter = class {
32231
33224
  name = "nftables";
32232
33225
  table = "threatcrush";
32233
33226
  set = "blocklist";
32234
33227
  isAvailable() {
32235
- const result = (0, import_node_child_process7.spawnSync)("nft", ["--version"], { stdio: "pipe" });
33228
+ const result = (0, import_node_child_process8.spawnSync)("nft", ["--version"], { stdio: "pipe" });
32236
33229
  return result.status === 0;
32237
33230
  }
32238
33231
  ensureSetup() {
32239
33232
  try {
32240
- (0, import_node_child_process7.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
33233
+ (0, import_node_child_process8.execSync)(`nft list table inet ${this.table} 2>/dev/null`, { stdio: "pipe" });
32241
33234
  } catch {
32242
- (0, import_node_child_process7.execSync)(`nft add table inet ${this.table}`);
32243
- (0, import_node_child_process7.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
32244
- (0, import_node_child_process7.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
32245
- (0, import_node_child_process7.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
33235
+ (0, import_node_child_process8.execSync)(`nft add table inet ${this.table}`);
33236
+ (0, import_node_child_process8.execSync)(`nft add set inet ${this.table} ${this.set} '{ type ipv4_addr; flags timeout; }'`);
33237
+ (0, import_node_child_process8.execSync)(`nft add chain inet ${this.table} input '{ type filter hook input priority -1; policy accept; }'`);
33238
+ (0, import_node_child_process8.execSync)(`nft add rule inet ${this.table} input ip saddr @${this.set} drop`);
32246
33239
  }
32247
33240
  }
32248
33241
  async block(ip) {
32249
33242
  assertValidFirewallIp(ip);
32250
33243
  this.ensureSetup();
32251
- (0, import_node_child_process7.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
33244
+ (0, import_node_child_process8.execSync)(`nft add element inet ${this.table} ${this.set} '{ ${ip} }'`);
32252
33245
  }
32253
33246
  async unblock(ip) {
32254
33247
  assertValidFirewallIp(ip);
32255
33248
  try {
32256
- (0, import_node_child_process7.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
33249
+ (0, import_node_child_process8.execSync)(`nft delete element inet ${this.table} ${this.set} '{ ${ip} }'`);
32257
33250
  } catch {
32258
33251
  }
32259
33252
  }
32260
33253
  async isBlocked(ip) {
32261
33254
  assertValidFirewallIp(ip);
32262
33255
  try {
32263
- const output = (0, import_node_child_process7.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
33256
+ const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
32264
33257
  return output.includes(ip);
32265
33258
  } catch {
32266
33259
  return false;
@@ -32268,7 +33261,7 @@ var NftablesAdapter = class {
32268
33261
  }
32269
33262
  async listBlocked() {
32270
33263
  try {
32271
- const output = (0, import_node_child_process7.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
33264
+ const output = (0, import_node_child_process8.execSync)(`nft list set inet ${this.table} ${this.set}`, { encoding: "utf-8" });
32272
33265
  const match = output.match(/elements\s*=\s*\{([^}]*)\}/);
32273
33266
  if (!match) return [];
32274
33267
  return match[1].split(",").map((s) => s.trim().split(/\s/)[0]).filter(Boolean);
@@ -32281,34 +33274,34 @@ var IptablesAdapter = class {
32281
33274
  name = "iptables";
32282
33275
  chain = "THREATCRUSH";
32283
33276
  isAvailable() {
32284
- const result = (0, import_node_child_process7.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
33277
+ const result = (0, import_node_child_process8.spawnSync)("iptables", ["--version"], { stdio: "pipe" });
32285
33278
  return result.status === 0;
32286
33279
  }
32287
33280
  ensureChain() {
32288
33281
  try {
32289
- (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
33282
+ (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain} 2>/dev/null`, { stdio: "pipe" });
32290
33283
  } catch {
32291
- (0, import_node_child_process7.execSync)(`iptables -N ${this.chain}`);
32292
- (0, import_node_child_process7.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
33284
+ (0, import_node_child_process8.execSync)(`iptables -N ${this.chain}`);
33285
+ (0, import_node_child_process8.execSync)(`iptables -I INPUT 1 -j ${this.chain}`);
32293
33286
  }
32294
33287
  }
32295
33288
  async block(ip) {
32296
33289
  assertValidFirewallIp(ip);
32297
33290
  this.ensureChain();
32298
33291
  if (await this.isBlocked(ip)) return;
32299
- (0, import_node_child_process7.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
33292
+ (0, import_node_child_process8.execSync)(`iptables -A ${this.chain} -s ${ip} -j DROP`);
32300
33293
  }
32301
33294
  async unblock(ip) {
32302
33295
  assertValidFirewallIp(ip);
32303
33296
  try {
32304
- (0, import_node_child_process7.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
33297
+ (0, import_node_child_process8.execSync)(`iptables -D ${this.chain} -s ${ip} -j DROP`);
32305
33298
  } catch {
32306
33299
  }
32307
33300
  }
32308
33301
  async isBlocked(ip) {
32309
33302
  assertValidFirewallIp(ip);
32310
33303
  try {
32311
- const output = (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
33304
+ const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
32312
33305
  return output.includes(ip);
32313
33306
  } catch {
32314
33307
  return false;
@@ -32316,7 +33309,7 @@ var IptablesAdapter = class {
32316
33309
  }
32317
33310
  async listBlocked() {
32318
33311
  try {
32319
- const output = (0, import_node_child_process7.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
33312
+ const output = (0, import_node_child_process8.execSync)(`iptables -n -L ${this.chain}`, { encoding: "utf-8" });
32320
33313
  const ips = [];
32321
33314
  for (const line of output.split("\n")) {
32322
33315
  const match = line.match(/DROP\s+all\s+--\s+(\d+\.\d+\.\d+\.\d+)/);
@@ -32373,139 +33366,10 @@ function detectFirewallAdapter(backend = "auto") {
32373
33366
 
32374
33367
  // src/daemon/firewall/remediation.ts
32375
33368
  var import_node_fs27 = require("fs");
32376
- var import_node_net5 = require("net");
33369
+ var import_node_net8 = require("net");
32377
33370
  init_paths();
32378
33371
  init_backoff();
32379
33372
 
32380
- // src/daemon/firewall/protected.ts
32381
- var import_node_child_process8 = require("child_process");
32382
- var import_node_net4 = require("net");
32383
- var DEFAULT_PROTECTED = [
32384
- "127.0.0.0/8",
32385
- "::1/128",
32386
- "10.0.0.0/8",
32387
- "172.16.0.0/12",
32388
- "192.168.0.0/16",
32389
- "169.254.0.0/16",
32390
- "fc00::/7",
32391
- "fe80::/10"
32392
- ];
32393
- function ipToBytes(ip) {
32394
- const version = (0, import_node_net4.isIP)(ip);
32395
- if (version === 4) return v4ToBytes(ip);
32396
- if (version === 6) return v6ToBytes(ip);
32397
- return null;
32398
- }
32399
- function v4ToBytes(ip) {
32400
- const parts = ip.split(".");
32401
- if (parts.length !== 4) return null;
32402
- const bytes = new Uint8Array(4);
32403
- for (let i = 0; i < 4; i++) {
32404
- const n = Number(parts[i]);
32405
- if (!Number.isInteger(n) || n < 0 || n > 255) return null;
32406
- bytes[i] = n;
32407
- }
32408
- return bytes;
32409
- }
32410
- function v6ToBytes(ip) {
32411
- const bare = ip.split("%")[0];
32412
- const [headText, tailText] = bare.split("::", 2);
32413
- const head = headText ? headText.split(":") : [];
32414
- const tail = tailText !== void 0 ? tailText ? tailText.split(":") : [] : null;
32415
- const groups = [];
32416
- const pushGroup = (group) => {
32417
- if (group.includes(".")) {
32418
- const v4 = v4ToBytes(group);
32419
- if (!v4) return false;
32420
- groups.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);
32421
- return true;
32422
- }
32423
- if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return false;
32424
- groups.push(parseInt(group, 16));
32425
- return true;
32426
- };
32427
- for (const group of head) if (!pushGroup(group)) return null;
32428
- const headCount = groups.length;
32429
- if (tail === null) {
32430
- if (headCount !== 8) return null;
32431
- } else {
32432
- const tailGroups = [];
32433
- const saved = groups.length;
32434
- for (const group of tail) if (!pushGroup(group)) return null;
32435
- tailGroups.push(...groups.splice(saved));
32436
- const zeros = 8 - headCount - tailGroups.length;
32437
- if (zeros < 0) return null;
32438
- for (let i = 0; i < zeros; i++) groups.push(0);
32439
- groups.push(...tailGroups);
32440
- }
32441
- if (groups.length !== 8) return null;
32442
- const bytes = new Uint8Array(16);
32443
- for (let i = 0; i < 8; i++) {
32444
- bytes[i * 2] = groups[i] >> 8 & 255;
32445
- bytes[i * 2 + 1] = groups[i] & 255;
32446
- }
32447
- return bytes;
32448
- }
32449
- function ipMatches(ip, entry) {
32450
- const [network, prefixText] = entry.trim().split("/");
32451
- const target = ipToBytes(ip);
32452
- const base = ipToBytes(network);
32453
- if (!target || !base || target.length !== base.length) return false;
32454
- const bits = prefixText === void 0 ? base.length * 8 : Number(prefixText);
32455
- if (!Number.isInteger(bits) || bits < 0 || bits > base.length * 8) return false;
32456
- const wholeBytes = Math.floor(bits / 8);
32457
- for (let i = 0; i < wholeBytes; i++) {
32458
- if (target[i] !== base[i]) return false;
32459
- }
32460
- const remainder = bits % 8;
32461
- if (remainder === 0) return true;
32462
- const mask = 255 << 8 - remainder & 255;
32463
- return (target[wholeBytes] & mask) === (base[wholeBytes] & mask);
32464
- }
32465
- function isProtected(ip, list) {
32466
- return list.some((entry) => ipMatches(ip, entry));
32467
- }
32468
- function currentSshClient(env2 = process.env) {
32469
- const source = env2.SSH_CLIENT || env2.SSH_CONNECTION;
32470
- if (!source) return null;
32471
- const ip = source.trim().split(/\s+/)[0];
32472
- return ip && (0, import_node_net4.isIP)(ip) ? ip : null;
32473
- }
32474
- function establishedSshPeers() {
32475
- const peers = /* @__PURE__ */ new Set();
32476
- try {
32477
- const out = (0, import_node_child_process8.execFileSync)("ss", ["-tnpH"], {
32478
- encoding: "utf-8",
32479
- stdio: ["ignore", "pipe", "ignore"],
32480
- timeout: 3e3
32481
- });
32482
- for (const line of out.split("\n")) {
32483
- if (!/users:\(\("sshd/.test(line)) continue;
32484
- const parts = line.trim().split(/\s+/);
32485
- const peer = parts[4];
32486
- if (!peer) continue;
32487
- const ip = peer.slice(0, peer.lastIndexOf(":")).replace(/^\[|\]$/g, "");
32488
- if (ip && (0, import_node_net4.isIP)(ip)) peers.add(ip);
32489
- }
32490
- } catch {
32491
- }
32492
- return [...peers];
32493
- }
32494
- function defaultGateways() {
32495
- const found = /* @__PURE__ */ new Set();
32496
- for (const args of [["-4", "route", "show", "default"], ["-6", "route", "show", "default"]]) {
32497
- try {
32498
- const out = (0, import_node_child_process8.execFileSync)("ip", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
32499
- for (const line of out.split("\n")) {
32500
- const match = line.match(/\bvia\s+(\S+)/);
32501
- if (match && (0, import_node_net4.isIP)(match[1])) found.add(match[1]);
32502
- }
32503
- } catch {
32504
- }
32505
- }
32506
- return [...found];
32507
- }
32508
-
32509
33373
  // src/daemon/firewall/crawlers.ts
32510
33374
  var import_node_dns = require("dns");
32511
33375
  var CRAWLER_DOMAINS = ["googlebot.com", "google.com", "search.msn.com"];
@@ -32559,7 +33423,7 @@ var DEFAULT_CONFIG2 = {
32559
33423
  protect_current_ssh_client: true,
32560
33424
  spare_verified_crawlers: true
32561
33425
  };
32562
- var SEVERITY_RANK4 = {
33426
+ var SEVERITY_RANK5 = {
32563
33427
  info: 0,
32564
33428
  low: 1,
32565
33429
  medium: 2,
@@ -32582,6 +33446,7 @@ var RemediationManager = class {
32582
33446
  this.bus = bus2;
32583
33447
  this.verifyCrawler = verifyCrawler;
32584
33448
  this.config = { ...DEFAULT_CONFIG2, ...config };
33449
+ this.config.allowlist = [...this.config.allowlist];
32585
33450
  this.protectedList = [...DEFAULT_PROTECTED, ...this.config.allowlist];
32586
33451
  for (const gateway of defaultGateways()) this.protectedList.push(gateway);
32587
33452
  this.refreshSshProtection();
@@ -32622,8 +33487,8 @@ var RemediationManager = class {
32622
33487
  }
32623
33488
  async handleDetection(event) {
32624
33489
  if (!this.config.enabled) return;
32625
- const eventRank = SEVERITY_RANK4[event.severity] ?? 0;
32626
- const minRank = SEVERITY_RANK4[this.config.min_severity] ?? 3;
33490
+ const eventRank = SEVERITY_RANK5[event.severity] ?? 0;
33491
+ const minRank = SEVERITY_RANK5[this.config.min_severity] ?? 3;
32627
33492
  if (eventRank < minRank) return;
32628
33493
  if (isSuccessfulAuth(event.message)) return;
32629
33494
  if (event.details?.rule_id) {
@@ -32631,7 +33496,7 @@ var RemediationManager = class {
32631
33496
  if (remediation?.action !== "block") return;
32632
33497
  }
32633
33498
  const ip = event.source_ip;
32634
- if (!ip || (0, import_node_net5.isIP)(ip) === 0) return;
33499
+ if (!ip || (0, import_node_net8.isIP)(ip) === 0) return;
32635
33500
  if (this.isAllowlisted(ip)) return;
32636
33501
  if (this.blocklist.some((b) => b.ip === ip)) return;
32637
33502
  if (this.config.spare_verified_crawlers) {
@@ -32650,7 +33515,7 @@ var RemediationManager = class {
32650
33515
  * to `max_ban_seconds`.
32651
33516
  */
32652
33517
  async ban(ip, reason, opts = {}) {
32653
- if ((0, import_node_net5.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
33518
+ if ((0, import_node_net8.isIP)(ip) === 0) return { ok: false, error: `not an IP address: ${ip}` };
32654
33519
  if (this.isAllowlisted(ip)) {
32655
33520
  return { ok: false, error: `${ip} is protected and can never be blocked` };
32656
33521
  }
@@ -32671,7 +33536,15 @@ var RemediationManager = class {
32671
33536
  category: "system",
32672
33537
  severity: "medium",
32673
33538
  message: `Failed to block ${ip}: ${message}`,
32674
- source_ip: ip
33539
+ source_ip: ip,
33540
+ details: {
33541
+ action: "block",
33542
+ failed: true,
33543
+ error: message,
33544
+ reason,
33545
+ rule_id: opts.ruleId,
33546
+ origin: opts.origin
33547
+ }
32675
33548
  });
32676
33549
  return { ok: false, error: message };
32677
33550
  }
@@ -32704,6 +33577,8 @@ var RemediationManager = class {
32704
33577
  details: {
32705
33578
  action: "block",
32706
33579
  rule_id: opts.ruleId,
33580
+ reason,
33581
+ origin: opts.origin,
32707
33582
  dry_run: this.config.dry_run,
32708
33583
  ttl_seconds: ttl,
32709
33584
  strikes: strike,
@@ -32742,7 +33617,13 @@ var RemediationManager = class {
32742
33617
  severity: "info",
32743
33618
  message: `Unbanned ${ip}`,
32744
33619
  source_ip: ip,
32745
- details: { action: "unblock", forget: opts.forget === true }
33620
+ details: {
33621
+ action: "unblock",
33622
+ forget: opts.forget === true,
33623
+ reason: opts.reason,
33624
+ origin: opts.origin,
33625
+ dry_run: entry?.dry_run === true
33626
+ }
32746
33627
  });
32747
33628
  return { ok: true };
32748
33629
  }
@@ -32851,7 +33732,7 @@ var RemediationManager = class {
32851
33732
  const now = Date.now();
32852
33733
  this.refreshSshProtection();
32853
33734
  for (const entry of this.blocklist.filter((b) => b.expires_at <= now)) {
32854
- await this.unban(entry.ip);
33735
+ await this.unban(entry.ip, { reason: "ban expired" });
32855
33736
  }
32856
33737
  const pruned = pruneStrikes(this.strikes, now, this.config.strike_memory_seconds);
32857
33738
  if (Object.keys(pruned).length !== Object.keys(this.strikes).length) {
@@ -32977,6 +33858,15 @@ function readVersion2() {
32977
33858
  return "0.0.0";
32978
33859
  }
32979
33860
  }
33861
+ async function runHardeningChecks() {
33862
+ const { stdout } = await (0, import_node_util.promisify)(import_node_child_process9.execFile)(
33863
+ process.execPath,
33864
+ [(0, import_node_path20.join)(__dirname, "index.js"), "harden", "--json", "--no-upload"],
33865
+ { timeout: 12e4, maxBuffer: 4 * 1024 * 1024 }
33866
+ );
33867
+ const parsed = JSON.parse(stdout.slice(stdout.indexOf("{")));
33868
+ return Array.isArray(parsed.findings) ? parsed.findings : [];
33869
+ }
32980
33870
  function logLine(line) {
32981
33871
  try {
32982
33872
  (0, import_node_fs28.appendFileSync)(PATHS.logFile, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
@@ -33024,6 +33914,7 @@ async function runDaemon() {
33024
33914
  source_ip: detection.source_ip,
33025
33915
  details: {
33026
33916
  rule_id: detection.rule_id,
33917
+ description: detection.description,
33027
33918
  username: detection.username,
33028
33919
  ...detection.raw_metadata
33029
33920
  }
@@ -33061,6 +33952,31 @@ async function runDaemon() {
33061
33952
  } catch (err) {
33062
33953
  logLine(`[daemon] runs-worker failed to start: ${err.message}`);
33063
33954
  }
33955
+ let cloudSync = null;
33956
+ let remediationConsumer = null;
33957
+ let allowlistSync = null;
33958
+ if (config.cloud?.enabled === false) {
33959
+ logLine("[cloud] disabled by [cloud] enabled = false");
33960
+ } else {
33961
+ const minSeverity = config.cloud?.min_severity ?? "medium";
33962
+ cloudSync = new CloudSync({
33963
+ bus,
33964
+ version,
33965
+ hostname: (0, import_node_os8.hostname)(),
33966
+ minSeverity,
33967
+ spoolPath: (0, import_node_path20.join)(PATHS.stateDir, "cloud-spool.jsonl"),
33968
+ log: logLine,
33969
+ ruleModules: new Set(ruleEngine.getRules().flatMap((rule) => rule.source_types)),
33970
+ runHardening: runHardeningChecks
33971
+ });
33972
+ cloudSync.start();
33973
+ remediationConsumer = new RemediationConsumer(remediation, { log: logLine });
33974
+ remediationConsumer.start();
33975
+ allowlistSync = new AllowlistSync(remediation, { log: logLine });
33976
+ allowlistSync.start();
33977
+ const link = currentLink();
33978
+ 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");
33979
+ }
33064
33980
  const ipc = new IpcServer(version, moduleHost, remediation);
33065
33981
  await ipc.start();
33066
33982
  logLine(`[daemon] ipc listening on ${PATHS.socket}`);
@@ -33074,6 +33990,18 @@ async function runDaemon() {
33074
33990
  runsWorker.stop();
33075
33991
  } catch {
33076
33992
  }
33993
+ try {
33994
+ remediationConsumer?.stop();
33995
+ } catch {
33996
+ }
33997
+ try {
33998
+ allowlistSync?.stop();
33999
+ } catch {
34000
+ }
34001
+ try {
34002
+ await cloudSync?.stop();
34003
+ } catch {
34004
+ }
33077
34005
  try {
33078
34006
  await moduleHost.stop();
33079
34007
  } catch {
@@ -33156,7 +34084,7 @@ async function daemonStart() {
33156
34084
  }
33157
34085
  return;
33158
34086
  }
33159
- const child = (0, import_node_child_process9.spawn)(process.execPath, [DAEMON_ENTRY], {
34087
+ const child = (0, import_node_child_process10.spawn)(process.execPath, [DAEMON_ENTRY], {
33160
34088
  detached: true,
33161
34089
  stdio: ["ignore", out, err],
33162
34090
  env: { ...process.env, THREATCRUSH_DAEMON: "1" }
@@ -33207,7 +34135,9 @@ async function daemonStop() {
33207
34135
  }
33208
34136
  if (!await waitForExit(pid, 1e3)) {
33209
34137
  console.log(source_default.red(` \u2717 threatcrushd (pid ${pid}) is still running and could not be stopped.`));
33210
- console.log(source_default.dim(" It may be owned by another user \u2014 try `sudo threatcrush stop`.\n"));
34138
+ console.log(source_default.dim(isRoot2() ? ` Inspect it with \`ps -o pid,stat,user,cmd -p ${pid}\`.
34139
+ ` : " It may be owned by another user \u2014 try `sudo threatcrush stop`.\n"));
34140
+ process.exitCode = 1;
33211
34141
  return false;
33212
34142
  }
33213
34143
  removePidFile();
@@ -33241,7 +34171,7 @@ async function releaseStaleSocket() {
33241
34171
  }
33242
34172
 
33243
34173
  // src/commands/service.ts
33244
- var import_node_child_process10 = require("child_process");
34174
+ var import_node_child_process11 = require("child_process");
33245
34175
  var import_node_fs31 = require("fs");
33246
34176
  var import_node_path22 = require("path");
33247
34177
  var UNIT_PATH = "/etc/systemd/system/threatcrushd.service";
@@ -33262,7 +34192,7 @@ function resolveBinPath() {
33262
34192
  const arg = process.argv[1];
33263
34193
  if (arg && (0, import_node_fs31.existsSync)(arg)) return stableBinPath(arg);
33264
34194
  try {
33265
- return (0, import_node_child_process10.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
34195
+ return (0, import_node_child_process11.execSync)("command -v threatcrush", { encoding: "utf-8" }).trim();
33266
34196
  } catch {
33267
34197
  return "threatcrush";
33268
34198
  }
@@ -33283,22 +34213,33 @@ function looksLikeNodeScript(path) {
33283
34213
  function execStartCommand(binPath, nodePath, isNodeScript) {
33284
34214
  return isNodeScript ? `${nodePath} ${binPath} daemon` : `${binPath} daemon`;
33285
34215
  }
34216
+ function nodeVersionDir(path) {
34217
+ const m = path.match(
34218
+ /^(.*?\/(?:installs\/node(?:js)?|\.nvm\/versions\/node|node-versions|tools\/image\/node|n\/versions\/node)\/[^/]+)\//
34219
+ );
34220
+ return m ? m[1] : null;
34221
+ }
34222
+ function systemdUnavailableReason(o) {
34223
+ if (!o.hasSystemctl) return "systemctl is not installed";
34224
+ if (!o.booted) return "systemd is not running as the init system (common in containers and WSL)";
34225
+ return null;
34226
+ }
33286
34227
  function isRoot3() {
33287
34228
  return typeof process.getuid === "function" && process.getuid() === 0;
33288
34229
  }
33289
34230
  function reexecWithSudo(args) {
33290
- if ((0, import_node_child_process10.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
34231
+ if ((0, import_node_child_process11.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
33291
34232
  console.log(source_default.dim(" This needs root \u2014 sudo will ask for your password.\n"));
33292
34233
  const bin = resolveBinPath();
33293
34234
  const argv = looksLikeNodeScript(bin) ? [stableNodePath(process.execPath), bin, ...args] : [bin, ...args];
33294
- const result = (0, import_node_child_process10.spawnSync)("sudo", argv, { stdio: "inherit" });
34235
+ const result = (0, import_node_child_process11.spawnSync)("sudo", argv, { stdio: "inherit" });
33295
34236
  return result.status === 0;
33296
34237
  }
33297
34238
  function callerHome() {
33298
34239
  const user = process.env.SUDO_USER;
33299
34240
  if (!user) return null;
33300
34241
  try {
33301
- const line = (0, import_node_child_process10.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
34242
+ const line = (0, import_node_child_process11.execSync)(`getent passwd ${user}`, { encoding: "utf-8" }).trim();
33302
34243
  const home = line.split(":")[5];
33303
34244
  return home && (0, import_node_fs31.existsSync)(home) ? home : null;
33304
34245
  } catch {
@@ -33333,39 +34274,65 @@ function stopUserModeDaemon() {
33333
34274
  }
33334
34275
  }
33335
34276
  function unitIsActive() {
33336
- const result = (0, import_node_child_process10.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
34277
+ const result = (0, import_node_child_process11.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT_NAME], { stdio: "pipe" });
33337
34278
  return result.status === 0;
33338
34279
  }
33339
34280
  async function installServiceCommand() {
33340
34281
  banner();
33341
34282
  if (process.platform !== "linux") {
33342
34283
  console.log(source_default.yellow(" systemd install is only supported on Linux."));
34284
+ process.exitCode = 1;
34285
+ return;
34286
+ }
34287
+ const noSystemd = systemdUnavailableReason({
34288
+ hasSystemctl: (0, import_node_child_process11.spawnSync)("sh", ["-c", "command -v systemctl"], { stdio: "ignore" }).status === 0,
34289
+ booted: (0, import_node_fs31.existsSync)("/run/systemd/system")
34290
+ });
34291
+ if (noSystemd) {
34292
+ console.log(source_default.red(` \u2717 systemd isn't available here: ${noSystemd}.`));
34293
+ console.log(source_default.dim(" Nothing was installed. Run the daemon without a service manager instead:"));
34294
+ console.log(source_default.dim(` ${source_default.white("threatcrush start")} # background daemon`));
34295
+ console.log(source_default.dim(` ${source_default.white("threatcrush daemon")} # foreground, e.g. as a container's command`));
34296
+ console.log();
34297
+ process.exitCode = 1;
33343
34298
  return;
33344
34299
  }
33345
34300
  if (!isRoot3()) {
33346
34301
  if (reexecWithSudo(["install-service"])) return;
33347
34302
  console.log(source_default.red(" Needs root and sudo is unavailable or was declined."));
33348
34303
  console.log(source_default.dim(" Run this as root: threatcrush install-service"));
34304
+ process.exitCode = 1;
33349
34305
  return;
33350
34306
  }
33351
- const binPath = resolveBinPath();
33352
- const exec = execStartCommand(
33353
- binPath,
33354
- stableNodePath(process.execPath),
33355
- looksLikeNodeScript(binPath)
33356
- );
34307
+ let binPath = resolveBinPath();
34308
+ const isNodeScript = looksLikeNodeScript(binPath);
34309
+ let nodePath = stableNodePath(process.execPath);
34310
+ if (isNodeScript && nodeVersionDir(binPath)) {
34311
+ binPath = (0, import_node_fs31.realpathSync)(binPath);
34312
+ nodePath = process.execPath;
34313
+ }
34314
+ const exec = execStartCommand(binPath, nodePath, isNodeScript);
33357
34315
  const unit = resolveTemplate().replace("{{BIN_PATH}} daemon", exec).replace("{{BIN_PATH}}", binPath);
33358
34316
  (0, import_node_fs31.writeFileSync)(UNIT_PATH, unit, { mode: 420 });
33359
34317
  console.log(source_default.green(` \u2713 Installed unit file: ${UNIT_PATH}`));
33360
34318
  console.log(source_default.dim(` ExecStart=${exec}`));
34319
+ const nodeDir = nodeVersionDir(nodePath);
34320
+ const pinnedTo = nodeVersionDir(binPath) ?? (isNodeScript && nodeDir && !nodeDir.endsWith("/latest") ? nodeDir : null);
34321
+ if (pinnedTo) {
34322
+ console.log(source_default.yellow(` ! ExecStart depends on the Node install in ${pinnedTo}.`));
34323
+ console.log(source_default.dim(" Upgrading or removing that Node version breaks the service. Afterwards, reinstall"));
34324
+ console.log(source_default.dim(` threatcrush for the new Node and re-run ${source_default.white("threatcrush install-service")}.`));
34325
+ console.log(source_default.dim(" Installing with a system Node (/usr/bin/node or /usr/local/bin/node) avoids this."));
34326
+ }
33361
34327
  ensureSystemDirs();
33362
34328
  stopUserModeDaemon();
33363
34329
  try {
33364
- (0, import_node_child_process10.execSync)("systemctl daemon-reload", { stdio: "inherit" });
33365
- (0, import_node_child_process10.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
34330
+ (0, import_node_child_process11.execSync)("systemctl daemon-reload", { stdio: "inherit" });
34331
+ (0, import_node_child_process11.execSync)(`systemctl enable --now ${DAEMON_UNIT_NAME}`, { stdio: "inherit" });
33366
34332
  } catch (err) {
33367
34333
  console.log(source_default.yellow(` ! systemctl error: ${err.message}`));
33368
34334
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
34335
+ process.exitCode = 1;
33369
34336
  return;
33370
34337
  }
33371
34338
  if (unitIsActive()) {
@@ -33375,6 +34342,7 @@ async function installServiceCommand() {
33375
34342
  } else {
33376
34343
  console.log(source_default.yellow(" ! The unit is installed but did not come up."));
33377
34344
  console.log(source_default.dim(` Logs: journalctl -u ${DAEMON_UNIT_NAME} -n 50`));
34345
+ process.exitCode = 1;
33378
34346
  }
33379
34347
  console.log();
33380
34348
  }
@@ -33402,7 +34370,7 @@ function ensureSystemDirs() {
33402
34370
  try {
33403
34371
  if (groupWritable && admGid !== null) {
33404
34372
  (0, import_node_fs31.chmodSync)(path, sticky ? 1533 : 509);
33405
- (0, import_node_child_process10.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
34373
+ (0, import_node_child_process11.execSync)(`chgrp adm ${path}`, { stdio: "ignore" });
33406
34374
  } else {
33407
34375
  (0, import_node_fs31.chmodSync)(path, 493);
33408
34376
  }
@@ -33424,22 +34392,22 @@ async function uninstallServiceCommand() {
33424
34392
  return;
33425
34393
  }
33426
34394
  try {
33427
- (0, import_node_child_process10.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
34395
+ (0, import_node_child_process11.execSync)("systemctl stop threatcrushd.service", { stdio: "inherit" });
33428
34396
  } catch {
33429
34397
  }
33430
34398
  try {
33431
- (0, import_node_child_process10.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
34399
+ (0, import_node_child_process11.execSync)("systemctl disable threatcrushd.service", { stdio: "inherit" });
33432
34400
  } catch {
33433
34401
  }
33434
34402
  try {
33435
34403
  if ((0, import_node_fs31.existsSync)(UNIT_PATH)) {
33436
- (0, import_node_child_process10.execSync)(`rm -f ${UNIT_PATH}`);
34404
+ (0, import_node_child_process11.execSync)(`rm -f ${UNIT_PATH}`);
33437
34405
  console.log(source_default.green(` \u2713 Removed unit file: ${UNIT_PATH}`));
33438
34406
  }
33439
34407
  } catch {
33440
34408
  }
33441
34409
  try {
33442
- (0, import_node_child_process10.execSync)("systemctl daemon-reload", { stdio: "inherit" });
34410
+ (0, import_node_child_process11.execSync)("systemctl daemon-reload", { stdio: "inherit" });
33443
34411
  } catch {
33444
34412
  }
33445
34413
  console.log(source_default.green(" \u2713 threatcrushd service removed."));
@@ -33533,9 +34501,9 @@ function welcomeCommand() {
33533
34501
  var import_node_fs32 = require("fs");
33534
34502
  var import_node_path23 = require("path");
33535
34503
  var import_node_readline6 = __toESM(require("readline"));
33536
- var API_URL7 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
34504
+ var API_URL5 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
33537
34505
  var KINDS = ["url", "api", "domain", "ip", "repo"];
33538
- function prompt2(question) {
34506
+ function prompt(question) {
33539
34507
  const rl = import_node_readline6.default.createInterface({ input: process.stdin, output: process.stdout });
33540
34508
  return new Promise((resolve5) => rl.question(question, (answer) => {
33541
34509
  rl.close();
@@ -33556,7 +34524,7 @@ async function resolveOrgId(orgFlag) {
33556
34524
  }
33557
34525
  let orgs = [];
33558
34526
  try {
33559
- const res = await fetch(`${API_URL7}/api/orgs`, { headers: authHeaders() });
34527
+ const res = await fetch(`${API_URL5}/api/orgs`, { headers: authHeaders() });
33560
34528
  if (!res.ok) {
33561
34529
  console.log(source_default.red(` Failed to list organizations (${res.status})
33562
34530
  `));
@@ -33586,7 +34554,7 @@ async function resolveOrgId(orgFlag) {
33586
34554
  }
33587
34555
  async function fetchProperties(orgId, kind) {
33588
34556
  const qs = kind ? `?kind=${kind}` : "";
33589
- const res = await fetch(`${API_URL7}/api/orgs/${orgId}/properties${qs}`, { headers: authHeaders() });
34557
+ const res = await fetch(`${API_URL5}/api/orgs/${orgId}/properties${qs}`, { headers: authHeaders() });
33590
34558
  if (!res.ok) {
33591
34559
  const body = await res.json().catch(() => ({ error: res.statusText }));
33592
34560
  console.log(source_default.red(` ${body.error || "Failed to load properties"}
@@ -33667,7 +34635,7 @@ async function propertiesAddCommand(name, target, opts) {
33667
34635
  };
33668
34636
  const spinner = ora({ text: `Creating property ${source_default.white(name)}...`, color: "green" }).start();
33669
34637
  try {
33670
- const res = await fetch(`${API_URL7}/api/orgs/${resolved.org.id}/properties`, {
34638
+ const res = await fetch(`${API_URL5}/api/orgs/${resolved.org.id}/properties`, {
33671
34639
  method: "POST",
33672
34640
  headers: authHeaders(),
33673
34641
  body: JSON.stringify(body)
@@ -33697,13 +34665,13 @@ async function propertiesRemoveCommand(nameOrId, opts) {
33697
34665
  return;
33698
34666
  }
33699
34667
  if (!opts.yes) {
33700
- const answer = (await prompt2(source_default.yellow(` Delete property "${match.name}"? (y/N): `))).toLowerCase();
34668
+ const answer = (await prompt(source_default.yellow(` Delete property "${match.name}"? (y/N): `))).toLowerCase();
33701
34669
  if (answer !== "y" && answer !== "yes") {
33702
34670
  console.log(source_default.dim(" Cancelled.\n"));
33703
34671
  return;
33704
34672
  }
33705
34673
  }
33706
- const res = await fetch(`${API_URL7}/api/orgs/${resolved.org.id}/properties/${match.id}`, {
34674
+ const res = await fetch(`${API_URL5}/api/orgs/${resolved.org.id}/properties/${match.id}`, {
33707
34675
  method: "DELETE",
33708
34676
  headers: authHeaders()
33709
34677
  });
@@ -33718,7 +34686,7 @@ async function propertiesRemoveCommand(nameOrId, opts) {
33718
34686
  }
33719
34687
  async function enqueueRun(orgId, propertyId, type, trigger = "cli") {
33720
34688
  try {
33721
- const res = await fetch(`${API_URL7}/api/orgs/${orgId}/properties/${propertyId}/runs`, {
34689
+ const res = await fetch(`${API_URL5}/api/orgs/${orgId}/properties/${propertyId}/runs`, {
33722
34690
  method: "POST",
33723
34691
  headers: authHeaders(),
33724
34692
  body: JSON.stringify({ type, trigger })
@@ -33731,7 +34699,7 @@ async function enqueueRun(orgId, propertyId, type, trigger = "cli") {
33731
34699
  }
33732
34700
  async function finalizeRun(orgId, propertyId, runId, result) {
33733
34701
  try {
33734
- await fetch(`${API_URL7}/api/orgs/${orgId}/properties/${propertyId}/runs/${runId}`, {
34702
+ await fetch(`${API_URL5}/api/orgs/${orgId}/properties/${propertyId}/runs/${runId}`, {
33735
34703
  method: "PATCH",
33736
34704
  headers: authHeaders(),
33737
34705
  body: JSON.stringify({
@@ -33835,7 +34803,7 @@ async function propertiesRunsCommand(opts) {
33835
34803
  let total = 0;
33836
34804
  for (const prop of propsToShow) {
33837
34805
  const res = await fetch(
33838
- `${API_URL7}/api/orgs/${resolved.org.id}/properties/${prop.id}/runs?limit=${limit}`,
34806
+ `${API_URL5}/api/orgs/${resolved.org.id}/properties/${prop.id}/runs?limit=${limit}`,
33839
34807
  { headers: authHeaders() }
33840
34808
  );
33841
34809
  if (!res.ok) continue;
@@ -33939,7 +34907,7 @@ async function propertiesImportCommand(filePath, opts) {
33939
34907
  continue;
33940
34908
  }
33941
34909
  try {
33942
- const res = await fetch(`${API_URL7}/api/orgs/${resolved.org.id}/properties`, {
34910
+ const res = await fetch(`${API_URL5}/api/orgs/${resolved.org.id}/properties`, {
33943
34911
  method: "POST",
33944
34912
  headers: authHeaders(),
33945
34913
  body: JSON.stringify({
@@ -34057,10 +35025,10 @@ async function rulesCommand(opts) {
34057
35025
 
34058
35026
  // src/commands/harden.ts
34059
35027
  var import_node_fs33 = require("fs");
34060
- var import_node_child_process11 = require("child_process");
35028
+ var import_node_child_process12 = require("child_process");
34061
35029
  function tryExec(cmd) {
34062
35030
  try {
34063
- return (0, import_node_child_process11.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
35031
+ return (0, import_node_child_process12.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
34064
35032
  } catch {
34065
35033
  return null;
34066
35034
  }
@@ -34398,6 +35366,39 @@ function computeScore(results) {
34398
35366
  if (maxScore === 0) return 100;
34399
35367
  return Math.max(0, Math.round((maxScore - deductions) / maxScore * 100));
34400
35368
  }
35369
+ async function uploadFindings(results, json) {
35370
+ const say = (line) => json ? console.error(line) : console.log(line);
35371
+ const link = currentLink();
35372
+ if (!link) {
35373
+ if (!json) say(source_default.gray(" Not linked to the dashboard; run `threatcrush servers link` to upload findings.\n"));
35374
+ return;
35375
+ }
35376
+ let res;
35377
+ try {
35378
+ res = await cloudFetch("/api/ingest", {
35379
+ method: "POST",
35380
+ body: JSON.stringify({ events: findingEvents(link.serverId, results) })
35381
+ });
35382
+ } catch (err) {
35383
+ say(source_default.yellow(` ! Could not upload findings: ${err.message}
35384
+ `));
35385
+ return;
35386
+ }
35387
+ if (!res.ok) {
35388
+ const detail = await res.text().catch(() => "");
35389
+ say(source_default.yellow(` ! Upload refused (${res.status}) ${detail.slice(0, 200)}
35390
+ `));
35391
+ return;
35392
+ }
35393
+ const body = await res.json().catch(() => ({}));
35394
+ const accepted = body.accepted?.findings ?? results.length;
35395
+ say(source_default.green(` \u2713 Uploaded ${accepted} of ${results.length} findings to server ${link.serverId}`));
35396
+ for (const r of results) say(source_default.gray(` ${r.status.padEnd(4)} ${r.key}`));
35397
+ for (const rejected of body.rejected ?? []) {
35398
+ say(source_default.yellow(` rejected ${results[rejected.index]?.key ?? `#${rejected.index}`}: ${rejected.error}`));
35399
+ }
35400
+ say("");
35401
+ }
34401
35402
  async function hardenCommand(opts) {
34402
35403
  if (!opts.json) {
34403
35404
  banner();
@@ -34409,6 +35410,7 @@ async function hardenCommand(opts) {
34409
35410
  if (spinner) spinner.succeed("Hardening scan complete\n");
34410
35411
  if (opts.json) {
34411
35412
  console.log(JSON.stringify({ score, findings: results }, null, 2));
35413
+ if (opts.upload !== false) await uploadFindings(results, true);
34412
35414
  return;
34413
35415
  }
34414
35416
  const scoreColor = score >= 80 ? source_default.green : score >= 60 ? source_default.yellow : source_default.red;
@@ -34446,6 +35448,7 @@ async function hardenCommand(opts) {
34446
35448
  console.log(source_default.gray(" " + "\u2500".repeat(60)));
34447
35449
  console.log(` ${source_default.white.bold(`${results.length} checks:`)} ${source_default.green(`${passes.length} pass`)} ${source_default.yellow(`${warns.length} warn`)} ${source_default.red(`${fails.length} fail`)}`);
34448
35450
  console.log();
35451
+ if (opts.upload !== false) await uploadFindings(results, false);
34449
35452
  }
34450
35453
 
34451
35454
  // src/commands/firewall.ts
@@ -34592,11 +35595,11 @@ async function allowlistCommand(opts) {
34592
35595
  init_paths();
34593
35596
 
34594
35597
  // src/upgrade.ts
34595
- var import_node_child_process12 = require("child_process");
35598
+ var import_node_child_process13 = require("child_process");
34596
35599
  var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
34597
35600
  var defaultRunner = (cmd) => {
34598
35601
  try {
34599
- return (0, import_node_child_process12.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
35602
+ return (0, import_node_child_process13.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
34600
35603
  } catch {
34601
35604
  return null;
34602
35605
  }
@@ -34708,28 +35711,28 @@ ${source_default.green(" \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u25
34708
35711
  ${source_default.green(" \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D")}
34709
35712
  ${source_default.dim(" C R U S H")}
34710
35713
  `;
34711
- var API_URL8 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
35714
+ var API_URL6 = process.env.THREATCRUSH_API_URL || "https://threatcrush.com";
34712
35715
  var PKG_NAME = "@profullstack/threatcrush";
34713
35716
  var DESKTOP_PKG_NAME = "@profullstack/threatcrush-desktop";
34714
- var INSTALL_CONFIG_PATH = (0, import_node_path24.join)((0, import_node_os8.homedir)(), ".threatcrush", "install.json");
35717
+ var INSTALL_CONFIG_PATH = (0, import_node_path24.join)((0, import_node_os9.homedir)(), ".threatcrush", "install.json");
34715
35718
  function detectPackageManager() {
34716
35719
  try {
34717
- const npmGlobal = (0, import_node_child_process13.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
35720
+ const npmGlobal = (0, import_node_child_process14.execSync)("npm ls -g --depth=0 --json 2>/dev/null", { encoding: "utf-8" });
34718
35721
  if (npmGlobal.includes(PKG_NAME)) return "npm";
34719
35722
  } catch {
34720
35723
  }
34721
35724
  try {
34722
- (0, import_node_child_process13.execSync)("pnpm --version", { stdio: "pipe" });
35725
+ (0, import_node_child_process14.execSync)("pnpm --version", { stdio: "pipe" });
34723
35726
  return "pnpm";
34724
35727
  } catch {
34725
35728
  }
34726
35729
  try {
34727
- (0, import_node_child_process13.execSync)("yarn --version", { stdio: "pipe" });
35730
+ (0, import_node_child_process14.execSync)("yarn --version", { stdio: "pipe" });
34728
35731
  return "yarn";
34729
35732
  } catch {
34730
35733
  }
34731
35734
  try {
34732
- (0, import_node_child_process13.execSync)("bun --version", { stdio: "pipe" });
35735
+ (0, import_node_child_process14.execSync)("bun --version", { stdio: "pipe" });
34733
35736
  return "bun";
34734
35737
  } catch {
34735
35738
  }
@@ -34744,7 +35747,7 @@ function readInstallConfig() {
34744
35747
  }
34745
35748
  function packageLooksInstalled(pm, pkgName) {
34746
35749
  try {
34747
- const output = (0, import_node_child_process13.execSync)(globalListCommand(pm, pkgName), {
35750
+ const output = (0, import_node_child_process14.execSync)(globalListCommand(pm, pkgName), {
34748
35751
  encoding: "utf-8",
34749
35752
  stdio: ["pipe", "pipe", "pipe"]
34750
35753
  });
@@ -34847,14 +35850,14 @@ async function promoteUnprivilegedDaemon() {
34847
35850
  function restartSystemdDaemon() {
34848
35851
  const asRoot = typeof process.getuid === "function" && process.getuid() === 0;
34849
35852
  const argv = asRoot ? ["systemctl", "restart", DAEMON_UNIT] : ["sudo", "systemctl", "restart", DAEMON_UNIT];
34850
- if (!asRoot && (0, import_node_child_process13.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
35853
+ if (!asRoot && (0, import_node_child_process14.spawnSync)("sudo", ["--version"], { stdio: "pipe" }).status !== 0) return false;
34851
35854
  const [cmd, ...args] = argv;
34852
- if ((0, import_node_child_process13.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
34853
- return (0, import_node_child_process13.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
35855
+ if ((0, import_node_child_process14.spawnSync)(cmd, args, { stdio: "inherit" }).status !== 0) return false;
35856
+ return (0, import_node_child_process14.spawnSync)("systemctl", ["is-active", "--quiet", DAEMON_UNIT], { stdio: "pipe" }).status === 0;
34854
35857
  }
34855
35858
  function execQuiet(cmd) {
34856
35859
  try {
34857
- return (0, import_node_child_process13.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
35860
+ return (0, import_node_child_process14.execSync)(cmd, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] });
34858
35861
  } catch {
34859
35862
  return null;
34860
35863
  }
@@ -34869,7 +35872,7 @@ program2.name("threatcrush").description(
34869
35872
  ${source_default.dim("Website:")} ${source_default.green("https://threatcrush.com")}
34870
35873
  ${source_default.dim("GitHub:")} ${source_default.green("https://github.com/profullstack/threatcrush")}
34871
35874
  ${source_default.dim("npm:")} ${source_default.green("https://www.npmjs.com/package/@profullstack/threatcrush")}
34872
- ${source_default.dim("License:")} ${source_default.green("$499 lifetime")} (or $399 with referral)
35875
+ ${source_default.dim("Pricing:")} Contact us for a quote: ${source_default.green("https://threatcrush.com/hire")}
34873
35876
 
34874
35877
  ${source_default.dim("Examples:")}
34875
35878
  ${source_default.green("$")} threatcrush monitor ${source_default.dim("# Real-time monitoring")}
@@ -34903,8 +35906,8 @@ program2.command("monitor").description("Watch nginx, auth and syslog for attack
34903
35906
  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) => {
34904
35907
  await monitorCommand({ tui: true, demo: opts.demo });
34905
35908
  });
34906
- program2.command("init").description("Sign in, auto-detect services, and configure ThreatCrush").action(async () => {
34907
- await initCommand();
35909
+ 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) => {
35910
+ await initCommand({ yes: opts.yes, offline: opts.offline });
34908
35911
  });
34909
35912
  program2.command("login").description("Log in to your threatcrush.com account").option("-e, --email <email>", "Email to log in with").action(async (opts) => {
34910
35913
  await loginCommand({ email: opts.email });
@@ -34962,7 +35965,7 @@ program2.command("status").description("Show daemon status and loaded modules").
34962
35965
  program2.command("rules").description("Manage detection rules").argument("[action]", "list | show", "list").argument("[id]", "Rule ID (for show)").action(async (action, id) => {
34963
35966
  await rulesCommand({ action, id });
34964
35967
  });
34965
- program2.command("harden").description("Run hardening security scan").option("--json", "Output results as JSON").action(async (opts) => {
35968
+ program2.command("harden").description("Run hardening security scan").option("--json", "Output results as JSON").option("--no-upload", "Do not upload findings to the dashboard (uploaded when this machine is linked)").action(async (opts) => {
34966
35969
  await hardenCommand(opts);
34967
35970
  });
34968
35971
  program2.command("block").description("Block an IP address via the firewall").argument("<ip>", "IP address to block").option("--ttl <duration>", "Block duration (e.g. 1h, 30m, 1d)").action(async (ip, opts) => {
@@ -35009,42 +36012,7 @@ program2.command("logs").description("Tail daemon logs").action(async () => {
35009
36012
  console.log(source_default.green(` Tailing ${logPath}...
35010
36013
  `));
35011
36014
  console.log(source_default.gray(" Press Ctrl+C to stop\n"));
35012
- (0, import_node_child_process13.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
35013
- });
35014
- program2.command("activate").description("Activate your license key").action(async () => {
35015
- console.log(LOGO2);
35016
- const rl = import_readline.default.createInterface({ input: process.stdin, output: process.stdout });
35017
- const key = await new Promise((resolve5) => {
35018
- rl.question(source_default.green(" Enter your ThreatCrush license key: "), (answer) => {
35019
- rl.close();
35020
- resolve5(answer.trim());
35021
- });
35022
- });
35023
- if (!key) {
35024
- console.log(source_default.red("\n No key provided.\n"));
35025
- return;
35026
- }
35027
- console.log(source_default.dim("\n Activating license..."));
35028
- try {
35029
- const res = await fetch(`${API_URL8}/api/auth/activate`, {
35030
- method: "POST",
35031
- headers: { "Content-Type": "application/json" },
35032
- body: JSON.stringify({ license_key: key })
35033
- });
35034
- const result = await res.json();
35035
- if (!res.ok) {
35036
- console.log(source_default.red(`
35037
- \u2717 Activation failed: ${result.error || "Unknown error"}
35038
- `));
35039
- return;
35040
- }
35041
- console.log(source_default.green("\n \u2713 License activated successfully!\n"));
35042
- console.log(source_default.dim(` Status: ${String(result.status ?? "active")}`));
35043
- console.log(source_default.dim(` Expires: ${String(result.expires ?? "never")}
35044
- `));
35045
- } catch {
35046
- console.log(source_default.red("\n \u2717 Activation failed. Check your connection and try again.\n"));
35047
- }
36015
+ (0, import_node_child_process14.execSync)(`tail -f ${logPath}`, { stdio: "inherit" });
35048
36016
  });
35049
36017
  program2.command("update").description("Update ThreatCrush CLI and installed bundle").option("--cli", "Update CLI only").option("--modules", "Update modules only").option("--desktop", "Update desktop app too").action(async (opts) => {
35050
36018
  console.log(LOGO2);
@@ -35056,7 +36024,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
35056
36024
  for (const cmd of commands2) {
35057
36025
  console.log(source_default.green(` \u2192 ${cmd}
35058
36026
  `));
35059
- (0, import_node_child_process13.execSync)(cmd, { stdio: "inherit" });
36027
+ (0, import_node_child_process14.execSync)(cmd, { stdio: "inherit" });
35060
36028
  }
35061
36029
  console.log(source_default.green("\n \u2713 Modules updated successfully!\n"));
35062
36030
  await reportIfStillStale();
@@ -35081,7 +36049,7 @@ program2.command("update").description("Update ThreatCrush CLI and installed bun
35081
36049
  for (const cmd of commands) {
35082
36050
  console.log(source_default.green(` \u2192 ${cmd}
35083
36051
  `));
35084
- (0, import_node_child_process13.execSync)(cmd, { stdio: "inherit" });
36052
+ (0, import_node_child_process14.execSync)(cmd, { stdio: "inherit" });
35085
36053
  }
35086
36054
  console.log(source_default.green("\n \u2713 ThreatCrush updated successfully!\n"));
35087
36055
  if (installMode === "desktop") {
@@ -35132,7 +36100,7 @@ program2.command("remove").description("Uninstall ThreatCrush and the installed
35132
36100
  for (const cmd of commands) {
35133
36101
  console.log(source_default.green(` \u2192 ${cmd}
35134
36102
  `));
35135
- (0, import_node_child_process13.execSync)(cmd, { stdio: "inherit" });
36103
+ (0, import_node_child_process14.execSync)(cmd, { stdio: "inherit" });
35136
36104
  }
35137
36105
  console.log(source_default.green("\n \u2713 ThreatCrush has been uninstalled.\n"));
35138
36106
  console.log(source_default.dim(" We're sorry to see you go! \u{1F44B}\n"));
@@ -35157,7 +36125,7 @@ var storeCmd = program2.command("store").description("Browse the module marketpl
35157
36125
  console.log(source_default.green(" Module Marketplace\n"));
35158
36126
  console.log(source_default.dim(" Loading available modules..."));
35159
36127
  try {
35160
- const res = await fetch(`${API_URL8}/api/modules`);
36128
+ const res = await fetch(`${API_URL6}/api/modules`);
35161
36129
  if (!res.ok) {
35162
36130
  console.log(source_default.red(` \u2717 Failed to load modules: ${res.statusText}
35163
36131
  `));
@@ -35184,7 +36152,7 @@ storeCmd.command("search <query>").description("Search for modules in the store"
35184
36152
  console.log(source_default.green(` Searching for "${query}"...
35185
36153
  `));
35186
36154
  try {
35187
- const res = await fetch(`${API_URL8}/api/modules?q=${encodeURIComponent(query)}`);
36155
+ const res = await fetch(`${API_URL6}/api/modules?q=${encodeURIComponent(query)}`);
35188
36156
  if (!res.ok) {
35189
36157
  console.log(source_default.red(` \u2717 Search failed: ${res.statusText}
35190
36158
  `));
@@ -35209,7 +36177,7 @@ storeCmd.command("search <query>").description("Search for modules in the store"
35209
36177
  });
35210
36178
  storeCmd.command("publish <url>").description("Publish a module from a git URL or web URL").action(async (url) => {
35211
36179
  console.log(LOGO2);
35212
- const configPath = (0, import_node_path24.join)((0, import_node_os8.homedir)(), ".threatcrush", "config.json");
36180
+ const configPath = (0, import_node_path24.join)((0, import_node_os9.homedir)(), ".threatcrush", "config.json");
35213
36181
  let email = "";
35214
36182
  try {
35215
36183
  const config = JSON.parse((0, import_node_fs34.readFileSync)(configPath, "utf-8"));
@@ -35229,7 +36197,7 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
35229
36197
  return;
35230
36198
  }
35231
36199
  try {
35232
- const dir = (0, import_node_path24.join)((0, import_node_os8.homedir)(), ".threatcrush");
36200
+ const dir = (0, import_node_path24.join)((0, import_node_os9.homedir)(), ".threatcrush");
35233
36201
  if (!(0, import_node_fs34.existsSync)(dir)) (0, import_node_fs34.mkdirSync)(dir, { recursive: true });
35234
36202
  (0, import_node_fs34.writeFileSync)(configPath, JSON.stringify({ email }, null, 2));
35235
36203
  console.log(source_default.dim(` Saved email to ${configPath}`));
@@ -35241,7 +36209,7 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
35241
36209
  `));
35242
36210
  let meta;
35243
36211
  try {
35244
- const res = await fetch(`${API_URL8}/api/modules/fetch-meta`, {
36212
+ const res = await fetch(`${API_URL6}/api/modules/fetch-meta`, {
35245
36213
  method: "POST",
35246
36214
  headers: { "Content-Type": "application/json" },
35247
36215
  body: JSON.stringify({ url, git_url: url })
@@ -35287,7 +36255,7 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
35287
36255
  }
35288
36256
  console.log(source_default.dim("\n Publishing..."));
35289
36257
  try {
35290
- const res = await fetch(`${API_URL8}/api/modules`, {
36258
+ const res = await fetch(`${API_URL6}/api/modules`, {
35291
36259
  method: "POST",
35292
36260
  headers: { "Content-Type": "application/json" },
35293
36261
  body: JSON.stringify({
@@ -35307,8 +36275,8 @@ storeCmd.command("publish <url>").description("Publish a module from a git URL o
35307
36275
  const mod = result.module;
35308
36276
  const slug = mod?.slug || meta.name;
35309
36277
  console.log(source_default.green(`
35310
- \u2713 Module published!`));
35311
- console.log(source_default.dim(` ${API_URL8}/store/${slug}
36278
+ \u2713 Module submitted for review. It appears in the store once approved.`));
36279
+ console.log(source_default.dim(` ${API_URL6}/store/${slug}
35312
36280
  `));
35313
36281
  } catch (err) {
35314
36282
  console.log(source_default.red(`
@@ -35334,6 +36302,12 @@ var serversCmd = program2.command("servers").alias("server").alias("srv").descri
35334
36302
  serversCmd.command("list").alias("ls").option("--org <slug>", "Filter by organization slug").description("List servers in current organization").action(async (opts) => {
35335
36303
  await serversCommand({ action: "list", org: opts.org });
35336
36304
  });
36305
+ serversCmd.command("link").option("--org <id|slug>", "Organization to link into (default: current org, or your only org)").option("--name <name>", "Name for the server on the dashboard (default: hostname)").description("Link this machine to the dashboard so the daemon reports to it").action(async (opts) => {
36306
+ await serversCommand({ action: "link", org: opts.org, name: opts.name });
36307
+ });
36308
+ serversCmd.command("unlink").description("Stop this machine reporting to the dashboard").action(async () => {
36309
+ await serversCommand({ action: "unlink" });
36310
+ });
35337
36311
  var propsCmd = program2.command("properties").alias("props").alias("targets").description("Manage scan/pentest targets (properties) in the current org").action(async () => {
35338
36312
  await propertiesListCommand({});
35339
36313
  });