@profullstack/threatcrush 0.13.56 → 0.13.57

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/README.md CHANGED
@@ -229,6 +229,17 @@ enabled = true # false: the daemon neither reports to nor takes actio
229
229
  min_severity = "medium" # info | low | medium | high | critical
230
230
  ```
231
231
 
232
+ ### Every machine, with what it costs
233
+
234
+ The Fleet panel lists linked daemons. To also list the machines that do not run one, and what each box costs a month, upload an [OpenDevice](https://logicsrc.com/docs/opendevice) inventory (org owners and admins):
235
+
236
+ ```bash
237
+ threatcrush fleet import opendevice.json # or an https:// URL; --org <slug> to pick the org
238
+ threatcrush fleet cost # per-box $/mo, provider, daemon status and the total
239
+ ```
240
+
241
+ Devices are matched to linked servers by hostname, name or IP. A device with no daemon shows as "no agent"; a cost the inventory does not state shows as "unstated" and is never guessed. Totals are per currency, never converted. `GET /api/fleet/costs` returns the recurring costs in the shape CoinPay imports.
242
+
232
243
  ## Automatic updates
233
244
 
234
245
  The daemon keeps itself on the latest release. About every 6 hours (plus up to an hour of jitter, so a fleet does not restart in step) it asks the npm registry for `latest`. When a newer version has been published for at least 2 hours, and is on the same major version, it installs it and restarts onto it. The update shows in the live feed as an info event (`auto-update`).
package/dist/index.js CHANGED
@@ -36459,9 +36459,9 @@ function urlAuthority(text) {
36459
36459
  return found ? found[1] : null;
36460
36460
  }
36461
36461
  function requestHostIsConstant(line2, fileText) {
36462
- const call = /(?:urlopen|requests\.(?:get|request|head)|httpx\.get)\s*\(\s*([A-Za-z_]\w*)\s*[,)]/.exec(line2);
36463
- if (!call) return false;
36464
- const assignment = new RegExp(String.raw`^[ \t]*${call[1]}[ \t]*=[ \t]*(.+)$`, "gm");
36462
+ const call2 = /(?:urlopen|requests\.(?:get|request|head)|httpx\.get)\s*\(\s*([A-Za-z_]\w*)\s*[,)]/.exec(line2);
36463
+ if (!call2) return false;
36464
+ const assignment = new RegExp(String.raw`^[ \t]*${call2[1]}[ \t]*=[ \t]*(.+)$`, "gm");
36465
36465
  const values = [...fileText.matchAll(assignment)].map((m) => m[1]);
36466
36466
  if (!values.length) return false;
36467
36467
  return values.every((value) => {
@@ -36484,7 +36484,7 @@ function hasSafeRedirectValue(line2, fileText) {
36484
36484
  }
36485
36485
  const equals = candidate.indexOf("=", at + declaration.length);
36486
36486
  const initializer = candidate.slice(equals + 1);
36487
- if (equals !== -1 && ["safeRedirectPath(", "safeRedirectUrl(", "safeRedirectURL("].some((call) => initializer.includes(call))) {
36487
+ if (equals !== -1 && ["safeRedirectPath(", "safeRedirectUrl(", "safeRedirectURL("].some((call2) => initializer.includes(call2))) {
36488
36488
  return true;
36489
36489
  }
36490
36490
  }
@@ -40914,6 +40914,102 @@ async function invitesCommand(action = "list", arg, f = fetch) {
40914
40914
  }
40915
40915
  }
40916
40916
 
40917
+ // src/commands/fleet.ts
40918
+ var import_promises = require("fs/promises");
40919
+ init_cli_config();
40920
+ async function call(path2, init = {}) {
40921
+ const res = await cloudFetch(path2, init);
40922
+ const body = await res.json().catch(() => ({}));
40923
+ return { ok: res.ok, status: res.status, body };
40924
+ }
40925
+ function fail2(message) {
40926
+ console.error(source_default.red(` ${message}`));
40927
+ process.exitCode = 1;
40928
+ }
40929
+ async function resolveOrg(wanted) {
40930
+ const r = await call("/api/orgs");
40931
+ if (r.status === 401) {
40932
+ fail2("Not signed in. Run `threatcrush login` first.");
40933
+ return null;
40934
+ }
40935
+ if (!r.ok) {
40936
+ fail2(String(r.body.error ?? `Could not list organizations (${r.status})`));
40937
+ return null;
40938
+ }
40939
+ const orgs = r.body.organizations ?? [];
40940
+ const pick = wanted ?? readCliConfig().current_org_id;
40941
+ if (pick) {
40942
+ const org = orgs.find((o) => o.id === pick || o.slug === pick);
40943
+ if (!org) fail2(`No organization "${pick}". See: threatcrush orgs list`);
40944
+ return org ?? null;
40945
+ }
40946
+ const admin = orgs.filter((o) => o.user_role === "owner" || o.user_role === "admin");
40947
+ if (admin.length === 1) return admin[0];
40948
+ fail2(admin.length === 0 ? "You administer no organization. Create one: threatcrush orgs create <name>" : `Pick an organization: --org <slug> (${admin.map((o) => o.slug).join(", ")})`);
40949
+ return null;
40950
+ }
40951
+ async function readInventorySource(source, f = fetch) {
40952
+ if (/^https?:\/\//i.test(source)) {
40953
+ const res = await f(source, { signal: AbortSignal.timeout(3e4) });
40954
+ if (!res.ok) throw new Error(`${source} answered ${res.status}`);
40955
+ return res.text();
40956
+ }
40957
+ return (0, import_promises.readFile)(source, "utf-8");
40958
+ }
40959
+ async function fleetImportCommand(source, opts = {}) {
40960
+ let text;
40961
+ try {
40962
+ text = await readInventorySource(source);
40963
+ JSON.parse(text);
40964
+ } catch (err) {
40965
+ return fail2(`Could not read ${source}: ${err instanceof Error ? err.message : String(err)}`);
40966
+ }
40967
+ const org = await resolveOrg(opts.org);
40968
+ if (!org) return;
40969
+ const r = await call(`/api/orgs/${encodeURIComponent(org.id)}/inventory`, { method: "PUT", body: text });
40970
+ const warnings = r.body.warnings ?? [];
40971
+ if (!r.ok) {
40972
+ fail2(String(r.body.error ?? `Import failed (${r.status})`));
40973
+ for (const e of r.body.errors ?? []) console.error(source_default.red(` - ${e}`));
40974
+ for (const w of warnings) console.error(source_default.yellow(` ! ${w}`));
40975
+ return;
40976
+ }
40977
+ const cost = r.body.cost;
40978
+ console.log(source_default.green(` Imported ${cost.devices} device${cost.devices === 1 ? "" : "s"} into ${org.name} (/${org.slug}).`));
40979
+ console.log(` Monthly: ${source_default.bold(formatTotal(cost.monthly))} (${cost.counted} counted, ${cost.unstated.length} unstated)`);
40980
+ if (cost.unstated.length > 0) console.log(source_default.dim(` Unstated: ${cost.unstated.join(", ")}`));
40981
+ for (const w of warnings) console.log(source_default.yellow(` ! ${w}`));
40982
+ console.log(source_default.dim(" See it: threatcrush fleet cost, or threatcrush.com/dashboard"));
40983
+ }
40984
+ async function fleetCostCommand(opts = {}) {
40985
+ const r = await call("/api/fleet");
40986
+ if (r.status === 401) return fail2("Not signed in. Run `threatcrush login` first.");
40987
+ if (!r.ok) return fail2(String(r.body.error ?? `Could not load the fleet (${r.status})`));
40988
+ if (opts.json) {
40989
+ console.log(JSON.stringify(r.body, null, 2));
40990
+ return;
40991
+ }
40992
+ const servers = r.body.servers ?? [];
40993
+ const s = r.body.summary;
40994
+ if (s.inventories === 0) {
40995
+ console.log(source_default.yellow(" No OpenDevice inventory yet. Import one: threatcrush fleet import <file|url>"));
40996
+ }
40997
+ const width = Math.max(6, ...servers.map((x) => x.name.length));
40998
+ console.log(source_default.dim(` ${"SERVER".padEnd(width)} ${"STATUS".padEnd(8)} ${"PROVIDER".padEnd(14)} $/MO`));
40999
+ for (const x of servers) {
41000
+ const status = x.connection === "online" ? source_default.green("online ") : x.connection === "no-agent" ? source_default.dim("no agent") : source_default.red("offline ");
41001
+ const cost = !x.device ? source_default.dim("\u2014") : x.device.monthly.amount == null ? source_default.dim(x.device.monthly_label) : x.device.monthly_label;
41002
+ console.log(` ${x.name.padEnd(width)} ${status} ${(x.device?.provider ?? "\u2014").slice(0, 14).padEnd(14)} ${cost}`);
41003
+ }
41004
+ console.log();
41005
+ console.log(` Total: ${source_default.bold(s.monthly_total_label)}/mo (${s.cost_counted} counted, ${s.cost_unstated} unstated)`);
41006
+ console.log(source_default.dim(` ${s.installs} with a daemon, ${s.no_agent} without${s.no_agent > 0 ? " (install: threatcrush login && threatcrush servers link)" : ""}`));
41007
+ }
41008
+ function formatTotal(monthly) {
41009
+ const parts = Object.entries(monthly ?? {}).map(([cur, n]) => new Intl.NumberFormat("en-US", { style: "currency", currency: cur }).format(n));
41010
+ return parts.length ? parts.join(" + ") : "\u2014";
41011
+ }
41012
+
40917
41013
  // src/commands/servers.ts
40918
41014
  var import_node_readline2 = __toESM(require("readline"));
40919
41015
  var import_node_os11 = require("os");
@@ -43653,7 +43749,7 @@ function findingEvents(serverId, results, observedAt = /* @__PURE__ */ new Date(
43653
43749
 
43654
43750
  // src/daemon/workers/cloud-spool.ts
43655
43751
  var import_node_fs34 = require("fs");
43656
- var import_promises = require("fs/promises");
43752
+ var import_promises2 = require("fs/promises");
43657
43753
  var import_node_path25 = require("path");
43658
43754
  var DEFAULT_SPOOL_LIMITS = { maxEvents: 1e4, maxBytes: 20 * 1024 * 1024 };
43659
43755
  var CloudSpool = class {
@@ -43761,13 +43857,13 @@ var CloudSpool = class {
43761
43857
  const body = this.lines.length > 0 ? `${this.lines.join("\n")}
