shield-llm 0.4.0 → 0.5.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.
package/dist/cli.js CHANGED
@@ -1,11 +1,16 @@
1
1
  import { createRequire as __cjs_createRequire } from "module"; import { fileURLToPath as __cjs_fileURLToPath } from "url"; import { dirname as __cjs_dirname } from "path"; const __filename = __cjs_fileURLToPath(import.meta.url); const __dirname = __cjs_dirname(__filename); const require = __cjs_createRequire(import.meta.url);
2
2
  import {
3
+ CONSENT_SCOPES,
3
4
  ConfigError,
4
5
  ConfigSchema,
6
+ FileCheckpointStore,
5
7
  Scanner,
6
8
  analyzeJudgeHealth,
9
+ buildAuthFromFlags,
7
10
  buildTargetConfig,
8
11
  calculateComplianceScore,
12
+ computeCatalogHash,
13
+ computeScanKey,
9
14
  createTargetClient,
10
15
  deserializeAttack,
11
16
  deserializeMultiTurnAttack,
@@ -16,16 +21,20 @@ import {
16
21
  formatSarif,
17
22
  generatePdf,
18
23
  loadConfig,
19
- loadSystemPrompt
20
- } from "./chunk-DVOKN4JV.js";
21
- import "./chunk-WM5Z3SXV.js";
24
+ loadSystemPrompt,
25
+ parseSegmentKey,
26
+ parseSnapshot,
27
+ resolveOfflinePosition,
28
+ summarizeAttackErrors
29
+ } from "./chunk-IB7T5OJ2.js";
30
+ import "./chunk-I7M3BZK7.js";
22
31
 
23
32
  // src/cli.ts
24
33
  import "dotenv/config";
25
34
  import { Command, CommanderError } from "commander";
26
35
 
27
36
  // package.json
28
- var version = "0.4.0";
37
+ var version = "0.5.0";
29
38
 
30
39
  // src/credentials.ts
31
40
  import {
@@ -37,7 +46,6 @@ import {
37
46
  } from "fs";
38
47
  import { join } from "path";
39
48
  import { homedir } from "os";
40
- var DEFAULT_API_URL = "https://shield-llm.com";
41
49
  function getConfigDir() {
42
50
  const home = process.env.SHIELD_LLM_HOME ?? homedir();
43
51
  return join(home, ".shield-llm");
@@ -54,15 +62,22 @@ function loadCredentials() {
54
62
  if (!parsed.apiKey || typeof parsed.apiKey !== "string") return null;
55
63
  return {
56
64
  apiKey: parsed.apiKey,
57
- apiUrl: parsed.apiUrl ?? DEFAULT_API_URL
65
+ // No public-SaaS default: Shield LLM is self-hosted, so a missing URL
66
+ // stays empty and resolveApiUrl() throws rather than guessing a host.
67
+ apiUrl: typeof parsed.apiUrl === "string" ? parsed.apiUrl : ""
58
68
  };
59
69
  } catch {
60
70
  return null;
61
71
  }
62
72
  }
63
73
  function resolveApiUrl(stored, override) {
64
- const raw = override ?? process.env.SHIELD_API_URL ?? stored ?? DEFAULT_API_URL;
65
- return raw.trim().replace(/\/+$/, "");
74
+ const explicit = override ?? process.env.SHIELD_API_URL ?? stored;
75
+ if (explicit && explicit.trim()) {
76
+ return explicit.trim().replace(/\/+$/, "");
77
+ }
78
+ throw new ConfigError(
79
+ "No Shield LLM backend URL is configured. Point the CLI at your self-hosted instance via `--api-url`, the SHIELD_API_URL env var, or `shield-llm login --api-url <url> --key <key>`."
80
+ );
66
81
  }
67
82
  function saveCredentials(creds) {
68
83
  const dir = getConfigDir();
@@ -110,15 +125,10 @@ async function fetchAttacks(args) {
110
125
  "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
111
126
  );
112
127
  }
113
- if (res.status === 403) {
114
- const body = await res.json().catch(() => ({}));
115
- throw new Error(
116
- body.error ?? "Plan does not allow this preset. Upgrade required."
117
- );
118
- }
119
128
  if (!res.ok) {
129
+ const body = await res.json().catch(() => ({}));
120
130
  throw new Error(
121
- `Backend returned HTTP ${res.status} fetching the attack catalogue.`
131
+ body.error ?? `Backend returned HTTP ${res.status} fetching the attack catalogue.`
122
132
  );
123
133
  }
124
134
  try {
@@ -129,7 +139,10 @@ async function fetchAttacks(args) {
129
139
  deserializeMultiTurnAttack
130
140
  ),
131
141
  source: "backend",
132
- catalogVersion: body.catalogVersion
142
+ catalogVersion: body.catalogVersion,
143
+ ...body.attackPackVersion && {
144
+ attackPackVersion: body.attackPackVersion
145
+ }
133
146
  };
134
147
  } catch (err) {
135
148
  const reason = err instanceof Error ? err.message : "Unknown error";
@@ -215,10 +228,472 @@ Attack catalogue \u2014 ${total} attack(s)${wanted ? ` (severity: ${wanted})` :
215
228
  );
216
229
  }
217
230
 
