@profullstack/threatcrush 0.13.55 → 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
@@ -182,7 +182,9 @@ threatcrush findings show 3f2a9c1d
182
182
  threatcrush findings ack|fix|fp|ignore|reopen 3f2a9c1d 7b1e… --note "why"
183
183
  ```
184
184
 
185
- `--no-upload` (or `THREATCRUSH_UPLOAD=0`) keeps a run local. A repo is named by
185
+ In CI, set `THREATCRUSH_API_KEY` to a `tc_agent_` key with write and runs
186
+ upload into that key's org with no login (workflow example in
187
+ docs/SCANNING.md). `--no-upload` (or `THREATCRUSH_UPLOAD=0`) keeps a run local. A repo is named by
186
188
  its origin remote (credentials stripped); URL targets lose their query string.
187
189
 
188
190
  ### Usage counts
@@ -227,6 +229,17 @@ enabled = true # false: the daemon neither reports to nor takes actio
227
229
  min_severity = "medium" # info | low | medium | high | critical
228
230
  ```
229
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
+
230
243
  ## Automatic updates
231
244
 
232
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;
@@ -50251,7 +50347,8 @@ async function uploadResult(result, opts) {
50251
50347
  const say = (line2) => (opts.machineReadable ? process.stderr : process.stdout).write(`${line2}
50252
50348
  `);
50253
50349
  if (uploadDisabled(opts.upload, opts.env)) return { uploaded: false, reason: "disabled" };
50254
- if (!hasSession()) {
50350
+ const apiKey = (opts.env ?? process.env).THREATCRUSH_API_KEY?.trim();
50351
+ if (!apiKey && !hasSession()) {
50255
50352
  if (!opts.machineReadable && process.stdout.isTTY) {
50256
50353
  say(source_default.dim(` Sign in with ${source_default.white("threatcrush login")} to track these findings in the cloud and triage them anywhere.
50257
50354
  `));
@@ -50259,31 +50356,33 @@ async function uploadResult(result, opts) {
50259
50356
  return { uploaded: false, reason: "signed-out" };
50260
50357
  }
50261
50358
  const cfg = readCliConfig();
50262
- if (!cfg.current_org_id) {
50359
+ if (!apiKey && !cfg.current_org_id) {
50263
50360
  say(source_default.yellow(` Not saved to the cloud: no current org. Pick one with ${source_default.white("threatcrush orgs use <slug>")}.
50264
50361
  `));
50265
50362
  return { uploaded: false, reason: "no-org" };
50266
50363
  }
50267
50364
  try {
50268
- const res = await cloudFetch(`/api/orgs/${cfg.current_org_id}/scan-findings/report`, {
50269
- method: "POST",
50270
- timeoutMs: 3e4,
50271
- body: JSON.stringify({
50272
- source: opts.source,
50273
- target: opts.target,
50274
- kind: opts.kind,
50275
- scope: opts.scope ?? "",
50276
- worker_id: workerId(),
50277
- result: {
50278
- // ai-scan and pentest put the target URL in each finding's location:
50279
- // clean it like the target, or a ?key= in the URL reaches the cloud.
50280
- findings: result.findings.map((f) => f.location && /^https?:\/\//i.test(f.location) ? { ...f, location: cleanUrl(f.location) } : f),
50281
- severity_summary: result.severity_summary,
50282
- summary: result.summary,
50283
- error: result.error
50284
- }
50285
- })
50365
+ const body = JSON.stringify({
50366
+ source: opts.source,
50367
+ target: opts.target,
50368
+ kind: opts.kind,
50369
+ scope: opts.scope ?? "",
50370
+ worker_id: workerId(),
50371
+ result: {
50372
+ // ai-scan and pentest put the target URL in each finding's location:
50373
+ // clean it like the target, or a ?key= in the URL reaches the cloud.
50374
+ findings: result.findings.map((f) => f.location && /^https?:\/\//i.test(f.location) ? { ...f, location: cleanUrl(f.location) } : f),
50375
+ severity_summary: result.severity_summary,
50376
+ summary: result.summary,
50377
+ error: result.error
50378
+ }
50286
50379
  });
50380
+ const res = apiKey ? await fetch(`${apiUrl()}/api/v1/findings/report`, {
50381
+ method: "POST",
50382
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
50383
+ body,
50384
+ signal: AbortSignal.timeout(3e4)
50385
+ }) : await cloudFetch(`/api/orgs/${cfg.current_org_id}/scan-findings/report`, { method: "POST", timeoutMs: 3e4, body });
50287
50386
  const data = await res.json().catch(() => ({}));
50288
50387
  if (!res.ok || !data.sync) {
50289
50388
  say(source_default.yellow(` Not saved to the cloud: ${data.error || `HTTP ${res.status}`}.
@@ -50291,10 +50390,15 @@ async function uploadResult(result, opts) {
50291
50390
  return { uploaded: false, reason: "error" };
50292
50391
  }
50293
50392
  const s = data.sync;
50294
- const org = cfg.current_org_slug || "your org";
50295
50393
  const parts = [`${s.new} new`, `${s.seen + s.reopened} still open${s.reopened ? ` (${s.reopened} back after a fix)` : ""}`, `${s.fixed} fixed`];
50296
- say(source_default.cyan(` \u2601 Saved to ${org}: ${parts.join(" \xB7 ")}. Triage with ${source_default.white("threatcrush findings")} or on threatcrush.com/org/${org}/findings
50394
+ if (apiKey) {
50395
+ say(source_default.cyan(` \u2601 Saved to the API key's org: ${parts.join(" \xB7 ")}. Triage on threatcrush.com (Findings).
50297
50396
  `));
50397
+ } else {
50398
+ const org = cfg.current_org_slug || "your org";
50399
+ say(source_default.cyan(` \u2601 Saved to ${org}: ${parts.join(" \xB7 ")}. Triage with ${source_default.white("threatcrush findings")} or on threatcrush.com/org/${org}/findings
50400
+ `));
50401
+ }
50298
50402
  return { uploaded: true, sync: s, propertyName: data.property_name };
50299
50403
  } catch (err) {
50300
50404
  say(source_default.yellow(` Not saved to the cloud: ${err.message}.
@@ -50381,7 +50485,7 @@ async function findingsListCommand(opts) {
50381
50485
  for (const f of data.findings) {
50382
50486
  const sev = (SEV_COLOR[f.severity] ?? source_default.white)(f.severity.toUpperCase().padEnd(8));
50383
50487
  console.log(` ${source_default.gray(short(f.id))} ${sev} ${source_default.dim((STATUS_LABEL[f.status] ?? f.status).padEnd(7))} ${f.message}`);
50384
- console.log(source_default.dim(` ${f.source} \xB7 ${f.properties?.name ?? "?"}${f.location ? ` \xB7 ${f.location}` : ""} \xB7 seen ${f.times_seen}x, last ${day(f.last_seen_at)}`));
50488
+ console.log(source_default.dim(` ${f.source} \xB7 ${f.properties?.name ?? "?"}${f.location && f.location !== f.properties?.target ? ` \xB7 ${f.location}` : ""} \xB7 seen ${f.times_seen}x, last ${day(f.last_seen_at)}`));
50385
50489
  }
50386
50490
  if (data.total > data.findings.length) console.log(source_default.dim(`
50387
50491
  ${data.findings.length} of ${data.total} shown; --limit for more.`));
@@ -51165,6 +51269,15 @@ orgsCmd.command("create <name>").description("Create a new organization").action
51165
51269
  orgsCmd.command("use <slug>").description("Switch to an organization").action(async (slug) => {
51166
51270
  await orgsCommand({ action: "use", name: slug });
51167
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
+ });
51168
51281
  var serversCmd = program2.command("servers").alias("server").alias("srv").description("Manage servers").action(async () => {
51169
51282
  await serversCommand({ action: "list" });
51170
51283
  });