@hardkeel/benthic 0.0.0-stage → 1.0.0

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/LICENSE +92 -0
  3. package/NOTICE +16 -0
  4. package/README.md +424 -2
  5. package/action.yml +54 -0
  6. package/dist/agility.js +80 -0
  7. package/dist/badge.js +62 -0
  8. package/dist/baseline.js +81 -0
  9. package/dist/cbom-diff.js +273 -0
  10. package/dist/cbom.js +418 -0
  11. package/dist/cli.js +834 -0
  12. package/dist/cloud-aws-services.js +375 -0
  13. package/dist/cloud-aws.js +354 -0
  14. package/dist/cloud-azure-services.js +73 -0
  15. package/dist/cloud-azure.js +144 -0
  16. package/dist/cloud-common.js +242 -0
  17. package/dist/cloud-gcp-services.js +90 -0
  18. package/dist/cloud-gcp.js +150 -0
  19. package/dist/comments.js +138 -0
  20. package/dist/community-rules.js +37 -0
  21. package/dist/community.js +30 -0
  22. package/dist/deps.js +406 -0
  23. package/dist/der.js +571 -0
  24. package/dist/evidence-cli.js +235 -0
  25. package/dist/evidence-live.js +109 -0
  26. package/dist/evidence.js +512 -0
  27. package/dist/ignore.js +90 -0
  28. package/dist/image.js +1224 -0
  29. package/dist/infra.js +635 -0
  30. package/dist/inventory.js +277 -0
  31. package/dist/map-activity.js +24 -0
  32. package/dist/map-areas.js +60 -0
  33. package/dist/map-cloud-keys.js +110 -0
  34. package/dist/map-cloud.js +34 -0
  35. package/dist/map-ct.js +107 -0
  36. package/dist/map-host.js +335 -0
  37. package/dist/map-network.js +520 -0
  38. package/dist/map-people.js +79 -0
  39. package/dist/map-rank.js +70 -0
  40. package/dist/map-report.js +304 -0
  41. package/dist/map-run.js +327 -0
  42. package/dist/map-sarif.js +61 -0
  43. package/dist/map-signin.js +247 -0
  44. package/dist/map-types.js +19 -0
  45. package/dist/map-web.js +666 -0
  46. package/dist/native.js +168 -0
  47. package/dist/policy.js +221 -0
  48. package/dist/pqc.js +46 -0
  49. package/dist/profile.js +65 -0
  50. package/dist/project.js +928 -0
  51. package/dist/prose.js +159 -0
  52. package/dist/protocols.js +207 -0
  53. package/dist/registry.js +326 -0
  54. package/dist/report.js +190 -0
  55. package/dist/rules.js +230 -0
  56. package/dist/sarif-common.js +30 -0
  57. package/dist/sarif.js +114 -0
  58. package/dist/scan.js +601 -0
  59. package/dist/score.js +124 -0
  60. package/dist/secrets.js +192 -0
  61. package/dist/share-config.js +129 -0
  62. package/dist/share-lists.js +19 -0
  63. package/dist/share.js +125 -0
  64. package/dist/sonar.js +83 -0
  65. package/dist/structure.js +218 -0
  66. package/dist/suites.js +402 -0
  67. package/dist/tls-check.js +122 -0
  68. package/dist/types.js +4 -0
  69. package/dist/walk.js +78 -0
  70. package/dist/yaml.js +173 -0
  71. package/package.json +73 -4