231
+ // src/commands/benchmark.ts
232
+ import { writeFileSync as writeFileSync2 } from "fs";
233
+ import { confirm, select } from "@inquirer/prompts";
234
+
235
+ // src/benchmark/api.ts
236
+ var BenchmarkApiError = class extends Error {
237
+ constructor(status, body) {
238
+ const detail = typeof body.message === "string" ? body.message : typeof body.error === "string" ? body.error : `HTTP ${status}`;
239
+ super(detail);
240
+ this.name = "BenchmarkApiError";
241
+ this.status = status;
242
+ this.body = body;
243
+ }
244
+ };
245
+ async function request(creds, method, path, body) {
246
+ let res;
247
+ try {
248
+ res = await fetch(`${creds.apiUrl}${path}`, {
249
+ method,
250
+ headers: {
251
+ Authorization: `Bearer ${creds.apiKey}`,
252
+ ...body !== void 0 && { "Content-Type": "application/json" }
253
+ },
254
+ ...body !== void 0 && { body: JSON.stringify(body) }
255
+ });
256
+ } catch (err) {
257
+ const reason = err instanceof Error ? err.message : "Unknown error";
258
+ throw new Error(
259
+ `Could not reach the Shield LLM backend at ${creds.apiUrl} (${reason}).`
260
+ );
261
+ }
262
+ const json = await res.json().catch(() => ({}));
263
+ if (!res.ok) {
264
+ if (res.status === 401) {
265
+ throw new BenchmarkApiError(401, {
266
+ error: "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
267
+ });
268
+ }
269
+ if (res.status === 404 && json.error === "Not found") {
270
+ throw new BenchmarkApiError(404, {
271
+ error: "Benchmark module is not enabled on this backend (NEXT_PUBLIC_MODULE_BENCHMARK)."
272
+ });
273
+ }
274
+ throw new BenchmarkApiError(res.status, json);
275
+ }
276
+ return json;
277
+ }
278
+ function listCohorts(creds) {
279
+ return request(
280
+ creds,
281
+ "GET",
282
+ "/api/benchmark/cohorts"
283
+ );
284
+ }
285
+ function createCohort(creds, args) {
286
+ return request(
287
+ creds,
288
+ "POST",
289
+ "/api/benchmark/cohorts",
290
+ args
291
+ );
292
+ }
293
+ function getCohort(creds, cohortId) {
294
+ return request(
295
+ creds,
296
+ "GET",
297
+ `/api/benchmark/cohorts/${encodeURIComponent(cohortId)}`
298
+ );
299
+ }
300
+ function grantConsent(creds, args) {
301
+ return request(
302
+ creds,
303
+ "POST",
304
+ `/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/targets/${encodeURIComponent(args.targetId)}/consent`,
305
+ { scopes: args.scopes, grantedBy: args.grantedBy }
306
+ );
307
+ }
308
+ function revokeConsent(creds, args) {
309
+ return request(
310
+ creds,
311
+ "DELETE",
312
+ `/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/targets/${encodeURIComponent(args.targetId)}/consent`
313
+ );
314
+ }
315
+ function previewSubmission(creds, args) {
316
+ return request(
317
+ creds,
318
+ "POST",
319
+ `/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/submissions/preview`,
320
+ { scanId: args.scanId, targetId: args.targetId }
321
+ );
322
+ }
323
+ function submitAggregate(creds, args) {
324
+ return request(
325
+ creds,
326
+ "POST",
327
+ `/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/submissions`,
328
+ { scanId: args.scanId, targetId: args.targetId }
329
+ );
330
+ }
331
+ function exportSnapshot(creds, cohortId) {
332
+ return request(
333
+ creds,
334
+ "POST",
335
+ `/api/benchmark/cohorts/${encodeURIComponent(cohortId)}/snapshot`
336
+ );
337
+ }
338
+ function getPosition(creds, cohortId, query) {
339
+ const params = new URLSearchParams();
340
+ if ("scanId" in query) {
341
+ params.set("scanId", query.scanId);
342
+ params.set("targetId", query.targetId);
343
+ } else {
344
+ params.set("score", String(query.score));
345
+ params.set("segmentKey", query.segmentKey);
346
+ }
347
+ return request(
348
+ creds,
349
+ "GET",
350
+ `/api/benchmark/cohorts/${encodeURIComponent(cohortId)}/position?${params.toString()}`
351
+ );
352
+ }
353
+
354
+ // src/benchmark/format.ts
355
+ var LABELS = {
356
+ above_p75: "Reinforced posture (above the 3rd quartile)",
357
+ p25_p75: "Within cohort average",
358
+ below_p25: "Above-median exposure"
359
+ };
360
+ function ordinal(n) {
361
+ const rounded = Math.round(n);
362
+ const mod100 = rounded % 100;
363
+ if (mod100 >= 11 && mod100 <= 13) return `${rounded}th`;
364
+ switch (rounded % 10) {
365
+ case 1:
366
+ return `${rounded}st`;
367
+ case 2:
368
+ return `${rounded}nd`;
369
+ case 3:
370
+ return `${rounded}rd`;
371
+ default:
372
+ return `${rounded}th`;
373
+ }
374
+ }
375
+ function formatPosition(position, attackPackVersion) {
376
+ if (position.status === "insufficient_cohort") {
377
+ return `Benchmark building (N=${position.n}/${position.kMin}) \u2014 position unavailable below the k-anonymity threshold.`;
378
+ }
379
+ const percentile = position.clamped === "low" ? `\u2264 ${ordinal(position.percentile)} percentile` : position.clamped === "high" ? `\u2265 ${ordinal(position.percentile)} percentile` : `${ordinal(position.percentile)} percentile`;
380
+ const scope = position.generalizationLevel === 0 ? "exact segment" : position.segmentKey === "s1|*|*|*|*|*" ? "whole cohort" : `generalized segment ${position.segmentKey}`;
381
+ return [
382
+ `${percentile} \u2014 ${LABELS[position.labelKey] ?? position.labelKey}`,
383
+ `vs ${position.n} comparable organizations \xB7 ${scope} \xB7 attack pack v${attackPackVersion}`
384
+ ].join("\n");
385
+ }
386
+
387
+ // src/benchmark/snapshot.ts
388
+ import { readFileSync as readFileSync2 } from "fs";
389
+ import { createPublicKey, verify } from "crypto";
390
+ function verifyAndLoadSnapshot(args) {
391
+ const bytes = readFileSync2(args.snapshotPath);
392
+ const signature = Buffer.from(
393
+ readFileSync2(args.signaturePath, "utf8").trim(),
394
+ "base64"
395
+ );
396
+ let publicKey;
397
+ try {
398
+ publicKey = createPublicKey(readFileSync2(args.publicKeyPath, "utf8"));
399
+ } catch (err) {
400
+ throw new Error(
401
+ `Could not load the public key at ${args.publicKeyPath}: ${err instanceof Error ? err.message : String(err)}`
402
+ );
403
+ }
404
+ if (publicKey.asymmetricKeyType !== "ed25519") {
405
+ throw new Error(
406
+ `Public key must be Ed25519 (got ${publicKey.asymmetricKeyType ?? "unknown"})`
407
+ );
408
+ }
409
+ const valid = verify(null, bytes, publicKey, signature);
410
+ if (!valid) {
411
+ throw new Error(
412
+ "Snapshot signature verification FAILED \u2014 refusing to compute a position. The snapshot or its signature was modified, or the public key does not match the issuing instance."
413
+ );
414
+ }
415
+ return parseSnapshot(JSON.parse(bytes.toString("utf8")));
416
+ }
417
+
418
+ // src/commands/benchmark.ts
419
+ function requireCreds(opts) {
420
+ const stored = loadCredentials();
421
+ if (!stored) {
422
+ console.error(
423
+ "Not authenticated. Run `shield-llm login --key <api-key>` first."
424
+ );
425
+ setExitCode(2);
426
+ return null;
427
+ }
428
+ return {
429
+ apiUrl: resolveApiUrl(stored.apiUrl, opts.apiUrl),
430
+ apiKey: stored.apiKey
431
+ };
432
+ }
433
+ function reportError(err) {
434
+ if (err instanceof BenchmarkApiError) {
435
+ console.error(`Error: ${err.message}`);
436
+ if (Array.isArray(err.body.reasons)) {
437
+ console.error(`Reasons: ${err.body.reasons.join(", ")}`);
438
+ }
439
+ if (Array.isArray(err.body.violations)) {
440
+ console.error(
441
+ `Violations: ${err.body.violations.join("; ")}`
442
+ );
443
+ }
444
+ setExitCode(2);
445
+ } else {
446
+ console.error(err instanceof Error ? err.message : String(err));
447
+ setExitCode(3);
448
+ }
449
+ }
450
+ function parseScopes(raw) {
451
+ const scopes = [];
452
+ for (const part of raw.split(",").map((s) => s.trim()).filter(Boolean)) {
453
+ const full = part.startsWith("contribute:") ? part : `contribute:${part}`;
454
+ if (!CONSENT_SCOPES.includes(full)) {
455
+ throw new Error(
456
+ `Unknown consent scope "${part}". Valid scopes: ` + CONSENT_SCOPES.map((s) => s.replace("contribute:", "")).join(", ")
457
+ );
458
+ }
459
+ scopes.push(full);
460
+ }
461
+ return scopes;
462
+ }
463
+ async function cohortsCommand(opts) {
464
+ const creds = requireCreds(opts);
465
+ if (!creds) return;
466
+ try {
467
+ if (opts.create) {
468
+ const created = await createCohort(creds, {
469
+ displayName: String(opts.create),
470
+ ...opts.kMin !== void 0 && { kMin: Number(opts.kMin) }
471
+ });
472
+ console.log(
473
+ `Created cohort ${created.id} (attack pack v${created.activePackVersion}, k_min=${created.kMin})`
474
+ );
475
+ return;
476
+ }
477
+ const { cohorts } = await listCohorts(creds);
478
+ if (cohorts.length === 0) {
479
+ console.log(
480
+ "No cohorts yet. Create one with `shield-llm benchmark cohorts --create <name>`."
481
+ );
482
+ return;
483
+ }
484
+ for (const c of cohorts) {
485
+ console.log(
486
+ `${c.id} ${c.displayName} pack v${c.activePackVersion} k_min=${c.kMin} targets=${c.targetCount} submissions=${c.submissionCount}`
487
+ );
488
+ }
489
+ } catch (err) {
490
+ reportError(err);
491
+ }
492
+ }
493
+ async function consentShowCommand(opts) {
494
+ const creds = requireCreds(opts);
495
+ if (!creds) return;
496
+ try {
497
+ const preview = await previewSubmission(creds, {
498
+ cohortId: opts.cohort,
499
+ scanId: opts.scan,
500
+ targetId: opts.target
501
+ });
502
+ console.log("Exact payload that WOULD be submitted (nothing sent):");
503
+ console.log(JSON.stringify(preview.payload, null, 2));
504
+ if (preview.wouldReplace) {
505
+ console.log(
506
+ "Note: this would REPLACE the previous contribution of this organization for this attack pack version."
507
+ );
508
+ }
509
+ } catch (err) {
510
+ reportError(err);
511
+ }
512
+ }
513
+ async function consentGrantCommand(opts) {
514
+ const creds = requireCreds(opts);
515
+ if (!creds) return;
516
+ try {
517
+ const scopes = parseScopes(String(opts.scope ?? ""));
518
+ const granted = await grantConsent(creds, {
519
+ cohortId: opts.cohort,
520
+ targetId: opts.target,
521
+ scopes,
522
+ grantedBy: String(opts.by)
523
+ });
524
+ console.log(
525
+ `Consent recorded (${granted.id}) \u2014 scopes: ${granted.scopes.join(", ")}`
526
+ );
527
+ } catch (err) {
528
+ reportError(err);
529
+ }
530
+ }
531
+ async function consentRevokeCommand(opts) {
532
+ const creds = requireCreds(opts);
533
+ if (!creds) return;
534
+ try {
535
+ const result = await revokeConsent(creds, {
536
+ cohortId: opts.cohort,
537
+ targetId: opts.target
538
+ });
539
+ console.log(
540
+ result.revoked ? "Consent revoked. Future contributions are blocked until a new grant." : "No active consent to revoke."
541
+ );
542
+ } catch (err) {
543
+ reportError(err);
544
+ }
545
+ }
546
+ async function confirmAndSubmit(creds, args, opts = {}) {
547
+ const log = opts.log ?? console.log;
548
+ const preview = await previewSubmission(creds, args);
549
+ log("The following anonymous aggregate will be submitted to the cohort:");
550
+ log(JSON.stringify(preview.payload, null, 2));
551
+ if (preview.wouldReplace) {
552
+ log("This will REPLACE the organization's previous contribution.");
553
+ }
554
+ const approved = opts.yes === true ? true : await confirm({ message: "Submit this aggregate?", default: false });
555
+ if (!approved) {
556
+ log("Aborted \u2014 nothing was submitted. Your scan stays 100% local.");
557
+ return false;
558
+ }
559
+ const result = await submitAggregate(creds, args);
560
+ log(
561
+ result.replaced ? "Aggregate submitted (replaced the previous contribution)." : "Aggregate submitted."
562
+ );
563
+ return true;
564
+ }
565
+ async function submitCommand(opts) {
566
+ const creds = requireCreds(opts);
567
+ if (!creds) return;
568
+ try {
569
+ await confirmAndSubmit(
570
+ creds,
571
+ { cohortId: opts.cohort, scanId: opts.scan, targetId: opts.target },
572
+ { yes: Boolean(opts.yes) }
573
+ );
574
+ } catch (err) {
575
+ reportError(err);
576
+ }
577
+ }
578
+ async function positionCommand(opts) {
579
+ if (opts.offline || opts.snapshot) {
580
+ return offlinePositionCommand(opts);
581
+ }
582
+ const creds = requireCreds(opts);
583
+ if (!creds) return;
584
+ try {
585
+ const query = opts.scan && opts.target ? { scanId: String(opts.scan), targetId: String(opts.target) } : opts.score !== void 0 && opts.segmentKey ? { score: Number(opts.score), segmentKey: String(opts.segmentKey) } : null;
586
+ if (!query) {
587
+ console.error(
588
+ "Provide either --scan <id> --target <id>, or --score <n> --segment-key <key>."
589
+ );
590
+ setExitCode(2);
591
+ return;
592
+ }
593
+ const response = await getPosition(creds, opts.cohort, query);
594
+ if (response.scanEligibility && !response.scanEligibility.eligible) {
595
+ console.log(
596
+ `Warning: this scan is not benchmark-grade (${response.scanEligibility.reasons.join(", ")}) \u2014 position is indicative only.`
597
+ );
598
+ }
599
+ console.log(formatPosition(response.position, response.attackPackVersion));
600
+ } catch (err) {
601
+ reportError(err);
602
+ }
603
+ }
604
+ async function offlinePositionCommand(opts) {
605
+ try {
606
+ if (!opts.snapshot || !opts.publicKey) {
607
+ console.error(
608
+ "Offline mode requires --snapshot <file> and --public-key <pem> (pinned out-of-band)."
609
+ );
610
+ setExitCode(2);
611
+ return;
612
+ }
613
+ if (opts.score === void 0 || !opts.segmentKey) {
614
+ console.error(
615
+ "Offline mode requires --score <n> and --segment-key <key>."
616
+ );
617
+ setExitCode(2);
618
+ return;
619
+ }
620
+ const snapshot2 = verifyAndLoadSnapshot({
621
+ snapshotPath: String(opts.snapshot),
622
+ signaturePath: String(opts.sig ?? `${opts.snapshot}.sig`),
623
+ publicKeyPath: String(opts.publicKey)
624
+ });
625
+ console.log(
626
+ `Signature verified (Ed25519) \u2014 snapshot of ${snapshot2.computedAt}, attack pack v${snapshot2.attackPackVersion}.`
627
+ );
628
+ const position = resolveOfflinePosition(snapshot2, {
629
+ segment: parseSegmentKey(String(opts.segmentKey)),
630
+ score: Number(opts.score)
631
+ });
632
+ console.log(formatPosition(position, snapshot2.attackPackVersion));
633
+ } catch (err) {
634
+ console.error(err instanceof Error ? err.message : String(err));
635
+ setExitCode(2);
636
+ }
637
+ }
638
+ async function snapshotExportCommand(opts) {
639
+ const creds = requireCreds(opts);
640
+ if (!creds) return;
641
+ try {
642
+ const out = String(opts.out ?? "./snapshot.json");
643
+ const result = await exportSnapshot(creds, opts.cohort);
644
+ writeFileSync2(out, result.snapshotJson);
645
+ writeFileSync2(`${out}.sig`, result.signature + "\n");
646
+ writeFileSync2(`${out}.pub.pem`, result.publicKeyPem);
647
+ console.log(`Snapshot written: ${out} (+ .sig, + .pub.pem)`);
648
+ console.log(
649
+ "Distribute the public key through a separate, trusted channel and pin it on the verifying side."
650
+ );
651
+ } catch (err) {
652
+ reportError(err);
653
+ }
654
+ }
655
+ async function interactiveSubmitFlow(creds, scanId, log) {
656
+ try {
657
+ const { cohorts } = await listCohorts(creds);
658
+ if (cohorts.length === 0) {
659
+ log(
660
+ "Benchmark: no cohort on this backend \u2014 create one with `shield-llm benchmark cohorts --create <name>`."
661
+ );
662
+ return;
663
+ }
664
+ const cohortId = cohorts.length === 1 ? cohorts[0].id : await select({
665
+ message: "Cohort to contribute to:",
666
+ choices: cohorts.map((c) => ({
667
+ name: `${c.displayName} (pack v${c.activePackVersion})`,
668
+ value: c.id
669
+ }))
670
+ });
671
+ const detail = await getCohort(creds, cohortId);
672
+ if (detail.targets.length === 0) {
673
+ log(
674
+ "Benchmark: this cohort has no declared organizations yet \u2014 add targets in the dashboard or API first."
675
+ );
676
+ return;
677
+ }
678
+ const targetId = await select({
679
+ message: "Organization this scan belongs to:",
680
+ choices: detail.targets.map((t) => ({
681
+ name: `${t.displayName}${t.consent ? "" : " (no consent on record)"}`,
682
+ value: t.id
683
+ }))
684
+ });
685
+ await confirmAndSubmit(creds, { cohortId, scanId, targetId }, { log });
686
+ } catch (err) {
687
+ log(
688
+ `Benchmark submission skipped: ${err instanceof Error ? err.message : String(err)}`
689
+ );
690
+ }
691
+ }
692
+
218
693
  // src/commands/init.ts