43762
43858
  ` : "";
43763
43859
  const tmp = `${this.path}.tmp`;
43764
- await (0, import_promises.writeFile)(tmp, body, { mode: 384 });
43765
- await (0, import_promises.rename)(tmp, this.path);
43860
+ await (0, import_promises2.writeFile)(tmp, body, { mode: 384 });
43861
+ await (0, import_promises2.rename)(tmp, this.path);
43766
43862
  } else if (this.pendingAppend.length > 0) {
43767
43863
  const chunk2 = `${this.pendingAppend.join("\n")}
43768
43864
  `;
43769
43865
  this.pendingAppend = [];
43770
- await (0, import_promises.appendFile)(this.path, chunk2, { mode: 384 });
43866
+ await (0, import_promises2.appendFile)(this.path, chunk2, { mode: 384 });
43771
43867
  }
43772
43868
  }).catch(() => {
43773
43869
  this.needsRewrite = true;
@@ -51173,6 +51269,15 @@ orgsCmd.command("create <name>").description("Create a new organization").action
51173
51269
  orgsCmd.command("use <slug>").description("Switch to an organization").action(async (slug) => {
51174
51270
  await orgsCommand({ action: "use", name: slug });
51175
51271
  });
51272
+ var fleetCmd = program2.command("fleet").description("Every machine you run (OpenDevice inventory) with monthly cost, daemon or not").action(async () => {
51273
+ await fleetCostCommand({});
51274
+ });
51275
+ fleetCmd.command("import <source>").description("Upload an OpenDevice inventory (file or https URL) to your organization").option("--org <slug>", "Organization slug or id (default: the `orgs use` org, or the only one you administer)").action(async (source, opts) => {
51276
+ await fleetImportCommand(source, opts);
51277
+ });
51278
+ fleetCmd.command("cost").alias("costs").description("Per-box monthly cost and the fleet total").option("--json", "Print the raw /api/fleet response").action(async (opts) => {
51279
+ await fleetCostCommand(opts);
51280
+ });
51176
51281
  var serversCmd = program2.command("servers").alias("server").alias("srv").description("Manage servers").action(async () => {
51177
51282
  await serversCommand({ action: "list" });
51178
51283
  });