package/dist/cli.js ADDED
@@ -0,0 +1,834 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
3
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
4
+ // Hard Keel Benthic, command line.
5
+ // Finds encryption quantum computers will break, weak encryption, exposed infrastructure settings
6
+ // and leaked keys in a folder,
7
+ // and writes an encryption inventory (CycloneDX CBOM) and a migration report.
8
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { basename, dirname, join, relative, resolve } from "node:path";
10
+ import { walkFolder } from "./walk.js";
11
+ import { buildCbom } from "./cbom.js";
12
+ import { evidenceCommand } from "./evidence-cli.js";
13
+ import { gitState } from "./evidence.js";
14
+ import { migrationReportMarkdown, prSummaryLine, shortLabel, sortFindings } from "./report.js";
15
+ import { buildSarif } from "./sarif.js";
16
+ import { scanFiles } from "./scan.js";
17
+ import { badgeSvg } from "./badge.js";
18
+ import { gradeSentence, readinessScore } from "./score.js";
19
+ import { applyIgnore, ignoreFileIn, parseIgnore } from "./ignore.js";
20
+ import { ActivityLog } from "./map-activity.js";
21
+ import { OLD_SCOPE_FILE, parseScope, runMap, SCOPE_FILE } from "./map-run.js";
22
+ import { checkProof, parseTarget, proofRecord, publicLookup } from "./map-web.js";
23
+ import { inventoryCautions, inventoryCounts } from "./inventory.js";
24
+ import { pqcReliance, relianceLine } from "./agility.js";
25
+ import { checkProfile, profileText, PROFILES } from "./profile.js";
26
+ import { applySeverity, checkPolicy, parsePolicy, POLICY_FILES, policyFailures, policyText, PolicyError } from "./policy.js";
27
+ import { buildSonar } from "./sonar.js";
28
+ import { cbomDiffText, diffCbom, newRisk, readCbom } from "./cbom-diff.js";
29
+ import { ctDomain, hostsText, lookupCt } from "./map-ct.js";
30
+ import { checkSshQuick, checkTlsQuick, tlsTargets, tlsText } from "./tls-check.js";
31
+ import { imageScanInput, imageText, loadImage } from "./image.js";
32
+ import { loadFromRegistry, looksLikeImageRef } from "./registry.js";
33
+ import { purlOf } from "./deps.js";
34
+ import { baselineText, compareBaseline, readBaseline } from "./baseline.js";
35
+ import { buildPayload, diffRuns, sendPayload } from "./share.js";
36
+ import { LOCATION, PROFILE, PROJECT, PROVIDERS, REGION, runCloud, SUBSCRIPTION } from "./map-cloud.js";
37
+ import { rank, toFinding } from "./map-rank.js";
38
+ import { buildMapReport, mapHtml, mapText } from "./map-report.js";
39
+ import { buildMapSarif } from "./map-sarif.js";
40
+ import { folderKey, INDUSTRIES, loadSettings, saveSettings, settingsPath, sharingState, showNoticeIfNeeded, SIZES } from "./share-config.js";
41
+ export const VERSION = "1.0.0";
42
+ const APP_URL = "https://github.com/apps/hard-keel-quantum-scan";
43
+ const HELP = `Hard Keel Benthic ${VERSION}
44
+
45
+ Finds encryption quantum computers will break, weak encryption, exposed settings and
46
+ leaked keys or passwords in your code and infrastructure config (Terraform, CloudFormation,
47
+ Kubernetes, Dockerfiles, nginx and Apache). Writes an encryption inventory and a
48
+ migration report.
49
+
50
+ Usage:
51
+ benthic [folder] [options] Scan code and infrastructure config
52
+ benthic map [options] Security map: code, websites, your network and
53
+ equipment, this machine and cloud accounts, asking
54
+ before each area
55
+ benthic cloud --provider <aws|azure|gcp>
56
+ Live cloud accounts: key service keys, certificates
57
+ and TLS policies, read-only, with your own sign-in
58
+ benthic prove <domain> Show the DNS record that proves a domain is yours
59
+ benthic hosts <domain> List hostnames under a domain from public certificate
60
+ logs, to check with map (--all, --json)
61
+ benthic tls <host[:port]>... Quick check of sites you name: does TLS offer quantum-safe
62
+ hybrid key exchange, and what key signs the certificate.
63
+ ssh://host checks SSH key exchange the same way
64
+ (--format json|cyclonedx, --cbom <file>, --require-pq)
65
+ benthic image <image> Scan a container image: pulled read-only from its registry
66
+ (nginx:1.27, ghcr.io/org/app@sha256:...) with the docker or
67
+ podman login already on this machine, or saved to a file or
68
+ folder (docker save, podman save, an OCI layout, or an
69
+ unpacked root filesystem). Reads packages, settings, keys,
70
+ programs with encryption built in and Java keystores. Takes
71
+ the same options as a folder scan, plus --platform os/arch
72
+ and --no-cache (layers are cached by digest)
73
+ benthic diff <before> <after> Compare two encryption inventories (CycloneDX CBOMs):
74
+ what was added, removed or changed (--format json,
75
+ --fail-on added,removed,changed,new-risk)
76
+ benthic evidence [folder] Cryptographic inventory for a compliance review (PCI DSS
77
+ 12.3.3): every protocol, cipher suite and algorithm in use,
78
+ by system, with purpose, viability, a review record and
79
+ hashes. --scope <file> names systems and hosts to check
80
+ live; benthic evidence --help for the rest
81
+ benthic config <setting> Sharing, offline mode, industry and size
82
+
83
+ Options:
84
+ --format <text|json|sarif|cyclonedx|sonar>
85
+ What to print (default: text). sarif is for GitHub code
86
+ scanning; cyclonedx is the encryption inventory (CBOM);
87
+ sonar is for SonarQube (sonar.externalIssuesReportPaths)
88
+ --output <file> Write the --format output to a file instead
89
+ --cbom <file> Write the encryption inventory (CycloneDX 1.6 CBOM)
90
+ --report <file> Write the migration report (Markdown)
91
+ --badge <file> Write a quantum readiness badge (SVG) for your README
92
+ --name <name> Repository name to use in the inventory and report
93
+ --fail-on <list> Exit with 1 on these: secret, weak-now, exposed,
94
+ quantum-vulnerable, increase (more than the baseline),
95
+ profile (anything --profile rules out),
96
+ policy (anything your policy rules out),
97
+ or none (default: secret,weak-now,exposed). Anything else
98
+ stops the scan with exit code 2
99
+ --policy <file> Your encryption policy in YAML: algorithms not allowed,
100
+ smallest key sizes, exceptions, severities (default:
101
+ .benthic.yml in the scanned folder, if there is one)
102
+ --ignore-file <file> Read what to ignore from this file instead of the
103
+ .benthic-ignore in the scanned folder
104
+ --no-repo-config Don't read .benthic-ignore or .benthic.yml from
105
+ the scanned folder. Use it on pull requests from people you
106
+ don't know, since those files arrive with the change
107
+ --profile cnsa2 Also list what NSA's CNSA 2.0 suite doesn't allow, like
108
+ AES-128, SHA-256 or ML-KEM-768 (doesn't change the grade)
109
+ --baseline <file> Compare with an earlier run: a CBOM from --cbom, or
110
+ --format json output. Shows what went up and down
111
+ --quiet Leave out the closing line about installing on GitHub
112
+ --offline Send nothing to Hard Keel
113
+ --version Print the version
114
+ --help Print this help
115
+
116
+ Map options:
117
+ --scope <file> Use saved answers (benthic.scope.json) instead of asking
118
+ --out <folder> Where to write the map (default: benthic-map)
119
+ --fail-on broken Exit with 1 when anything is broken now
120
+
121
+ Cloud options:
122
+ --provider <list> aws, azure, gcp, or several separated by commas
123
+ --profile <name> AWS profile to use (default: the AWS CLI's default)
124
+ --region <list> AWS regions (default: every region turned on for the account)
125
+ --subscription <list> Azure subscriptions (default: the one az has selected)
126
+ --project <list> Google Cloud projects (default: the one gcloud has selected)
127
+ --location <list> Google Cloud KMS locations (default: all)
128
+ --format, --output, --cbom, --report work as for a folder scan. --html <file> writes
129
+ the branded report. --fail-on broken exits with 1 when anything is broken now.
130
+ Uses the aws, az or gcloud command-line tool already signed in on this machine. Every
131
+ call only lists or reads settings; nothing is changed, and credentials never leave it.
132
+
133
+ Config:
134
+ benthic config show Current settings
135
+ benthic config show-shared Exactly what the last run sent, or would have sent
136
+ benthic config sharing on|off Anonymized sharing (on by default)
137
+ benthic config offline on|off Send nothing at all, ever
138
+ benthic config industry <name> Optional. ${INDUSTRIES.join(", ")}, or none
139
+ benthic config size <band> Optional. ${SIZES.join(", ")}, or none
140
+
141
+ Sharing: unless you turn it off, each run sends an anonymized summary: rounded counts of
142
+ which checks fired and which encryption types were found. Never code, keys, server
143
+ names, IP addresses or company name. Details: https://hardkeel.com/privacy/
144
+ `;
145
+ const FLAGS = new Set(["quiet", "help", "version", "offline", "all", "json", "no-cache", "no-repo-config"]);
146
+ const VALUE_OPTIONS = new Set(["format", "output", "cbom", "report", "badge", "name", "fail-on", "policy", "profile", "baseline", "ignore-file", "scope", "out", "provider", "region", "subscription", "project", "location", "html", "platform"]);
147
+ /**
148
+ * Options and the folder. An option this tool doesn't know, or one that needs a value and has none, is an
149
+ * error: guessing would swallow the folder name (--colour src) or quietly turn a check off.
150
+ */
151
+ export function parseArgs(argv) {
152
+ const opts = {};
153
+ const rest = [];
154
+ for (let i = 0; i < argv.length; i++) {
155
+ const a = argv[i];
156
+ if (!a.startsWith("--")) {
157
+ rest.push(a);
158
+ continue;
159
+ }
160
+ const eq = a.indexOf("=");
161
+ const k = eq < 0 ? a.slice(2) : a.slice(2, eq);
162
+ const v = eq < 0 ? undefined : a.slice(eq + 1);
163
+ if (FLAGS.has(k))
164
+ opts[k] = true;
165
+ else if (!VALUE_OPTIONS.has(k))
166
+ return { opts, dir: rest[0] ?? ".", error: `Unknown option --${k}. Run benthic --help for the list.` };
167
+ else if (v !== undefined)
168
+ opts[k] = v;
169
+ else if (i + 1 < argv.length && !argv[i + 1].startsWith("--"))
170
+ opts[k] = argv[++i];
171
+ else
172
+ return { opts, dir: rest[0] ?? ".", error: `--${k} needs a value.` };
173
+ }
174
+ return { opts, dir: rest[0] ?? "." };
175
+ }
176
+ export const FAIL_ON = ["secret", "weak-now", "exposed", "quantum-vulnerable", "increase", "profile", "policy", "none"];
177
+ /** The --fail-on list, or what's wrong with it. A misspelled entry would otherwise turn the check off. */
178
+ export function parseFailOn(value) {
179
+ if (value === undefined)
180
+ return { list: ["secret", "weak-now", "exposed"] };
181
+ const list = value.split(",").map((x) => x.trim()).filter(Boolean);
182
+ const bad = list.filter((x) => !FAIL_ON.includes(x));
183
+ if (!list.length || bad.length)
184
+ return { error: `${bad.length ? `Unknown --fail-on "${bad.join(", ")}"` : "--fail-on is empty"}. Use ${FAIL_ON.join(", ")}, separated by commas.` };
185
+ return { list };
186
+ }
187
+ /** A path for the terminal: no control characters, so a file name can't rewrite what a reviewer sees. */
188
+ export function safeText(s) {
189
+ return s.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
190
+ }
191
+ /**
192
+ * The scanned folder's path inside its git repository, so SARIF paths start at the repository root
193
+ * when only a subfolder was scanned. GitHub code scanning can't place a file otherwise. Outside a
194
+ * repository, paths stay relative to the scanned folder.
195
+ */
196
+ export function repoPrefix(dir) {
197
+ const abs = resolve(dir);
198
+ for (let d = abs;; d = dirname(d)) {
199
+ if (existsSync(join(d, ".git")))
200
+ return relative(d, abs).split("\\").join("/");
201
+ if (dirname(d) === d)
202
+ return "";
203
+ }
204
+ }
205
+ export function suppressedLine(s) {
206
+ return `Hidden by ${s.file}: ${s.count} finding${s.count === 1 ? "" : "s"}${s.secrets ? `, including ${s.secrets} leaked key${s.secrets === 1 ? "" : "s"} or password${s.secrets === 1 ? "" : "s"}` : ""}. Review changes to that file the way you review code.`;
207
+ }
208
+ function textReport(findings, filesScanned, quiet, score, inventory = [], libraries = [], pqc = [], suppressed) {
209
+ const out = [`Hard Keel Benthic · ${filesScanned} file${filesScanned === 1 ? "" : "s"} scanned`, "", gradeSentence(score), ""];
210
+ if (suppressed?.count)
211
+ out.push(suppressedLine(suppressed), "");
212
+ if (!findings.length) {
213
+ out.push("Nothing found. No leaked keys, weak or quantum-breakable encryption, or exposed settings.");
214
+ }
215
+ else {
216
+ out.push(prSummaryLine(findings).replace("This change adds", "Found"));
217
+ const sorted = sortFindings(findings);
218
+ const section = (title, list, note) => {
219
+ if (!list.length)
220
+ return;
221
+ out.push("", title);
222
+ if (note)
223
+ out.push(` ${note}`);
224
+ for (const f of list) {
225
+ out.push(` ${safeText(f.file)}${f.line > 0 ? `:${f.line}` : ""} ${shortLabel(f)}`);
226
+ // Where the value came from, when it isn't on the line: a constant, or a caller.
227
+ for (const v of f.via ?? [])
228
+ out.push(` from ${safeText(v.file)}:${v.line} ${safeText(v.note)}`);
229
+ out.push(` ${f.fix}`);
230
+ }
231
+ };
232
+ section("Fix now", sorted.filter((f) => f.risk !== "quantum-vulnerable"));
233
+ section("Plan for later", sorted.filter((f) => f.risk === "quantum-vulnerable"), "Safe today, but quantum computers will be able to break these. NIST plans to phase them out between 2030 and 2035.");
234
+ }
235
+ if (inventory.length) {
236
+ const counts = inventoryCounts(inventory);
237
+ const shown = counts.slice(0, 6).map(([a, n]) => `${a} (${n})`).join(", ");
238
+ out.push("", `Also in use, nothing to fix: ${shown}${counts.length > 6 ? `, and ${counts.length - 6} more` : ""}. The full list is in the inventory (--cbom).`);
239
+ const cautions = inventoryCautions(inventory);
240
+ if (cautions.length) {
241
+ out.push("", "Worth a look (doesn't change the grade)");
242
+ for (const c of cautions)
243
+ out.push(` ${c.at} ${c.algorithm}${c.more ? ` (${c.more + 1} places)` : ""}`, ` ${c.caution}`);
244
+ }
245
+ }
246
+ const reliance = pqcReliance(pqc, inventory);
247
+ if (reliance.places) {
248
+ out.push("", `Post-quantum encryption in use (doesn't change the grade): ${relianceLine(reliance)}`);
249
+ for (const n of reliance.notes)
250
+ out.push(` ${n}`);
251
+ }
252
+ if (libraries.length) {
253
+ const label = { "quantum-vulnerable": "quantum-breakable", "quantum-safe": "post-quantum", mixed: "has both kinds", check: "worth a look" };
254
+ out.push("", "Encryption libraries in your dependencies (don't change the grade)");
255
+ for (const l of libraries.slice(0, 10))
256
+ out.push(` ${l.file}${l.line > 0 ? `:${l.line}` : ""} ${l.name}: ${l.provides} (${label[l.risk]})`);
257
+ if (libraries.length > 10)
258
+ out.push(` and ${libraries.length - 10} more in the inventory (--cbom)`);
259
+ }
260
+ if (!quiet)
261
+ out.push("", `Check every pull request automatically: ${APP_URL}`);
262
+ return out.join("\n");
263
+ }
264
+ /** The lattice reliance block for --format json, only when post-quantum encryption was found. */
265
+ function pqcRelianceField(r) {
266
+ return r.places ? { pqcReliance: r } : {};
267
+ }
268
+ export function main(argv) {
269
+ return scanCommand(argv).code;
270
+ }
271
+ /** The folder scan. Returns its exit code and the counts the anonymized summary may use. */
272
+ export function scanCommand(argv, image) {
273
+ const { opts, dir, error } = parseArgs(argv);
274
+ if (error) {
275
+ console.error(error);
276
+ return { code: 2 };
277
+ }
278
+ if (opts.help) {
279
+ process.stdout.write(HELP);
280
+ return { code: 0 };
281
+ }
282
+ if (opts.version) {
283
+ console.log(VERSION);
284
+ return { code: 0 };
285
+ }
286
+ const str = (k) => (typeof opts[k] === "string" ? opts[k] : undefined);
287
+ const failOnParsed = parseFailOn(str("fail-on"));
288
+ if ("error" in failOnParsed) {
289
+ console.error(failOnParsed.error);
290
+ return { code: 2 };
291
+ }
292
+ const format = str("format") ?? "text";
293
+ if (!["text", "json", "sarif", "sonar", "cyclonedx", "cbom"].includes(format)) {
294
+ console.error(`Unknown --format "${format}". Use text, json, sarif, cyclonedx or sonar.`);
295
+ return { code: 2 };
296
+ }
297
+ // The ignore file and the policy arrive with the code. --no-repo-config leaves them out, for changes from people you don't know.
298
+ const repoConfig = opts["no-repo-config"] !== true;
299
+ let walked;
300
+ if (image)
301
+ walked = { files: image.files, unreadable: [] };
302
+ else {
303
+ try {
304
+ walked = walkFolder(dir);
305
+ }
306
+ catch (e) {
307
+ console.error(e instanceof Error ? e.message : String(e));
308
+ return { code: 2 };
309
+ }
310
+ }
311
+ if (walked.unreadable.length) {
312
+ const list = walked.unreadable.slice(0, 5).map((u) => `${u.path} (${u.reason})`).join(", ");
313
+ console.error(`Skipped ${walked.unreadable.length} path${walked.unreadable.length === 1 ? "" : "s"} that couldn't be read: ${list}${walked.unreadable.length > 5 ? ", ..." : ""}`);
314
+ }
315
+ const scanned = scanFiles(walked.files);
316
+ if (image) {
317
+ // A key or password in an image is there for anyone who pulls it, in every layer that holds it.
318
+ for (const f of scanned.findings) {
319
+ if (f.kind !== "secret")
320
+ continue;
321
+ f.title = f.title.replace("committed to the repository", "stored in the image");
322
+ f.fix = "Revoke it and issue a new one, then pass it in at run time from a secret store. Deleting it in a later layer leaves it in the earlier one.";
323
+ }
324
+ scanned.findings.push(...image.findings);
325
+ const seen = new Set((scanned.libraries ?? []).map((l) => `${purlOf(l)} ${l.file}`));
326
+ for (const l of image.libraries)
327
+ if (!seen.has(`${purlOf(l)} ${l.file}`))
328
+ (scanned.libraries ??= []).push(l);
329
+ }
330
+ const { filesScanned, pqc } = scanned;
331
+ // An image's own files are what's being checked, so an ignore file inside it doesn't count.
332
+ const ignorePath = str("ignore-file") ?? (repoConfig && !image ? ignoreFileIn(dir, existsSync) : undefined);
333
+ if (str("ignore-file") && !existsSync(str("ignore-file"))) {
334
+ console.error(`Can't read the ignore file ${str("ignore-file")}.`);
335
+ return { code: 2 };
336
+ }
337
+ const { kept: findings, ignored } = applyIgnore(scanned.findings, ignorePath && existsSync(ignorePath) ? parseIgnore(readFileSync(ignorePath, "utf8")) : []);
338
+ const hiddenCount = Object.values(ignored).reduce((a, b) => a + b, 0);
339
+ const suppressed = hiddenCount && ignorePath ? { file: str("ignore-file") ?? basename(ignorePath), count: hiddenCount, secrets: scanned.findings.filter((f) => f.kind === "secret").length - findings.filter((f) => f.kind === "secret").length, rules: ignored } : undefined;
340
+ if (suppressed && format !== "text")
341
+ console.error(suppressedLine(suppressed));
342
+ const score = readinessScore(findings, pqc);
343
+ const repo = str("name") ?? image?.summary.tags[0] ?? dir;
344
+ let diff;
345
+ const baselinePath = str("baseline");
346
+ if (baselinePath) {
347
+ try {
348
+ diff = compareBaseline(readBaseline(readFileSync(baselinePath, "utf8")), findings, scanned.inventory);
349
+ }
350
+ catch (e) {
351
+ console.error(`Can't use the baseline ${baselinePath}: ${e instanceof Error ? e.message : String(e)}`);
352
+ return { code: 2 };
353
+ }
354
+ }
355
+ const profileName = str("profile");
356
+ if (profileName !== undefined && !PROFILES.includes(profileName)) {
357
+ console.error(`Unknown --profile "${profileName}". Use ${PROFILES.join(", ")}.`);
358
+ return { code: 2 };
359
+ }
360
+ const profile = profileName ? checkProfile(profileName, findings, scanned.inventory) : undefined;
361
+ // Your own policy: --policy, or .benthic.yml at the top of the folder.
362
+ let policy;
363
+ const policyPath = str("policy") ?? (image || !repoConfig ? undefined : POLICY_FILES.map((n) => join(dir, n)).find((p) => existsSync(p)));
364
+ if (policyPath) {
365
+ try {
366
+ policy = parsePolicy(readFileSync(policyPath, "utf8"));
367
+ }
368
+ catch (e) {
369
+ console.error(`Can't use the policy ${policyPath}: ${e instanceof PolicyError ? e.message : e instanceof Error ? e.message : String(e)}`);
370
+ return { code: 2 };
371
+ }
372
+ // After the grade, which stays the same for everyone.
373
+ applySeverity(policy, findings);
374
+ }
375
+ const policyResult = policy ? checkPolicy(policy, findings, scanned.inventory) : undefined;
376
+ const badgePath = str("badge");
377
+ if (badgePath)
378
+ writeFileSync(badgePath, badgeSvg(score) + "\n");
379
+ // The commit scanned and whether it had uncommitted changes, so the inventory can be traced and run again.
380
+ let gitCache;
381
+ const git = () => {
382
+ if (!gitCache) {
383
+ const g = gitState(dir);
384
+ gitCache = g.commit ? { ref: g.commit, dirty: g.uncommittedChanges } : {};
385
+ }
386
+ return gitCache;
387
+ };
388
+ const cbomPath = str("cbom");
389
+ if (cbomPath)
390
+ writeFileSync(cbomPath, JSON.stringify(buildCbom(findings, { repo, toolVersion: VERSION, pqc, protocols: scanned.protocols, ...(image ? {} : git()) }, scanned.inventory, scanned.libraries), null, 2) + "\n");
391
+ const reportPath = str("report");
392
+ if (reportPath)
393
+ writeFileSync(reportPath, migrationReportMarkdown(repo, findings, new Date().toISOString().slice(0, 10), score, undefined, suppressed ? suppressedLine(suppressed) : undefined) + "\n");
394
+ let body;
395
+ if (format === "json")
396
+ body = JSON.stringify({ tool: "hard-keel-benthic", version: VERSION, filesScanned, score, findings, inventory: scanned.inventory, protocols: scanned.protocols ?? [], libraries: scanned.libraries ?? [], ...pqcRelianceField(pqcReliance(pqc, scanned.inventory)), ...(diff ? { baseline: diff } : {}), ...(profile ? { profile } : {}), ...(policyResult ? { policy: policyResult } : {}), ...(image ? { image: image.summary } : {}), ...(suppressed ? { suppressed } : {}) }, null, 2);
397
+ else if (format === "sarif")
398
+ body = JSON.stringify(buildSarif(findings, VERSION, { uriPrefix: image ? "" : repoPrefix(dir), policy: policyResult?.violations, suppressed }), null, 2);
399
+ else if (format === "sonar")
400
+ body = JSON.stringify(buildSonar(findings, { pathPrefix: image ? "" : repoPrefix(dir), policy: policyResult?.violations }), null, 2);
401
+ else if (format === "cyclonedx" || format === "cbom")
402
+ body = JSON.stringify(buildCbom(findings, { repo, toolVersion: VERSION, pqc, protocols: scanned.protocols, ...(image ? {} : git()) }, scanned.inventory, scanned.libraries), null, 2);
403
+ else
404
+ body = (image ? `${imageText(image.summary)}\n\n` : "") + textReport(findings, filesScanned, opts.quiet === true, score, scanned.inventory, scanned.libraries, pqc, suppressed) + (profile ? `\n\n${profileText(profile)}` : "") + (policyResult ? `\n\n${policyText(policyResult)}` : "") + (diff ? `\n\n${baselineText(diff)}` : "");
405
+ const outPath = str("output");
406
+ if (outPath) {
407
+ writeFileSync(outPath, body + "\n");
408
+ console.log(`${filesScanned} files scanned, ${findings.length} finding${findings.length === 1 ? "" : "s"}. Wrote ${outPath}.`);
409
+ }
410
+ else
411
+ console.log(body);
412
+ const failOn = [...failOnParsed.list];
413
+ if (policy?.fail && !failOn.includes("policy"))
414
+ failOn.push("policy");
415
+ if (failOn.includes("policy") && !policyResult) {
416
+ console.error(`--fail-on policy needs --policy <file> or a ${POLICY_FILES[0]} in the scanned folder.`);
417
+ return { code: 2 };
418
+ }
419
+ const policyFails = policyResult !== undefined && failOn.includes("policy") && policyFailures(policyResult).length > 0;
420
+ if (failOn.includes("increase") && !diff) {
421
+ console.error("--fail-on increase needs --baseline <file>.");
422
+ return { code: 2 };
423
+ }
424
+ if (failOn.includes("profile") && !profile) {
425
+ console.error("--fail-on profile needs --profile <name>.");
426
+ return { code: 2 };
427
+ }
428
+ const profileFails = profile !== undefined && failOn.includes("profile") && (profile.gaps.length > 0 || profile.findings > 0);
429
+ const code = findings.some((f) => failOn.includes(f.risk)) || (failOn.includes("increase") && diff.up.length > 0) || profileFails || policyFails ? 1 : 0;
430
+ const rules = {};
431
+ const algorithms = {};
432
+ for (const f of findings) {
433
+ rules[f.ruleId] = (rules[f.ruleId] ?? 0) + 1;
434
+ if (f.kind === "secret")
435
+ continue; // what kind of secret is a rule id already; no algorithm entry
436
+ const a = (algorithms[f.algorithm] ??= { count: 0, quantumVulnerable: 0 });
437
+ a.count++;
438
+ if (f.risk === "quantum-vulnerable")
439
+ a.quantumVulnerable++;
440
+ }
441
+ const pqcCounts = {};
442
+ for (const p of pqc)
443
+ pqcCounts[p.algorithm] = (pqcCounts[p.algorithm] ?? 0) + 1;
444
+ const facts = { command: "scan", areas: ["code"], rules, algorithms, quantumSafe: pqcCounts, fixed: {}, ignored, replacements: {}, errors: walked.unreadable.some((u) => u.reason === "permission denied") ? ["permission"] : walked.unreadable.length ? ["read"] : [] };
445
+ return { code, facts, stateKey: folderKey(dir), state: { rules, pqc: pqcCounts } };
446
+ }
447
+ /** Records this run, works out what was fixed since the last one, and sends the summary unless sharing is off. */
448
+ async function finishRun(facts, stateKey, state, s, sharing, send) {
449
+ if (!facts || !stateKey || !state)
450
+ return;
451
+ const key = stateKey.startsWith("map:") ? folderKey(stateKey) : stateKey;
452
+ const diff = diffRuns(s.state[key], state);
453
+ facts.fixed = diff.fixed;
454
+ facts.replacements = diff.replacements;
455
+ s.state[key] = state;
456
+ const payload = buildPayload(facts, s, VERSION);
457
+ s.lastShared = sharing === "on" ? payload : { notSent: sharing, wouldHaveSent: payload };
458
+ // The notice comes before the first summary is sent, and only on runs that send one.
459
+ showNoticeIfNeeded(s, sharing);
460
+ saveSettings(s);
461
+ if (sharing === "on")
462
+ await send(payload);
463
+ }
464
+ function configCommand(args, s) {
465
+ const [what, value] = args;
466
+ const onOff = (v) => (v === "on" || v === "off" ? v : null);
467
+ if (!what || what === "show") {
468
+ console.log([
469
+ `Settings file: ${settingsPath()}`,
470
+ `Sharing: ${s.sharing}${sharingState(s, {}) !== s.sharing ? ` (overridden here: ${sharingState(s, {})})` : ""}`,
471
+ `Offline mode: ${s.offline ? "on" : "off"}`,
472
+ `Industry: ${s.industry ?? "not set"}`,
473
+ `Size: ${s.size ?? "not set"}`,
474
+ `Random ID: ${s.id} (linked to nothing; quote it to ask us to delete your data)`,
475
+ ].join("\n"));
476
+ return 0;
477
+ }
478
+ if (what === "show-shared") {
479
+ console.log(s.lastShared ? JSON.stringify(s.lastShared, null, 2) : "Nothing yet. Run a scan first.");
480
+ return 0;
481
+ }
482
+ if (what === "sharing" && onOff(value))
483
+ s.sharing = onOff(value);
484
+ else if (what === "offline" && onOff(value))
485
+ s.offline = value === "on";
486
+ else if (what === "industry" && value && (value === "none" || INDUSTRIES.includes(value)))
487
+ s.industry = value === "none" ? undefined : value;
488
+ else if (what === "size" && value && (value === "none" || SIZES.includes(value)))
489
+ s.size = value === "none" ? undefined : value;
490
+ else {
491
+ console.error("Unknown setting. Run benthic --help for the list.");
492
+ return 2;
493
+ }
494
+ s.profileAsked = true;
495
+ saveSettings(s);
496
+ console.log(`Saved: ${what} ${value}.`);
497
+ return 0;
498
+ }
499
+ async function proveCommand(domain, s) {
500
+ const p = domain ? parseTarget(domain) : { error: "missing domain" };
501
+ if ("error" in p) {
502
+ console.error("Usage: benthic prove <domain>, for example benthic prove example.com");
503
+ return 2;
504
+ }
505
+ const scopeFile = [SCOPE_FILE, OLD_SCOPE_FILE].find((f) => existsSync(f));
506
+ const scope = scopeFile ? parseScope(readFileSync(scopeFile, "utf8")) : null;
507
+ const token = scope && !("error" in scope) && scope.ownershipToken ? scope.ownershipToken : s.ownershipToken;
508
+ const r = proofRecord(p.host, token);
509
+ console.log(`To prove you own ${p.host}, add this DNS record:\n\n Name: ${r.name}\n Type: TXT\n Value: ${r.value}\n\nIt covers ${p.host} and everything under it. It only allows look-only checks from this machine${scope && !("error" in scope) && scope.ownershipToken ? " and anyone using this scope file" : ""}.`);
510
+ const r2 = await checkProof(p.host, token, new ActivityLog(), undefined, publicLookup());
511
+ if (r2.status === "found")
512
+ console.log(`\nFound it. ${p.host} is proved.`);
513
+ else if (r2.status === "missing")
514
+ console.log("\nNot found yet. DNS changes can take a few minutes; run this again to check.");
515
+ else
516
+ console.log(`\nCouldn't check: ${r2.detail}. Check this machine's DNS settings, then run this again.`);
517
+ return r2.status === "found" ? 0 : 1;
518
+ }
519
+ /** Lists hostnames under a domain from public certificate logs. One request to crt.sh; none of the hosts are contacted. */
520
+ export async function hostsCommand(args, s, fetchFn) {
521
+ const { opts, dir, error } = parseArgs(args);
522
+ if (error) {
523
+ console.error(error);
524
+ return 2;
525
+ }
526
+ const domain = ctDomain(dir);
527
+ if (!domain) {
528
+ console.error("Usage: benthic hosts <domain> [--all] [--json], for example benthic hosts example.com");
529
+ return 2;
530
+ }
531
+ if (sharingState(s, { offline: Boolean(opts.offline) }) === "offline") {
532
+ console.error(`Offline mode is on, so this won't look ${domain} up. It asks crt.sh, a public certificate log, for names under the domain. Turn offline mode off for this run, or search ${domain} on crt.sh yourself.`);
533
+ return 2;
534
+ }
535
+ const r = await lookupCt(domain, VERSION, fetchFn);
536
+ if ("error" in r) {
537
+ console.error(`Couldn't list hostnames for ${domain}: ${r.error}`);
538
+ return 1;
539
+ }
540
+ if (opts.json)
541
+ process.stdout.write(JSON.stringify(r, null, 2) + "\n");
542
+ else
543
+ process.stdout.write(hostsText(r, Boolean(opts.all)));
544
+ return 0;
545
+ }
546
+ /** map and cloud take --fail-on broken or none; anything else is a mistake, not a pass. */
547
+ export function checkMapFailOn(v) {
548
+ return v === undefined || v === "broken" || v === "none" ? undefined : `Unknown --fail-on "${v}". Use broken or none.`;
549
+ }
550
+ const csv = (v, re) => (v ?? "").split(",").map((x) => x.trim()).filter((x) => re.test(x));
551
+ /** The scope a `cloud` run asked for, or what's wrong with the options. */
552
+ export function cloudScopeFromArgs(opts) {
553
+ const str = (k) => (typeof opts[k] === "string" ? opts[k] : undefined);
554
+ const asked = (str("provider") ?? "").split(",").map((p) => p.trim().toLowerCase()).filter(Boolean);
555
+ const bad = asked.filter((p) => !PROVIDERS.includes(p));
556
+ if (!asked.length || bad.length)
557
+ return { error: `${bad.length ? `Unknown provider ${bad.join(", ")}. ` : ""}Name one or more with --provider: aws, azure or gcp. For example: benthic cloud --provider aws` };
558
+ const providers = [...new Set(asked)];
559
+ const scope = {};
560
+ for (const [flag, re] of [["profile", PROFILE], ["region", REGION], ["subscription", SUBSCRIPTION], ["project", PROJECT], ["location", LOCATION]]) {
561
+ const v = str(flag);
562
+ if (v !== undefined && v.split(",").some((x) => x.trim() && !re.test(x.trim())))
563
+ return { error: `--${flag} "${v}" doesn't look right.` };
564
+ }
565
+ if (providers.includes("aws"))
566
+ scope.aws = { ...(str("profile") ? { profile: str("profile") } : {}), ...(csv(str("region"), REGION).length ? { regions: csv(str("region"), REGION) } : {}) };
567
+ if (providers.includes("azure"))
568
+ scope.azure = csv(str("subscription"), SUBSCRIPTION).length ? { subscriptions: csv(str("subscription"), SUBSCRIPTION) } : {};
569
+ if (providers.includes("gcp"))
570
+ scope.gcp = { ...(csv(str("project"), PROJECT).length ? { projects: csv(str("project"), PROJECT) } : {}), ...(csv(str("location"), LOCATION).length ? { locations: csv(str("location"), LOCATION) } : {}) };
571
+ return { scope, providers };
572
+ }
573
+ const CLOUD_COVERAGE = "This report lists what the scanner read from the cloud accounts named above: keys in the provider's key service, certificates and certificate authorities, TLS settings on load balancers, CDNs, APIs, apps and file transfer servers, and whether databases, caches, storage and file systems require encryption. It does not read the data itself, your code or your servers. Run benthic on your code and benthic map for websites, networks and machines.";
574
+ /** Live cloud accounts, read-only. Returns its exit code and the counts the anonymized summary may use. */
575
+ export async function cloudCommand(argv, runner) {
576
+ const { opts, error } = parseArgs(argv);
577
+ if (error) {
578
+ console.error(error);
579
+ return { code: 2 };
580
+ }
581
+ if (opts.help) {
582
+ process.stdout.write(HELP);
583
+ return { code: 0 };
584
+ }
585
+ const str = (k) => (typeof opts[k] === "string" ? opts[k] : undefined);
586
+ const mapFailOn = checkMapFailOn(str("fail-on"));
587
+ if (mapFailOn) {
588
+ console.error(mapFailOn);
589
+ return { code: 2 };
590
+ }
591
+ const parsed = cloudScopeFromArgs(opts);
592
+ if ("error" in parsed) {
593
+ console.error(parsed.error);
594
+ return { code: 2 };
595
+ }
596
+ const format = str("format") ?? "text";
597
+ if (!["text", "json", "sarif", "cyclonedx", "cbom"].includes(format)) {
598
+ console.error(`Unknown --format "${format}". Use text, json, sarif or cyclonedx.`);
599
+ return { code: 2 };
600
+ }
601
+ const log = new ActivityLog();
602
+ const names = parsed.providers.map((p) => ({ aws: "AWS", azure: "Azure", gcp: "Google Cloud" })[p]);
603
+ process.stderr.write(`Reading ${names.join(", ")} settings, read-only. This can take a few minutes.\n`);
604
+ const cloud = await runCloud(parsed.scope, log, { runner });
605
+ const ranked = rank(cloud.result.findings);
606
+ const report = buildMapReport([cloud.result], ranked, VERSION, new Date(), [], { cloudKeys: [], people: null });
607
+ const findings = ranked.map(toFinding);
608
+ const name = str("name") ?? "cloud accounts";
609
+ const cbom = () => JSON.stringify(buildCbom(findings, { repo: name, toolVersion: VERSION }, cloud.inventory), null, 2);
610
+ if (str("cbom"))
611
+ writeFileSync(str("cbom"), cbom() + "\n");
612
+ if (str("report"))
613
+ writeFileSync(str("report"), migrationReportMarkdown(name, findings, new Date().toISOString().slice(0, 10), report.score, CLOUD_COVERAGE) + "\n");
614
+ if (str("html"))
615
+ writeFileSync(str("html"), mapHtml(report, log.entries));
616
+ let body;
617
+ if (format === "json")
618
+ body = JSON.stringify({ ...report, accounts: cloud.notes, inventory: cloud.inventory }, null, 2);
619
+ else if (format === "sarif")
620
+ body = JSON.stringify(buildMapSarif(ranked, VERSION), null, 2);
621
+ else if (format === "cyclonedx" || format === "cbom")
622
+ body = cbom();
623
+ else {
624
+ const text = mapText(report).replace("Hard Keel Benthic · encryption map", "Hard Keel Benthic · cloud accounts");
625
+ const lines = text.split("\n");
626
+ if (cloud.notes.length)
627
+ lines.splice(1, 0, "", ...cloud.notes.map((n) => `Checked ${n}`));
628
+ lines.push("", `Read-only: ${log.entries.length} list, describe, get or show call${log.entries.length === 1 ? "" : "s"}. Nothing was changed.`);
629
+ lines.push("Key exchange and certificates on each website are also worth a live check: benthic map tests the real handshake.");
630
+ body = lines.join("\n");
631
+ }
632
+ const outPath = str("output");
633
+ if (outPath) {
634
+ writeFileSync(outPath, body + "\n");
635
+ console.log(`${ranked.length} finding${ranked.length === 1 ? "" : "s"}. Wrote ${outPath}.`);
636
+ }
637
+ else
638
+ console.log(body);
639
+ const nothing = !cloud.result.checked.length;
640
+ const code = nothing ? 2 : str("fail-on") === "broken" && report.counts[1] > 0 ? 1 : 0;
641
+ // Counts for the anonymized summary: rule ids and algorithm names only. Accounts, regions and resource names never leave this function.
642
+ const rules = {};
643
+ const algorithms = {};
644
+ for (const f of ranked) {
645
+ rules[f.ruleId] = (rules[f.ruleId] ?? 0) + 1;
646
+ const a = (algorithms[f.algorithm] ??= { count: 0, quantumVulnerable: 0 });
647
+ a.count++;
648
+ if (f.risk === "quantum-vulnerable")
649
+ a.quantumVulnerable++;
650
+ }
651
+ const pqc = {};
652
+ for (const st of cloud.result.strengths)
653
+ pqc[st.algorithm] = (pqc[st.algorithm] ?? 0) + 1;
654
+ const errors = [...new Set(cloud.result.errors.map((e) => e.kind))];
655
+ const facts = { command: "map", areas: ["cloud"], rules, algorithms, quantumSafe: pqc, fixed: {}, ignored: {}, replacements: {}, errors };
656
+ return { code, facts, stateKey: `cloud:${parsed.providers.join(",")}`, state: { rules, pqc } };
657
+ }
658
+ /** Entry point: subcommands, the first-run notice and the anonymized summary. */
659
+ /**
660
+ * benthic tls: two handshakes per host the person typed, like a browser makes, or one SSH banner
661
+ * exchange for ssh:// hosts. Sends nothing to Hard Keel.
662
+ * Exit 1 with --require-pq when a host offers no hybrid ML-KEM key exchange; 2 when none could be reached.
663
+ */
664
+ export async function tlsCommand(args, hs, ssh) {
665
+ const rest = [];
666
+ const opts = {};
667
+ for (let i = 0; i < args.length; i++) {
668
+ const a = args[i];
669
+ if (!a.startsWith("--"))
670
+ rest.push(a);
671
+ else if (a === "--require-pq" || a === "--help")
672
+ opts[a.slice(2)] = true;
673
+ else
674
+ opts[a.slice(2).split("=")[0]] = a.includes("=") ? a.split("=").slice(1).join("=") : (args[++i] ?? "");
675
+ }
676
+ if (opts.help || !rest.length) {
677
+ process.stdout.write("Usage: benthic tls <host[:port] | ssh://host[:port]>... [--format text|json|cyclonedx] [--output <file>] [--cbom <file>] [--require-pq]\n");
678
+ return opts.help ? 0 : 2;
679
+ }
680
+ const { targets, errors } = tlsTargets(rest);
681
+ for (const e of errors)
682
+ console.error(e);
683
+ if (!targets.length)
684
+ return 2;
685
+ const results = [];
686
+ for (const t of targets)
687
+ results.push(t.kind === "ssh" ? await checkSshQuick(t, ssh) : await checkTlsQuick(t, hs));
688
+ const findings = results.flatMap((r) => r.findings);
689
+ const cbom = () => buildCbom(findings, { repo: targets.map((t) => t.label).join(", "), toolVersion: VERSION });
690
+ const format = typeof opts.format === "string" ? opts.format : "text";
691
+ if (!["text", "json", "cyclonedx", "cbom"].includes(format)) {
692
+ console.error(`Unknown --format "${format}". Use text, json or cyclonedx.`);
693
+ return 2;
694
+ }
695
+ const body = format === "json" ? JSON.stringify({ version: VERSION, results }, null, 2) : format === "cyclonedx" || format === "cbom" ? JSON.stringify(cbom(), null, 2) : tlsText(results);
696
+ if (typeof opts.output === "string" && opts.output)
697
+ writeFileSync(opts.output, body + "\n");
698
+ else
699
+ process.stdout.write(body + "\n");
700
+ if (typeof opts.cbom === "string" && opts.cbom)
701
+ writeFileSync(opts.cbom, JSON.stringify(cbom(), null, 2) + "\n");
702
+ if (results.every((r) => !r.ok))
703
+ return 2;
704
+ if (opts["require-pq"] && results.some((r) => r.ok && r.hybrid !== true))
705
+ return 1;
706
+ return 0;
707
+ }
708
+ /** benthic diff <before> <after>: two encryption inventories, compared. */
709
+ export function diffCommand(args) {
710
+ const { opts, error } = parseArgs(args);
711
+ if (error) {
712
+ console.error(error);
713
+ return 2;
714
+ }
715
+ const files = args.filter((a, i) => !a.startsWith("--") && !(i > 0 && /^--(format|output|fail-on)$/.test(args[i - 1])));
716
+ if (opts.help || files.length !== 2) {
717
+ console.error("Usage: benthic diff <before.cbom.json> <after.cbom.json> [--format text|json] [--output <file>] [--fail-on added,removed,changed,new-risk]");
718
+ return opts.help ? 0 : 2;
719
+ }
720
+ let before, after;
721
+ try {
722
+ before = readCbom(readFileSync(files[0], "utf8"), files[0]);
723
+ after = readCbom(readFileSync(files[1], "utf8"), files[1]);
724
+ }
725
+ catch (e) {
726
+ console.error(e instanceof Error ? e.message : String(e));
727
+ return 2;
728
+ }
729
+ const d = diffCbom(before, after);
730
+ const risk = newRisk(d, after);
731
+ const format = typeof opts.format === "string" ? opts.format : "text";
732
+ if (format !== "text" && format !== "json") {
733
+ console.error(`Unknown --format "${format}". Use text or json.`);
734
+ return 2;
735
+ }
736
+ const body = format === "json" ? JSON.stringify({ tool: "hard-keel-benthic", version: VERSION, ...d, newRisk: risk }, null, 2) : cbomDiffText(d) + (risk.length ? `\n\nSteps back (new or more places, with a risk to fix): ${risk.join(", ")}` : "");
737
+ if (typeof opts.output === "string" && opts.output)
738
+ writeFileSync(opts.output, body + "\n");
739
+ else
740
+ console.log(body);
741
+ const failOn = typeof opts["fail-on"] === "string" ? opts["fail-on"].split(",").map((x) => x.trim()) : [];
742
+ const known = new Set(["added", "removed", "changed", "new-risk", "none"]);
743
+ const bad = failOn.find((x) => !known.has(x));
744
+ if (bad) {
745
+ console.error(`Unknown --fail-on "${bad}". Use added, removed, changed, new-risk or none.`);
746
+ return 2;
747
+ }
748
+ const fails = (failOn.includes("added") && d.added.length > 0) || (failOn.includes("removed") && d.removed.length > 0) || (failOn.includes("changed") && d.changed.length > 0) || (failOn.includes("new-risk") && risk.length > 0);
749
+ return fails ? 1 : 0;
750
+ }
751
+ export async function run(argv, deps = {}) {
752
+ const send = deps.send ?? ((p) => sendPayload(p));
753
+ const s = loadSettings();
754
+ const [cmd, ...rest] = argv;
755
+ if (cmd === "config")
756
+ return configCommand(rest, s);
757
+ if (cmd === "prove")
758
+ return proveCommand(rest[0], s);
759
+ if (cmd === "hosts")
760
+ return hostsCommand(rest, s);
761
+ if (cmd === "tls")
762
+ return tlsCommand(rest, deps.handshake, deps.ssh);
763
+ if (cmd === "diff")
764
+ return diffCommand(rest);
765
+ if (cmd === "evidence")
766
+ return evidenceCommand(rest, VERSION, { hs: deps.handshake, ssh: deps.ssh, pick: deps.pick });
767
+ const offline = argv.includes("--offline");
768
+ const sharing = sharingState(s, { offline });
769
+ if (cmd === "cloud") {
770
+ const out = await cloudCommand(rest, deps.cloudRunner);
771
+ await finishRun(out.facts, out.stateKey, out.state, s, sharing, send);
772
+ return out.code;
773
+ }
774
+ if (cmd === "map") {
775
+ const { opts, error } = parseArgs(rest);
776
+ const str = (k) => (typeof opts[k] === "string" ? opts[k] : undefined);
777
+ const bad = error ?? checkMapFailOn(str("fail-on"));
778
+ if (bad) {
779
+ console.error(bad);
780
+ return 2;
781
+ }
782
+ if (opts.help) {
783
+ process.stdout.write(HELP);
784
+ return 0;
785
+ }
786
+ const out = await runMap({
787
+ scopePath: str("scope"),
788
+ outDir: str("out") ?? "benthic-map",
789
+ cwd: process.cwd(),
790
+ version: VERSION,
791
+ settings: s,
792
+ sharingOn: sharing === "on",
793
+ interactive: deps.interactive ?? Boolean(process.stdin.isTTY),
794
+ });
795
+ await finishRun(out.facts, out.stateKey, out.state, s, sharing, send);
796
+ if (str("fail-on") === "broken" && out.report && out.report.counts[1] > 0)
797
+ return 1;
798
+ return out.code;
799
+ }
800
+ if (cmd === "image") {
801
+ const { opts, dir, error } = parseArgs(rest);
802
+ if (error) {
803
+ console.error(error);
804
+ return 2;
805
+ }
806
+ if (opts.help || !rest.length) {
807
+ process.stdout.write(HELP);
808
+ return rest.length ? 0 : 2;
809
+ }
810
+ let input;
811
+ try {
812
+ const cache = { scanner: VERSION, enabled: opts["no-cache"] !== true };
813
+ const img = looksLikeImageRef(dir) ? await loadFromRegistry(dir, { platform: typeof opts.platform === "string" ? opts.platform : undefined, cache }) : await loadImage(dir, cache);
814
+ input = imageScanInput(img, dir);
815
+ }
816
+ catch (e) {
817
+ console.error(e instanceof Error ? e.message : String(e));
818
+ return 2;
819
+ }
820
+ const r = scanCommand(rest, input);
821
+ await finishRun(r.facts, r.stateKey, r.state, s, sharing, send);
822
+ return r.code;
823
+ }
824
+ const r = scanCommand(argv);
825
+ await finishRun(r.facts, r.stateKey, r.state, s, sharing, send);
826
+ return r.code;
827
+ }
828
+ const invoked = process.argv[1] ?? "";
829
+ if (/cli\.(ts|js)$/.test(invoked) || /(benthic|quantum-scan)$/.test(invoked)) {
830
+ run(process.argv.slice(2)).then((code) => (process.exitCode = code), (e) => {
831
+ console.error(e instanceof Error ? e.message : e);
832
+ process.exitCode = 2;
833
+ });
834
+ }