219
- import { existsSync as existsSync2, writeFileSync as writeFileSync2 } from "fs";
694
+ import { existsSync as existsSync2, writeFileSync as writeFileSync3 } from "fs";
220
695
  import { resolve } from "path";
221
- import { select, input, confirm } from "@inquirer/prompts";
696
+ import { select as select2, input, confirm as confirm2 } from "@inquirer/prompts";
222
697
  var CONFIG_FILENAME = "shield.config.json";
223
698
  async function initCommand() {
224
699
  console.log("\nShield LLM \u2014 Configuration wizard\n");
@@ -231,7 +706,7 @@ async function initCommand() {
231
706
  }
232
707
  const configPath = resolve(CONFIG_FILENAME);
233
708
  if (existsSync2(configPath)) {
234
- const overwrite = await confirm({
709
+ const overwrite = await confirm2({
235
710
  message: `${CONFIG_FILENAME} already exists. Overwrite?`,
236
711
  default: false
237
712
  });
@@ -251,7 +726,7 @@ async function initCommand() {
251
726
  }
252
727
  }
253
728
  });
254
- const method = await select({
729
+ const method = await select2({
255
730
  message: "HTTP method:",
256
731
  choices: [
257
732
  { value: "POST", name: "POST (most chatbots)" },
@@ -263,7 +738,7 @@ async function initCommand() {
263
738
  const auth = await collectAuth();
264
739
  const { body, responseField } = await collectBodyShape();
265
740
  const customHeaders = await collectCustomHeaders();
266
- const preset = await select({
741
+ const preset = await select2({
267
742
  message: "Default scan preset:",
268
743
  choices: [
269
744
  { value: "owasp", name: "owasp \u2014 OWASP LLM Top 10 (10 tests)" },
@@ -298,12 +773,12 @@ async function initCommand() {
298
773
  Generated config is invalid:
299
774
  ${issues}`);
300
775
  console.error(
301
- "This is a bug \u2014 please report it at https://github.com/anthropics/shield-llm/issues"
776
+ "This is a bug \u2014 please report it at https://shield-llm.com/contact"
302
777
  );
303
778
  setExitCode(3);
304
779
  return;
305
780
  }
306
- writeFileSync2(configPath, JSON.stringify(result.data, null, 2) + "\n");
781
+ writeFileSync3(configPath, JSON.stringify(result.data, null, 2) + "\n");
307
782
  console.log(`
308
783
  \u2713 Config written to ${CONFIG_FILENAME}
309
784
  `);
@@ -316,7 +791,7 @@ ${issues}`);
316
791
  console.log("");
317
792
  }
318
793
  async function collectAuth() {
319
- const authType = await select({
794
+ const authType = await select2({
320
795
  message: "How does your endpoint authenticate?",
321
796
  choices: [
322
797
  { value: "none", name: "No authentication" },
@@ -367,7 +842,7 @@ async function collectAuth() {
367
842
  return { type: "oauth2", clientId, clientSecret, tokenUrl };
368
843
  }
369
844
  async function collectBodyShape() {
370
- const shape = await select({
845
+ const shape = await select2({
371
846
  message: "Request body shape:",
372
847
  choices: [
373
848
  {
@@ -393,7 +868,7 @@ async function collectBodyShape() {
393
868
  default: "message"
394
869
  });
395
870
  const body = { [promptField]: "{{prompt}}" };
396
- const addExtra = await confirm({
871
+ const addExtra = await confirm2({
397
872
  message: "Add extra fixed fields to the request body (assistant_id, thread_id, ...) ?",
398
873
  default: false
399
874
  });
@@ -408,7 +883,7 @@ async function collectBodyShape() {
408
883
  message: `Value for "${key}":`
409
884
  });
410
885
  body[key] = value;
411
- more = await confirm({ message: "Another field?", default: false });
886
+ more = await confirm2({ message: "Another field?", default: false });
412
887
  }
413
888
  }
414
889
  const responseField = await input({
@@ -418,7 +893,7 @@ async function collectBodyShape() {
418
893
  return { body, responseField };
419
894
  }
420
895
  async function collectCustomHeaders() {
421
- const add = await confirm({
896
+ const add = await confirm2({
422
897
  message: "Add custom request headers?",
423
898
  default: false
424
899
  });
@@ -435,7 +910,7 @@ async function collectCustomHeaders() {
435
910
  });
436
911
  warnIfHardcodedSecret(value);
437
912
  headers[name] = value;
438
- more = await confirm({ message: "Another header?", default: false });
913
+ more = await confirm2({ message: "Another header?", default: false });
439
914
  }
440
915
  return headers;
441
916
  }
@@ -460,9 +935,8 @@ async function loginCommand(opts) {
460
935
  console.log(`Credentials saved to ${getCredentialsPath()}`);
461
936
  try {
462
937
  const res = await fetch(`${apiUrl}/api/cli/scans`, {
463
- method: "POST",
938
+ method: "GET",
464
939
  headers: {
465
- "Content-Type": "application/json",
466
940
  Authorization: `Bearer ${key}`
467
941
  }
468
942
  });
@@ -471,10 +945,7 @@ async function loginCommand(opts) {
471
945
  "Warning: API key appears to be invalid. Check your key and try again."
472
946
  );
473
947
  } else if (res.ok) {
474
- const data = await res.json();
475
- console.log(
476
- `Authenticated to ${apiUrl}! Plan: ${data.plan} (${data.remaining}/${data.limit} scans remaining)`
477
- );
948
+ console.log(`Authenticated to ${apiUrl}!`);
478
949
  }
479
950
  } catch {
480
951
  console.log(
@@ -527,20 +998,31 @@ async function presetsCommand(opts) {
527
998
  }
528
999
  console.log("\nAvailable presets:\n");
529
1000
  for (const preset of presets) {
530
- const lock = preset.allowed ? "" : " (upgrade required)";
531
1001
  console.log(
532
- ` ${preset.id.padEnd(12)} ${preset.name.padEnd(20)} ${preset.description}${lock}`
1002
+ ` ${preset.id.padEnd(12)} ${preset.name.padEnd(20)} ${preset.description}`
533
1003
  );
534
1004
  }
535
1005
  console.log("");
536
1006
  }
537
1007
 
538
1008
  // src/commands/report.ts
539
- import { writeFileSync as writeFileSync3 } from "fs";
1009
+ import { writeFileSync as writeFileSync4 } from "fs";
540
1010
  import { resolve as resolve2 } from "path";
1011
+ function verificationLabel(v) {
1012
+ if (v.verificationStatus === "fixed") {
1013
+ return `\u2713 Fixed & verified${v.verifiedAt ? ` (${v.verifiedAt.slice(0, 10)})` : ""}`;
1014
+ }
1015
+ if (v.verificationStatus === "still_vulnerable") {
1016
+ return `\u2717 Still vulnerable${v.verifiedAt ? ` (${v.verifiedAt.slice(0, 10)})` : ""}`;
1017
+ }
1018
+ return "\u2014";
1019
+ }
541
1020
  function renderScanMarkdown(scan) {
542
1021
  const detected = scan.vulns.filter((v) => v.status === "DETECTED");
543
1022
  const passed = scan.vulns.length - detected.length;
1023
+ const verifiedFixed = detected.filter(
1024
+ (v) => v.verificationStatus === "fixed"
1025
+ ).length;
544
1026
  const lines = [
545
1027
  `# Shield LLM scan ${scan.id}`,
546
1028
  "",
@@ -548,6 +1030,9 @@ function renderScanMarkdown(scan) {
548
1030
  `- Score: **${scan.score}** (${scan.grade})`,
549
1031
  `- Date: ${scan.createdAt}`,
550
1032
  `- Tests: ${scan.testsRun}/${scan.testsTotal} run, ${detected.length} vulnerable, ${passed} secure`,
1033
+ ...verifiedFixed > 0 ? [
1034
+ `- Verified fixes: ${verifiedFixed}/${detected.length} (shield-llm retest)`
1035
+ ] : [],
551
1036
  "",
552
1037
  "## Vulnerabilities detected",
553
1038
  ""
@@ -555,11 +1040,11 @@ function renderScanMarkdown(scan) {
555
1040
  if (detected.length === 0) {
556
1041
  lines.push("_None_");
557
1042
  } else {
558
- lines.push("| Severity | Name | Notes |");
559
- lines.push("|---|---|---|");
1043
+ lines.push("| Severity | Name | Verification | Notes |");
1044
+ lines.push("|---|---|---|---|");
560
1045
  for (const v of detected) {
561
1046
  lines.push(
562
- `| ${v.severity} | ${v.name} | ${(v.description ?? "").slice(0, 80)} |`
1047
+ `| ${v.severity} | ${v.name} | ${verificationLabel(v)} | ${(v.description ?? "").slice(0, 80)} |`
563
1048
  );
564
1049
  }
565
1050
  }
@@ -615,17 +1100,13 @@ async function reportCommand(scanId, opts) {
615
1100
  content = JSON.stringify(scan, null, 2);
616
1101
  }
617
1102
  if (opts.outputFile) {
618
- writeFileSync3(resolve2(opts.outputFile), content, "utf-8");
1103
+ writeFileSync4(resolve2(opts.outputFile), content, "utf-8");
619
1104
  console.error(`Report written to ${opts.outputFile}`);
620
1105
  } else {
621
1106
  console.log(content);
622
1107
  }
623
1108
  }
624
1109
 
625
- // src/commands/scan.ts
626
- import { writeFileSync as writeFileSync4 } from "fs";
627
- import { resolve as resolve3 } from "path";
628
-
629
1110
  // src/custom-tests-loader.ts
630
1111
  async function fetchCustomTests(apiUrl, apiKey) {
631
1112
  const res = await fetch(`${apiUrl}/api/cli/tests`, {
@@ -674,52 +1155,75 @@ function truncateInput(input2) {
674
1155
  }))
675
1156
  };
676
1157
  }
1158
+ var TRANSIENT_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
677
1159
  var BackendEvaluator = class {
678
- constructor(apiUrl, apiKey) {
1160
+ constructor(apiUrl, apiKey, opts) {
679
1161
  this.apiUrl = apiUrl;
680
1162
  this.apiKey = apiKey;
1163
+ this.maxRetries = opts?.maxRetries ?? 3;
1164
+ this.backoffMs = opts?.backoffMs ?? 1e3;
1165
+ this.maxBackoffMs = opts?.maxBackoffMs ?? 3e4;
1166
+ this.sleep = opts?.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
681
1167
  }
682
1168
  async evaluate(input2) {
683
- const response = await fetch(`${this.apiUrl}/api/cli/evaluate`, {
684
- method: "POST",
685
- headers: {
686
- "Content-Type": "application/json",
687
- Authorization: `Bearer ${this.apiKey}`
688
- },
689
- body: JSON.stringify(truncateInput(input2))
690
- });
691
- if (response.status === 401) {
692
- throw new Error(
693
- "Invalid API key. Run `shield-llm login` to re-authenticate."
694
- );
695
- }
696
- if (response.status === 403) {
697
- const body = await response.json().catch(() => ({}));
698
- throw new Error(
699
- body.error ?? `Scan quota exceeded. Upgrade your plan at ${DEFAULT_API_URL}/settings`
700
- );
701
- }
702
- if (response.status === 429) {
703
- throw new Error("Rate limit exceeded. Please wait and try again.");
704
- }
705
- if (!response.ok) {
706
- const body = await response.text().catch(() => "");
707
- let userMessage = `Backend evaluation failed (HTTP ${response.status}). Please try again.`;
708
- try {
709
- const parsed = JSON.parse(body);
710
- if (typeof parsed.error === "string" && parsed.error.length > 0) {
711
- userMessage = `Backend evaluation failed (${response.status}): ${parsed.error}`;
712
- }
713
- } catch {
714
- if (body) {
715
- console.error(
716
- `[BackendEvaluator] Non-JSON ${response.status} response body (first 500 chars): ${body.slice(0, 500)}`
717
- );
1169
+ const body = JSON.stringify(truncateInput(input2));
1170
+ let attempt = 0;
1171
+ for (; ; ) {
1172
+ const response = await fetch(`${this.apiUrl}/api/cli/evaluate`, {
1173
+ method: "POST",
1174
+ headers: {
1175
+ "Content-Type": "application/json",
1176
+ Authorization: `Bearer ${this.apiKey}`
1177
+ },
1178
+ body
1179
+ });
1180
+ if (TRANSIENT_STATUSES.has(response.status) && attempt < this.maxRetries) {
1181
+ const waitMs = this.backoffFor(response, attempt);
1182
+ attempt++;
1183
+ await this.sleep(waitMs);
1184
+ continue;
1185
+ }
1186
+ if (response.status === 401) {
1187
+ throw new Error(
1188
+ "Invalid API key. Run `shield-llm login` to re-authenticate."
1189
+ );
1190
+ }
1191
+ if (response.status === 403) {
1192
+ const errBody = await response.json().catch(() => ({}));
1193
+ throw new Error(errBody.error ?? "Access denied by the backend (403).");
1194
+ }
1195
+ if (response.status === 429) {
1196
+ throw new Error(
1197
+ "Rate limit exceeded after retries. Please wait and try again."
1198
+ );
1199
+ }
1200
+ if (!response.ok) {
1201
+ const errText = await response.text().catch(() => "");
1202
+ let userMessage = `Backend evaluation failed (HTTP ${response.status}). Please try again.`;
1203
+ try {
1204
+ const parsed = JSON.parse(errText);
1205
+ if (typeof parsed.error === "string" && parsed.error.length > 0) {
1206
+ userMessage = `Backend evaluation failed (${response.status}): ${parsed.error}`;
1207
+ }
1208
+ } catch {
1209
+ if (errText) {
1210
+ console.error(
1211
+ `[BackendEvaluator] Non-JSON ${response.status} response body (first 500 chars): ${errText.slice(0, 500)}`
1212
+ );
1213
+ }
718
1214
  }
1215
+ throw new Error(userMessage);
719
1216
  }
720
- throw new Error(userMessage);
1217
+ return response.json();
721
1218
  }
722
- return response.json();
1219
+ }
1220
+ /** Backoff for one retry: a 429 Retry-After (seconds) when present, else
1221
+ * exponential (backoffMs · 2^attempt). Both clamped to maxBackoffMs. */
1222
+ backoffFor(response, attempt) {
1223
+ const header = response.headers.get("retry-after");
1224
+ const retryAfterSec = header ? parseInt(header, 10) : NaN;
1225
+ const base = response.status === 429 && Number.isFinite(retryAfterSec) && retryAfterSec > 0 ? retryAfterSec * 1e3 : this.backoffMs * 2 ** attempt;
1226
+ return Math.min(base, this.maxBackoffMs);
723
1227
  }
724
1228
  };
725
1229
 
@@ -735,6 +1239,14 @@ function handleEvent(event) {
735
1239
  chalk.cyan(`Starting scan (${event.totalAttacks} attacks)...`)
736
1240
  );
737
1241
  break;
1242
+ case "scan:resume":
1243
+ spinner.info(
1244
+ chalk.cyan(
1245
+ `Resuming \u2014 ${event.completed}/${event.total} attacks already done, running the rest`
1246
+ )
1247
+ );
1248
+ spinner.start();
1249
+ break;
738
1250
  case "attack:start":
739
1251
  currentAttackName = event.attack.name;
740
1252
  spinner.text = chalk.cyan(
@@ -765,6 +1277,11 @@ function handleEvent(event) {
765
1277
  `${currentAttackName} \u2014 turn ${event.turn}/${event.totalTurns}`
766
1278
  );
767
1279
  break;
1280
+ case "attack:retry":
1281
+ spinner.text = chalk.yellow(
1282
+ `${currentAttackName} \u2014 ${event.reason === "rate_limited" ? "rate limited" : "server error"}, backing off ${(event.waitMs / 1e3).toFixed(1)}s (retry ${event.attempt}/${event.maxRetries})`
1283
+ );
1284
+ break;
768
1285
  case "scan:rate_limited":
769
1286
  spinner.fail(
770
1287
  chalk.red(
@@ -864,6 +1381,403 @@ function gradeColor(grade) {
864
1381
  }
865
1382
  }
866
1383
 
1384
+ // src/lib/format.ts
1385
+ function truncate(str, max) {
1386
+ const oneLine = str.replace(/\n/g, " ").trim();
1387
+ return oneLine.length <= max ? oneLine : oneLine.slice(0, max - 3) + "...";
1388
+ }
1389
+
1390
+ // src/retest-core.ts
1391
+ function selectRetestableFindings(vulns, filter) {
1392
+ const seen = /* @__PURE__ */ new Set();
1393
+ const findings = [];
1394
+ for (const v of vulns) {
1395
+ if (v.status !== "DETECTED") continue;
1396
+ if (v.captureStatus === "pending" || v.captureStatus === "rate_limited") {
1397
+ continue;
1398
+ }
1399
+ const key = v.vulnerabilityType ?? v.name;
1400
+ if (seen.has(key)) continue;
1401
+ seen.add(key);
1402
+ findings.push({
1403
+ attackId: v.vulnerabilityType ?? null,
1404
+ name: v.name,
1405
+ severity: v.severity
1406
+ });
1407
+ }
1408
+ if (!filter || filter.length === 0) return findings;
1409
+ const wanted = new Set(filter);
1410
+ return findings.filter(
1411
+ (f) => f.attackId && wanted.has(f.attackId) || wanted.has(f.name)
1412
+ );
1413
+ }
1414
+ var CUSTOM_PREFIX = "custom_";
1415
+ function buildRetestPlan(findings, catalogue) {
1416
+ const plan = {
1417
+ singles: [],
1418
+ multiTurn: [],
1419
+ customs: [],
1420
+ unavailable: [],
1421
+ findingByResultId: /* @__PURE__ */ new Map()
1422
+ };
1423
+ for (const finding of findings) {
1424
+ if (finding.attackId?.startsWith(CUSTOM_PREFIX)) {
1425
+ const customName = finding.attackId.slice(CUSTOM_PREFIX.length);
1426
+ const test = catalogue.customTests.find((t) => t.name === customName);
1427
+ if (test) {
1428
+ plan.customs.push({ finding, test });
1429
+ plan.findingByResultId.set(`${CUSTOM_PREFIX}${test.name}`, finding);
1430
+ } else {
1431
+ plan.unavailable.push(finding);
1432
+ }
1433
+ continue;
1434
+ }
1435
+ const single = catalogue.attacks.find((a) => a.id === finding.attackId) ?? (finding.attackId ? void 0 : catalogue.attacks.find((a) => a.name === finding.name));
1436
+ if (single) {
1437
+ plan.singles.push({ finding, attack: single });
1438
+ plan.findingByResultId.set(single.id, finding);
1439
+ continue;
1440
+ }
1441
+ const multi = catalogue.multiTurnAttacks.find((a) => a.id === finding.attackId) ?? (finding.attackId ? void 0 : catalogue.multiTurnAttacks.find((a) => a.name === finding.name));
1442
+ if (multi) {
1443
+ plan.multiTurn.push({ finding, attack: multi });
1444
+ plan.findingByResultId.set(multi.id, finding);
1445
+ continue;
1446
+ }
1447
+ plan.unavailable.push(finding);
1448
+ }
1449
+ return plan;
1450
+ }
1451
+ var EVIDENCE_PROMPT_CAP = 6e3;
1452
+ var EVIDENCE_RESPONSE_CAP = 2500;
1453
+ var REASONING_CAP = 4500;
1454
+ function buildRetestOutcome(results, findingByResultId) {
1455
+ const outcome = { verifications: [], failed: [] };
1456
+ for (const result of results) {
1457
+ const finding = findingByResultId.get(result.id);
1458
+ if (!finding) continue;
1459
+ if (result.error || result.rateLimited) {
1460
+ outcome.failed.push({
1461
+ finding,
1462
+ error: result.error ?? "rate limited"
1463
+ });
1464
+ continue;
1465
+ }
1466
+ outcome.verifications.push({
1467
+ // For legacy findings attackId is the catalogue id we matched by name;
1468
+ // the server falls back to name-matching rows with null vulnerabilityType.
1469
+ attackId: finding.attackId ?? result.id,
1470
+ name: finding.name,
1471
+ vulnerable: result.vulnerable,
1472
+ evidence: JSON.stringify({
1473
+ prompt: truncate(result.prompt, EVIDENCE_PROMPT_CAP),
1474
+ response: truncate(result.response, EVIDENCE_RESPONSE_CAP)
1475
+ }),
1476
+ evaluationMethod: result.llmEvaluation?.evaluationMethod,
1477
+ confidence: result.llmEvaluation?.confidence,
1478
+ reasoning: result.llmEvaluation?.reasoning ? truncate(result.llmEvaluation.reasoning, REASONING_CAP) : void 0
1479
+ });
1480
+ }
1481
+ return outcome;
1482
+ }
1483
+ function decideExitCode(summary) {
1484
+ if (summary.stillVulnerable > 0) return 1;
1485
+ if (summary.fixed > 0) return 0;
1486
+ return 3;
1487
+ }
1488
+
1489
+ // src/commands/retest.ts
1490
+ function findingLabel(finding) {
1491
+ return `${finding.name} (${finding.severity})`;
1492
+ }
1493
+ async function retestCommand(scanId, opts) {
1494
+ try {
1495
+ if (opts.ci) opts.progress = false;
1496
+ const info = (msg) => {
1497
+ if (opts.ci) console.error(msg);
1498
+ else console.log(msg);
1499
+ };
1500
+ const stored = loadCredentials();
1501
+ const credentials = stored ? { ...stored, apiUrl: resolveApiUrl(stored.apiUrl, opts.apiUrl) } : null;
1502
+ if (!credentials) {
1503
+ console.error("Not logged in. Run `shield-llm login` to authenticate.");
1504
+ setExitCode(2);
1505
+ return;
1506
+ }
1507
+ let scan;
1508
+ try {
1509
+ const res = await fetch(
1510
+ `${credentials.apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}`,
1511
+ { headers: { Authorization: `Bearer ${credentials.apiKey}` } }
1512
+ );
1513
+ if (res.status === 401) {
1514
+ await res.text().catch(() => void 0);
1515
+ console.error(
1516
+ "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
1517
+ );
1518
+ setExitCode(2);
1519
+ return;
1520
+ }
1521
+ if (res.status === 403) {
1522
+ const body = await res.json().catch(() => ({}));
1523
+ console.error(body.error ?? "Plan does not allow CLI access.");
1524
+ setExitCode(2);
1525
+ return;
1526
+ }
1527
+ if (res.status === 404) {
1528
+ await res.text().catch(() => void 0);
1529
+ console.error(`Scan "${scanId}" not found.`);
1530
+ setExitCode(2);
1531
+ return;
1532
+ }
1533
+ if (!res.ok) {
1534
+ await res.text().catch(() => void 0);
1535
+ console.error(`Backend returned HTTP ${res.status} fetching the scan.`);
1536
+ setExitCode(3);
1537
+ return;
1538
+ }
1539
+ scan = await res.json();
1540
+ } catch (err) {
1541
+ const msg = err instanceof Error ? err.message : "Unknown error";
1542
+ console.error(`Failed to reach backend: ${msg}`);
1543
+ setExitCode(3);
1544
+ return;
1545
+ }
1546
+ if (scan.status && scan.status !== "completed") {
1547
+ console.error(
1548
+ `Scan "${scanId}" is ${scan.status} \u2014 only completed scans can be retested.`
1549
+ );
1550
+ setExitCode(2);
1551
+ return;
1552
+ }
1553
+ const filter = opts.finding && opts.finding.length > 0 ? opts.finding : void 0;
1554
+ const findings = selectRetestableFindings(scan.vulns ?? [], filter);
1555
+ if (findings.length === 0) {
1556
+ if (filter) {
1557
+ console.error(
1558
+ `No detected finding matches ${filter.map((f) => `"${f}"`).join(", ")} in scan ${scanId}.`
1559
+ );
1560
+ setExitCode(2);
1561
+ return;
1562
+ }
1563
+ info(`Scan ${scanId} has no detected findings \u2014 nothing to retest.`);
1564
+ setExitCode(0);
1565
+ return;
1566
+ }
1567
+ const cliOverrides = {};
1568
+ if (opts.endpoint) {
1569
+ cliOverrides.endpoint = {
1570
+ url: opts.endpoint,
1571
+ auth: buildAuthFromFlags(opts),
1572
+ request: {
1573
+ method: "POST",
1574
+ body: opts.requestBody ? JSON.parse(opts.requestBody) : { message: "{{prompt}}" }
1575
+ },
1576
+ response: { field: opts.responseField ?? "response" }
1577
+ };
1578
+ }
1579
+ const config = loadConfig({ configPath: opts.config, cliOverrides });
1580
+ const systemPrompt = loadSystemPrompt(config);
1581
+ const endpointHost = safeHostname(config.endpoint?.url);
1582
+ if (scan.targetDomain && endpointHost && endpointHost !== scan.targetDomain) {
1583
+ console.error(
1584
+ `Warning: retesting against "${endpointHost}" but scan ${scanId} targeted "${scan.targetDomain}". Verification badges will reflect this endpoint.`
1585
+ );
1586
+ }
1587
+ const needsCustom = findings.some(
1588
+ (f) => f.attackId?.startsWith(CUSTOM_PREFIX)
1589
+ );
1590
+ let catalogue;
1591
+ try {
1592
+ const fetched = await fetchAttacks({
1593
+ apiUrl: credentials.apiUrl,
1594
+ apiKey: credentials.apiKey,
1595
+ preset: "full",
1596
+ includeMultiTurn: true
1597
+ });
1598
+ catalogue = {
1599
+ attacks: fetched.attacks,
1600
+ multiTurnAttacks: fetched.multiTurnAttacks,
1601
+ customTests: needsCustom ? await fetchCustomTests(credentials.apiUrl, credentials.apiKey) : []
1602
+ };
1603
+ } catch (err) {
1604
+ const msg = err instanceof Error ? err.message : "Unknown error";
1605
+ console.error(`Failed to fetch the attack catalogue: ${msg}`);
1606
+ setExitCode(3);
1607
+ return;
1608
+ }
1609
+ const plan = buildRetestPlan(findings, catalogue);
1610
+ const runnable = plan.singles.length + plan.multiTurn.length + plan.customs.length;
1611
+ for (const finding of plan.unavailable) {
1612
+ info(
1613
+ `Skipping ${findingLabel(finding)} \u2014 not replayable from the CLI (attack unavailable in the catalogue or custom test deleted).`
1614
+ );
1615
+ }
1616
+ if (runnable === 0) {
1617
+ console.error("None of the selected findings can be replayed.");
1618
+ setExitCode(3);
1619
+ return;
1620
+ }
1621
+ info(
1622
+ `Retesting ${runnable} finding(s) from scan ${scanId} against ${config.endpoint?.url ?? "target"}\u2026`
1623
+ );
1624
+ const evaluator = new BackendEvaluator(
1625
+ credentials.apiUrl,
1626
+ credentials.apiKey
1627
+ );
1628
+ const scanOptions = {
1629
+ target: buildTargetConfig(config),
1630
+ systemPrompt,
1631
+ preset: config.preset ?? "standard",
1632
+ attacks: plan.singles.map((s) => s.attack),
1633
+ multiTurnAttacks: plan.multiTurn.map((m) => m.attack),
1634
+ includeCrescendo: plan.multiTurn.length > 0,
1635
+ customTests: plan.customs.map((c) => c.test),
1636
+ concurrency: config.concurrency,
1637
+ delayMs: config.delayMs,
1638
+ attackTimeoutMs: config.attackTimeoutMs,
1639
+ maxConsecutiveFailures: config.maxConsecutiveFailures,
1640
+ maxRateLimitRetries: config.maxRateLimitRetries,
1641
+ rateLimitBackoffMs: config.rateLimitBackoffMs,
1642
+ rateLimitMaxBackoffMs: config.rateLimitMaxBackoffMs,
1643
+ evaluator
1644
+ };
1645
+ const onEvent = opts.progress !== false ? handleEvent : void 0;
1646
+ const scanner = new Scanner(scanOptions, onEvent);
1647
+ const report = await scanner.run();
1648
+ const outcome = buildRetestOutcome(report.attacks, plan.findingByResultId);
1649
+ let verify2 = null;
1650
+ let verifyError = null;
1651
+ if (outcome.verifications.length > 0) {
1652
+ try {
1653
+ const res = await fetch(
1654
+ `${credentials.apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}/verify`,
1655
+ {
1656
+ method: "POST",
1657
+ headers: {
1658
+ "Content-Type": "application/json",
1659
+ Authorization: `Bearer ${credentials.apiKey}`
1660
+ },
1661
+ body: JSON.stringify({
1662
+ targetUrl: config.endpoint?.url,
1663
+ results: outcome.verifications
1664
+ })
1665
+ }
1666
+ );
1667
+ if (!res.ok) {
1668
+ const body = await res.text().catch(() => "");
1669
+ verifyError = `HTTP ${res.status}: ${body.slice(0, 200)}`;
1670
+ } else {
1671
+ verify2 = await res.json();
1672
+ }
1673
+ } catch (err) {
1674
+ verifyError = err instanceof Error ? err.message : "Unknown error";
1675
+ }
1676
+ }
1677
+ const fixed = outcome.verifications.filter((v) => !v.vulnerable);
1678
+ const stillVulnerable = outcome.verifications.filter((v) => v.vulnerable);
1679
+ if (opts.ci) {
1680
+ console.log(
1681
+ JSON.stringify(
1682
+ {
1683
+ scanId,
1684
+ targetUrl: config.endpoint?.url,
1685
+ retested: outcome.verifications.length,
1686
+ fixed: fixed.length,
1687
+ stillVulnerable: stillVulnerable.length,
1688
+ results: outcome.verifications.map((v) => ({
1689
+ attackId: v.attackId,
1690
+ name: v.name,
1691
+ outcome: v.vulnerable ? "still_vulnerable" : "fixed"
1692
+ })),
1693
+ failed: outcome.failed.map((f) => ({
1694
+ attackId: f.finding.attackId,
1695
+ name: f.finding.name,
1696
+ error: f.error
1697
+ })),
1698
+ unavailable: plan.unavailable.map((f) => ({
1699
+ attackId: f.attackId,
1700
+ name: f.name
1701
+ })),
1702
+ verify: verify2 ?? void 0,
1703
+ verifyError: verifyError ?? void 0
1704
+ },
1705
+ null,
1706
+ 2
1707
+ )
1708
+ );
1709
+ } else {
1710
+ console.log("");
1711
+ for (const v of fixed) {
1712
+ console.log(` \u2713 FIXED & VERIFIED ${v.name}`);
1713
+ }
1714
+ for (const v of stillVulnerable) {
1715
+ console.log(` \u2717 STILL VULNERABLE ${v.name}`);
1716
+ }
1717
+ for (const f of outcome.failed) {
1718
+ console.log(
1719
+ ` \u26A0 NOT RETESTED ${findingLabel(f.finding)} \u2014 ${f.error}`
1720
+ );
1721
+ }
1722
+ for (const f of plan.unavailable) {
1723
+ console.log(` \u26A0 NOT RETESTED ${findingLabel(f)} \u2014 unavailable`);
1724
+ }
1725
+ console.log("");
1726
+ console.log(
1727
+ `Retest complete: ${fixed.length} fixed & verified, ${stillVulnerable.length} still vulnerable` + (outcome.failed.length + plan.unavailable.length > 0 ? `, ${outcome.failed.length + plan.unavailable.length} not retested` : "") + "."
1728
+ );
1729
+ if (verify2) {
1730
+ console.log(
1731
+ `Dashboard updated (${verify2.updated} finding(s) stamped).`
1732
+ );
1733
+ if (verify2.notFound.length > 0) {
1734
+ console.warn(
1735
+ `Warning: no matching dashboard row for: ${verify2.notFound.join(", ")}`
1736
+ );
1737
+ }
1738
+ }
1739
+ }
1740
+ if (verifyError) {
1741
+ console.error(
1742
+ `Warning: verdicts computed but NOT recorded on the dashboard: ${verifyError}`
1743
+ );
1744
+ setExitCode(3);
1745
+ return;
1746
+ }
1747
+ setExitCode(
1748
+ decideExitCode({
1749
+ fixed: fixed.length,
1750
+ stillVulnerable: stillVulnerable.length,
1751
+ failed: outcome.failed.length,
1752
+ unavailable: plan.unavailable.length
1753
+ })
1754
+ );
1755
+ return;
1756
+ } catch (error) {
1757
+ if (error instanceof ConfigError) {
1758
+ console.error(`Configuration error: ${error.message}`);
1759
+ setExitCode(2);
1760
+ return;
1761
+ }
1762
+ const msg = error instanceof Error ? error.message : "Unknown error";
1763
+ console.error(`Runtime error: ${msg}`);
1764
+ setExitCode(3);
1765
+ return;
1766
+ }
1767
+ }
1768
+ function safeHostname(url) {
1769
+ if (!url) return null;
1770
+ try {
1771
+ return new URL(url).hostname.replace(/^www\./, "");
1772
+ } catch {
1773
+ return null;
1774
+ }
1775
+ }
1776
+
1777
+ // src/commands/scan.ts
1778
+ import { writeFileSync as writeFileSync5 } from "fs";
1779
+ import { resolve as resolve3 } from "path";
1780
+
867
1781
  // src/lib/sanitize.ts
868
1782
  var DEFAULTS = {
869
1783
  responseMaxChars: 500,
@@ -904,36 +1818,8 @@ function sanitizeReportForDisk(report, opts = {}) {
904
1818
  };
905
1819
  }
906
1820
 
907
- // src/lib/format.ts
908
- function truncate(str, max) {
909
- const oneLine = str.replace(/\n/g, " ").trim();
910
- return oneLine.length <= max ? oneLine : oneLine.slice(0, max - 3) + "...";
911
- }
912
-
913
1821
  // src/commands/scan.ts
914
- function buildAuthFromFlags(opts) {
915
- if (!opts.auth) return void 0;
916
- switch (opts.auth) {
917
- case "bearer":
918
- if (!opts.token)
919
- throw new ConfigError("--token is required with --auth bearer");
920
- return { type: "bearer", token: opts.token };
921
- case "api-key":
922
- if (!opts.token)
923
- throw new ConfigError("--token is required with --auth api-key");
924
- return {
925
- type: "api-key",
926
- header: opts.authHeader ?? "X-API-Key",
927
- value: opts.token
928
- };
929
- // oauth2 requires too many params for CLI flags — use config file instead
930
- default:
931
- throw new ConfigError(
932
- `Unknown or unsupported auth type for CLI flags: "${opts.auth}". OAuth2 must be configured via shield.config.json.`
933
- );
934
- }
935
- }
936
- async function uploadReportToBackend(report, credentials, scanId) {
1822
+ async function uploadReportToBackend(report, credentials, scanId, attackPackVersion) {
937
1823
  const vulnerabilities = report.attacks.filter((a) => !a.error && !a.rateLimited).map((a) => ({
938
1824
  // attackId lets the backend validate against its known catalogue + the
939
1825
  // user's custom tests, rejecting fabricated vulnerability rows.
@@ -959,6 +1845,7 @@ async function uploadReportToBackend(report, credentials, scanId) {
959
1845
  const testsRun = report.attacks.filter(
960
1846
  (a) => !a.error && !a.rateLimited
961
1847
  ).length;
1848
+ const attackErrorSummary = summarizeAttackErrors(report.attacks);
962
1849
  const payload = {
963
1850
  scanId,
964
1851
  targetUrl: report.target,
@@ -967,6 +1854,11 @@ async function uploadReportToBackend(report, credentials, scanId) {
967
1854
  testsRun,
968
1855
  testsTotal: report.config.totalAttacks,
969
1856
  durationMs: report.durationMs,
1857
+ preset: report.config.preset,
1858
+ ...attackPackVersion && { attackPackVersion },
1859
+ ...attackErrorSummary && {
1860
+ attackErrors: { items: attackErrorSummary.items }
1861
+ },
970
1862
  vulnerabilities
971
1863
  };
972
1864
  const res = await fetch(`${credentials.apiUrl}/api/cli/reports`, {
@@ -981,8 +1873,30 @@ async function uploadReportToBackend(report, credentials, scanId) {
981
1873
  const body = await res.text().catch(() => "");
982
1874
  throw new Error(`HTTP ${res.status}: ${body.slice(0, 200)}`);
983
1875
  }
1876
+ const data = await res.json().catch(() => ({}));
1877
+ return {
1878
+ score: typeof data.score === "number" ? data.score : report.score,
1879
+ grade: data.grade ?? report.grade,
1880
+ droppedAttackIds: data.droppedAttackIds ?? 0
1881
+ };
1882
+ }
1883
+ async function reportScanFailure(credentials, scanId, reason) {
1884
+ try {
1885
+ await fetch(`${credentials.apiUrl}/api/cli/scans/${scanId}/fail`, {
1886
+ method: "POST",
1887
+ headers: {
1888
+ "Content-Type": "application/json",
1889
+ Authorization: `Bearer ${credentials.apiKey}`
1890
+ },
1891
+ body: JSON.stringify({ error: reason.slice(0, 2e3) })
1892
+ });
1893
+ } catch {
1894
+ }
984
1895
  }
985
1896
  async function scanCommand(opts) {
1897
+ let reservedScanId = null;
1898
+ let scanFinalized = false;
1899
+ let failTarget = null;
986
1900
  try {
987
1901
  if (opts.ci) {
988
1902
  opts.output = opts.output ?? "json";
@@ -1004,7 +1918,7 @@ async function scanCommand(opts) {
1004
1918
  setExitCode(2);
1005
1919
  return;
1006
1920
  }
1007
- let reservedScanId = null;
1921
+ failTarget = { apiUrl: credentials.apiUrl, apiKey: credentials.apiKey };
1008
1922
  try {
1009
1923
  const res = await fetch(`${credentials.apiUrl}/api/cli/scans`, {
1010
1924
  method: "POST",
@@ -1020,14 +1934,6 @@ async function scanCommand(opts) {
1020
1934
  setExitCode(2);
1021
1935
  return;
1022
1936
  }
1023
- if (res.status === 403) {
1024
- const body = await res.json().catch(() => ({}));
1025
- console.error(
1026
- body.error ?? `Monthly scan limit reached. Upgrade at ${DEFAULT_API_URL}/settings`
1027
- );
1028
- setExitCode(2);
1029
- return;
1030
- }
1031
1937
  if (!res.ok) {
1032
1938
  console.error(`Failed to start scan: HTTP ${res.status}`);
1033
1939
  setExitCode(3);
@@ -1035,9 +1941,7 @@ async function scanCommand(opts) {
1035
1941
  }
1036
1942
  const scanSlot = await res.json();
1037
1943
  reservedScanId = scanSlot.scanId;
1038
- info(
1039
- `Scan reserved (${scanSlot.remaining}/${scanSlot.limit} remaining this month)`
1040
- );
1944
+ info("Scan started");
1041
1945
  } catch (err) {
1042
1946
  const msg = err instanceof Error ? err.message : "Unknown error";
1043
1947
  console.error(`Failed to connect to backend: ${msg}`);
@@ -1089,11 +1993,26 @@ async function scanCommand(opts) {
1089
1993
  );
1090
1994
  if (remoteTests.length === 0) {
1091
1995
  info(
1092
- `No custom tests found in your dashboard. Create them at ${DEFAULT_API_URL}/tests`
1996
+ `No custom tests found in your dashboard. Create them at ${credentials.apiUrl}/tests`
1093
1997
  );
1094
1998
  } else {
1095
1999
  info(`Loaded ${remoteTests.length} custom test(s) from dashboard`);
1096
2000
  config.customTests = [...config.customTests ?? [], ...remoteTests];
2001
+ const seen = /* @__PURE__ */ new Set();
2002
+ const dupNames = [
2003
+ ...new Set(
2004
+ config.customTests.map((t) => t.name).filter((n) => seen.has(n) ? true : (seen.add(n), false))
2005
+ )
2006
+ ];
2007
+ if (dupNames.length > 0) {
2008
+ console.error(
2009
+ `Duplicate custom test name(s) after merging local + dashboard tests: ${dupNames.join(
2010
+ ", "
2011
+ )}. Rename so every custom test name is unique.`
2012
+ );
2013
+ setExitCode(2);
2014
+ return;
2015
+ }
1097
2016
  }
1098
2017
  } catch (err) {
1099
2018
  const msg = err instanceof Error ? err.message : "Unknown error";
@@ -1111,6 +2030,7 @@ async function scanCommand(opts) {
1111
2030
  const includeCrescendo = customOnly ? false : config.includeCrescendo ?? config.preset === "full";
1112
2031
  let attacks = [];
1113
2032
  let multiTurnAttacks = [];
2033
+ let attackPackVersion;
1114
2034
  if (customOnly) {
1115
2035
  if (!config.customTests || config.customTests.length === 0) {
1116
2036
  console.error(
@@ -1131,38 +2051,114 @@ async function scanCommand(opts) {
1131
2051
  });
1132
2052
  attacks = fetched.attacks;
1133
2053
  multiTurnAttacks = fetched.multiTurnAttacks;
2054
+ attackPackVersion = fetched.attackPackVersion;
1134
2055
  const multiTurnNote = fetched.multiTurnAttacks.length > 0 ? ` + ${fetched.multiTurnAttacks.length} multi-turn` : "";
1135
2056
  info(
1136
2057
  `Loaded ${fetched.attacks.length} attacks${multiTurnNote} from ${fetched.source} (catalog ${fetched.catalogVersion})`
1137
2058
  );
1138
2059
  }
2060
+ const target = buildTargetConfig(config);
2061
+ const catalogHash = computeCatalogHash([
2062
+ ...(attacks ?? []).map((a) => a.id),
2063
+ ...(multiTurnAttacks ?? []).map((a) => a.id),
2064
+ ...(config.customTests ?? []).map((t) => `custom_${t.name}`)
2065
+ ]);
2066
+ const scanKey = computeScanKey({
2067
+ target: target.url,
2068
+ preset: presetForScan,
2069
+ systemPromptHash: systemPrompt,
2070
+ catalogHash
2071
+ });
2072
+ const checkpointDir = opts.checkpointDir ?? resolve3(process.cwd(), ".shield-llm", "checkpoints");
2073
+ const checkpointStore = new FileCheckpointStore(
2074
+ resolve3(checkpointDir, `scan-${scanKey}.jsonl`)
2075
+ );
2076
+ if (opts.resume === false) {
2077
+ await checkpointStore.finalize();
2078
+ }
1139
2079
  const scanOptions = {
1140
- target: buildTargetConfig(config),
2080
+ target,
1141
2081
  systemPrompt,
1142
2082
  preset: presetForScan,
1143
2083
  attacks,
1144
2084
  multiTurnAttacks,
1145
2085
  includeCrescendo,
1146
2086
  customTests: config.customTests,
1147
- concurrency: config.concurrency,
2087
+ // Adaptive concurrency: 4-way by default (AIMD backs off on 429s),
2088
+ // overridable via config.concurrency. Set 1 for strictly sequential.
2089
+ concurrency: config.concurrency ?? 4,
1148
2090
  delayMs: config.delayMs,
1149
2091
  attackTimeoutMs: config.attackTimeoutMs,
1150
2092
  maxConsecutiveFailures: config.maxConsecutiveFailures,
2093
+ maxRateLimitRetries: config.maxRateLimitRetries,
2094
+ rateLimitBackoffMs: config.rateLimitBackoffMs,
2095
+ rateLimitMaxBackoffMs: config.rateLimitMaxBackoffMs,
2096
+ checkpoint: checkpointStore,
1151
2097
  evaluator
1152
2098
  };
1153
2099
  const onEvent = opts.progress !== false ? handleEvent : void 0;
1154
2100
  const scanner = new Scanner(scanOptions, onEvent);
1155
2101
  const report = await scanner.run();
2102
+ const attempted = report.attacks.length;
2103
+ const evaluated = report.attacks.filter(
2104
+ (a) => !a.error && !a.rateLimited
2105
+ ).length;
2106
+ if (reservedScanId && attempted > 0 && evaluated === 0) {
2107
+ const errored = report.attacks.filter(
2108
+ (a) => a.error && !a.rateLimited
2109
+ ).length;
2110
+ const rateLimited = report.attacks.filter((a) => a.rateLimited).length;
2111
+ const reason = `Target unreachable: 0/${attempted} attacks evaluated (${errored} errored, ${rateLimited} rate-limited)`;
2112
+ await reportScanFailure(credentials, reservedScanId, reason);
2113
+ scanFinalized = true;
2114
+ console.error(`Scan failed: ${reason}`);
2115
+ setExitCode(3);
2116
+ return;
2117
+ }
2118
+ let uploadedScanId = null;
1156
2119
  try {
1157
2120
  if (!reservedScanId) {
1158
2121
  throw new Error(
1159
2122
  "Missing scan reservation id (server returned no scanId)."
1160
2123
  );
1161
2124
  }
1162
- await uploadReportToBackend(report, credentials, reservedScanId);
2125
+ const authoritative = await uploadReportToBackend(
2126
+ report,
2127
+ credentials,
2128
+ reservedScanId,
2129
+ attackPackVersion
2130
+ );
2131
+ uploadedScanId = reservedScanId;
2132
+ scanFinalized = true;
2133
+ await checkpointStore.finalize();
2134
+ report.score = authoritative.score;
2135
+ report.grade = authoritative.grade;
2136
+ if (authoritative.droppedAttackIds > 0) {
2137
+ info(
2138
+ `Note: ${authoritative.droppedAttackIds} result(s) weren't in the backend catalogue (e.g. local custom tests) and were excluded from the saved score.`
2139
+ );
2140
+ }
1163
2141
  } catch (err) {
1164
2142
  const msg = err instanceof Error ? err.message : String(err);
1165
2143
  console.warn(`Warning: Could not save scan to dashboard: ${msg}`);
2144
+ console.warn(
2145
+ "Showing the locally-computed score \u2014 it may differ from the dashboard."
2146
+ );
2147
+ }
2148
+ const benchmarkEligible = presetForScan === "full" && !customOnly && (config.customTests?.length ?? 0) === 0 && attackPackVersion !== void 0;
2149
+ if (opts.consent || benchmarkEligible) {
2150
+ info(
2151
+ benchmarkEligible ? `Benchmark: scan is eligible (full preset, attack pack v${attackPackVersion})` : `Benchmark: scan is NOT eligible (requires the full preset with no custom tests)`
2152
+ );
2153
+ }
2154
+ if (opts.consent && uploadedScanId) {
2155
+ if (opts.ci) {
2156
+ info(
2157
+ "Benchmark: --consent is interactive and is skipped in --ci mode. Use `shield-llm benchmark submit --yes` instead."
2158
+ );
2159
+ } else {
2160
+ await interactiveSubmitFlow(credentials, uploadedScanId, info);
2161
+ }
1166
2162
  }
1167
2163
  let thresholdResult = evaluateThresholds(report, config.thresholds);
1168
2164
  if (!opts.ci) {
@@ -1196,7 +2192,7 @@ async function scanCommand(opts) {
1196
2192
  if (format === "pdf") {
1197
2193
  const pdfPath = outputFile ?? `shield-report-${report.id.slice(0, 8)}.pdf`;
1198
2194
  const pdfBuffer = await generatePdf(report);
1199
- writeFileSync4(resolve3(pdfPath), pdfBuffer);
2195
+ writeFileSync5(resolve3(pdfPath), pdfBuffer);
1200
2196
  info(`PDF report written to ${pdfPath}`);
1201
2197
  } else {
1202
2198
  let content;
@@ -1217,7 +2213,7 @@ async function scanCommand(opts) {
1217
2213
  break;
1218
2214
  }
1219
2215
  if (outputFile) {
1220
- writeFileSync4(resolve3(outputFile), content, "utf-8");
2216
+ writeFileSync5(resolve3(outputFile), content, "utf-8");
1221
2217
  info(`Report written to ${outputFile}`);
1222
2218
  } else {
1223
2219
  console.log(content);
@@ -1232,7 +2228,7 @@ async function scanCommand(opts) {
1232
2228
  thresholds: thresholdResult,
1233
2229
  compliance: complianceResult
1234
2230
  });
1235
- writeFileSync4(jsonPath, jsonContent, "utf-8");
2231
+ writeFileSync5(jsonPath, jsonContent, "utf-8");
1236
2232
  info(
1237
2233
  `JSON copy written to ${jsonPath}${opts.includeFullPayloads ? " (full payloads)" : " (sanitized)"}`
1238
2234
  );
@@ -1240,6 +2236,10 @@ async function scanCommand(opts) {
1240
2236
  setExitCode(thresholdResult.passed ? 0 : 1);
1241
2237
  return;
1242
2238
  } catch (error) {
2239
+ if (failTarget && reservedScanId && !scanFinalized) {
2240
+ const reason = error instanceof ConfigError ? `Configuration error: ${error.message}` : `Scan run failed: ${error instanceof Error ? error.message : "Unknown error"}`;
2241
+ await reportScanFailure(failTarget, reservedScanId, reason);
2242
+ }
1243
2243
  if (error instanceof ConfigError) {
1244
2244
  console.error(`Configuration error: ${error.message}`);
1245
2245
  setExitCode(2);
@@ -1335,8 +2335,7 @@ async function testsCommand(opts) {
1335
2335
  " shield-llm init Add tests to shield.config.json"
1336
2336
  );
1337
2337
  console.log(
1338
- ` ${DEFAULT_API_URL}/tests Create tests on the dashboard
1339
- `
2338
+ " Tests page on your dashboard Create tests in the web app\n"
1340
2339
  );
1341
2340
  return;
1342
2341
  }
@@ -1385,7 +2384,7 @@ function validateCommand(opts) {
1385
2384
  return;
1386
2385
  } catch (error) {
1387
2386
  if (error instanceof ConfigError) {
1388
- console.error(`Invalid configuration: ${error.message}`);
2387
+ console.error(error.message);
1389
2388
  setExitCode(2);
1390
2389
  return;
1391
2390
  }
@@ -1407,10 +2406,16 @@ ${label}:`);
1407
2406
  );
1408
2407
  process.exit(3);
1409
2408
  }
2409
+ function exitWithConfigError(err) {
2410
+ console.error(`Configuration error: ${err.message}`);
2411
+ process.exit(2);
2412
+ }
1410
2413
  process.on("unhandledRejection", (reason) => {
2414
+ if (reason instanceof ConfigError) exitWithConfigError(reason);
1411
2415
  reportFatal("Unhandled promise rejection", reason);
1412
2416
  });
1413
2417
  process.on("uncaughtException", (err) => {
2418
+ if (err instanceof ConfigError) exitWithConfigError(err);
1414
2419
  reportFatal("Uncaught exception", err);
1415
2420
  });
1416
2421
  var program = new Command();
@@ -1422,7 +2427,10 @@ program.command("scan").description("Run a security scan against a target chatbo
1422
2427
  ).option(
1423
2428
  "--request-body <json>",
1424
2429
  "JSON request body template (use {{prompt}} placeholder)"
1425
- ).option("--preset <name>", "Scan preset (dev, quick, owasp, standard, full)").option("--system-prompt <text>", "System prompt for target chatbot").option("--system-prompt-file <path>", "Path to system prompt file").option("--crescendo", "Include crescendo (multi-turn) attacks").option("--min-score <n>", "Minimum score threshold", parseFloat).option("--fail-on-critical", "Fail if any CRITICAL vulnerability found").option("-o, --output <format>", "Output format (json, markdown, sarif, pdf)").option("--output-file <path>", "Write report to file").option(
2430
+ ).option(
2431
+ "--preset <name>",
2432
+ "Scan preset (dev, quick, owasp, frontier, standard, full)"
2433
+ ).option("--system-prompt <text>", "System prompt for target chatbot").option("--system-prompt-file <path>", "Path to system prompt file").option("--crescendo", "Include crescendo (multi-turn) attacks").option("--min-score <n>", "Minimum score threshold", parseFloat).option("--fail-on-critical", "Fail if any CRITICAL vulnerability found").option("-o, --output <format>", "Output format (json, markdown, sarif, pdf)").option("--output-file <path>", "Write report to file").option(
1426
2434
  "--write-json <path>",
1427
2435
  "Always write a parseable JSON copy here, regardless of --output (useful for CI to extract score/grade alongside SARIF)"
1428
2436
  ).option(
@@ -1444,7 +2452,46 @@ program.command("scan").description("Run a security scan against a target chatbo
1444
2452
  ).option(
1445
2453
  "--api-url <url>",
1446
2454
  "Backend API URL (overrides SHIELD_API_URL env var and stored credentials)"
2455
+ ).option(
2456
+ "--consent",
2457
+ "After the scan, offer to contribute an anonymous aggregate to a benchmark cohort (interactive preview + explicit confirmation)"
2458
+ ).option(
2459
+ "--no-resume",
2460
+ "Ignore any saved checkpoint and start fresh (the scan still checkpoints so it can resume if THIS run is interrupted)"
2461
+ ).option(
2462
+ "--checkpoint-dir <path>",
2463
+ "Directory for resumable scan checkpoints (default: .shield-llm/checkpoints)"
1447
2464
  ).action(scanCommand);
2465
+ var benchmark = program.command("benchmark").description("Cohort benchmarking \u2014 consent, submission, relative position");
2466
+ benchmark.command("cohorts").description("List your cohorts, or create one with --create").option(
2467
+ "--create <name>",
2468
+ "Create a cohort pinned to the current attack pack version"
2469
+ ).option("--k-min <n>", "K-anonymity threshold for --create (default 5)").option("--api-url <url>", "Backend API URL override").action(cohortsCommand);
2470
+ var consent = benchmark.command("consent").description("Manage an organization's contribution consent");
2471
+ consent.command("show").description(
2472
+ "Preview the EXACT payload a submission would send (nothing is sent)"
2473
+ ).requiredOption("--cohort <id>", "Cohort id").requiredOption("--target <id>", "Organization (target) id in the cohort").requiredOption("--scan <id>", "Scan id to build the preview from").option("--api-url <url>", "Backend API URL override").action(consentShowCommand);
2474
+ consent.command("grant").description("Record an organization's consent (append-only ledger)").requiredOption("--cohort <id>", "Cohort id").requiredOption("--target <id>", "Organization (target) id in the cohort").requiredOption(
2475
+ "--scope <scopes>",
2476
+ "Comma-separated: global_score,category_scores,segment_metadata"
2477
+ ).requiredOption(
2478
+ "--by <identity>",
2479
+ "Identity/role with authority granting the consent"
2480
+ ).option("--api-url <url>", "Backend API URL override").action(consentGrantCommand);
2481
+ consent.command("revoke").description("Revoke the organization's active consent").requiredOption("--cohort <id>", "Cohort id").requiredOption("--target <id>", "Organization (target) id in the cohort").option("--api-url <url>", "Backend API URL override").action(consentRevokeCommand);
2482
+ benchmark.command("submit").description(
2483
+ "Contribute a scan's anonymous aggregate (preview + confirmation)"
2484
+ ).requiredOption("--cohort <id>", "Cohort id").requiredOption("--target <id>", "Organization (target) id in the cohort").requiredOption("--scan <id>", "Scan id to contribute").option("--yes", "Skip the interactive confirmation (CI use)").option("--api-url <url>", "Backend API URL override").action(submitCommand);
2485
+ benchmark.command("position").description(
2486
+ "Relative position of a score within the cohort (read-only; --offline for air-gapped)"
2487
+ ).option("--cohort <id>", "Cohort id (online mode)").option("--scan <id>", "Scan id (with --target)").option("--target <id>", "Organization (target) id (with --scan)").option("--score <n>", "Explicit score 0-100 (with --segment-key)").option("--segment-key <key>", "Canonical segment key (with --score)").option("--offline", "Compute locally from a signed snapshot \u2014 no network").option("--snapshot <file>", "Snapshot file (offline mode)").option("--sig <file>", "Signature file (default: <snapshot>.sig)").option(
2488
+ "--public-key <pem>",
2489
+ "Issuer public key PEM, pinned out-of-band (offline mode, REQUIRED)"
2490
+ ).option("--api-url <url>", "Backend API URL override").action(positionCommand);
2491
+ var snapshot = benchmark.command("snapshot").description("Signed distribution snapshots for air-gapped positioning");
2492
+ snapshot.command("export").description(
2493
+ "Export the cohort's signed snapshot (segments under k_min are excluded)"
2494
+ ).requiredOption("--cohort <id>", "Cohort id").option("--out <file>", "Output path (default ./snapshot.json)").option("--api-url <url>", "Backend API URL override").action(snapshotExportCommand);
1448
2495
  program.command("init").description("Generate a shield.config.json interactively").action(initCommand);
1449
2496
  program.command("attacks").description("List all available attacks (fetched from your backend)").option("--severity <level>", "Filter by severity").option("--api-url <url>", "Backend API URL override").action(attacksCommand);
1450
2497
  program.command("presets").description("List available scan presets (fetched from your backend)").option("--api-url <url>", "Backend API URL override").action(presetsCommand);
@@ -1460,9 +2507,26 @@ program.command("test-connection").description(
1460
2507
  "Benign message to send (default: a greeting)"
1461
2508
  ).action(testConnectionCommand);
1462
2509
  program.command("report <scanId>").description("Fetch a past scan report from your dashboard").option("-o, --output <format>", "Output format (json, markdown)", "json").option("--output-file <path>", "Write report to file").option("--api-url <url>", "Backend API URL override").action(reportCommand);
2510
+ program.command("retest <scanId>").description(
2511
+ "Replay the detected findings of a past scan against the target and record which are fixed (verified) vs still vulnerable"
2512
+ ).option("-c, --config <path>", "Path to shield.config.json").option("-e, --endpoint <url>", "Target chatbot HTTP endpoint URL").option("--auth <type>", "Auth type: bearer, api-key").option("--token <value>", "Bearer token or API key value").option("--auth-header <name>", "Custom auth header name (for api-key auth)").option(
2513
+ "--response-field <path>",
2514
+ "Dot-notation path to response text in JSON (default: response)"
2515
+ ).option(
2516
+ "--request-body <json>",
2517
+ "JSON request body template (use {{prompt}} placeholder)"
2518
+ ).option(
2519
+ "--finding <attackId>",
2520
+ "Retest only this finding (attack id or name). Repeatable.",
2521
+ (value, previous) => [...previous, value],
2522
+ []
2523
+ ).option("--no-progress", "Disable progress spinner").option(
2524
+ "--ci",
2525
+ "CI mode: JSON to stdout, no spinner. Exit 0=all fixed, 1=still vulnerable, 2=config/auth, 3=infra"
2526
+ ).option("--api-url <url>", "Backend API URL override").action(retestCommand);
1463
2527
  program.command("login").description("Authenticate with your Shield LLM API key").requiredOption("--key <api-key>", "Your API key (sk_shield_...)").option(
1464
2528
  "--api-url <url>",
1465
- "Backend API URL (defaults to SHIELD_API_URL env var or https://shield-llm.com)"
2529
+ "Your Shield LLM backend URL (or set the SHIELD_API_URL env var)"
1466
2530
  ).action(loginCommand);
1467
2531
  program.command("logout").description("Remove stored API key credentials").action(logoutCommand);
1468
2532
  try {
@@ -1472,5 +2536,8 @@ try {
1472
2536
  const code = err.code === "commander.helpDisplayed" || err.code === "commander.version" ? 0 : 2;
1473
2537
  process.exit(code);
1474
2538
  }
2539
+ if (err instanceof ConfigError) {
2540
+ exitWithConfigError(err);
2541
+ }
1475
2542
  reportFatal("Error", err);
1476
2543
  }