shield-llm 0.12.2 → 0.13.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
@@ -3,7 +3,6 @@ import {
3
3
  ATTACK_PACK_VERSION,
4
4
  BENIGN_CORE_V1,
5
5
  BENIGN_SUITE_ID,
6
- CONSENT_SCOPES,
7
6
  CROSSWALK_GAPS,
8
7
  ConfigError,
9
8
  ConfigSchema,
@@ -23,10 +22,13 @@ import {
23
22
  RateLimitError,
24
23
  RegexOnlyEvaluator,
25
24
  Scanner,
25
+ VULN_TO_AGENTIC,
26
26
  analyzeJudgeHealth,
27
+ articleNumberEn,
28
+ aspectArticleLabel,
27
29
  attacksForContract,
28
30
  baseAttackId,
29
- buildAuthFromFlags,
31
+ buildEndpointOverride,
30
32
  buildTargetConfig,
31
33
  c,
32
34
  calculateComplianceScore,
@@ -52,7 +54,6 @@ import {
52
54
  formatSarif,
53
55
  formatShareAboveLimit,
54
56
  frameworkVersion,
55
- generatePdf,
56
57
  getCrosswalk,
57
58
  getMutator,
58
59
  getObligationProfile,
@@ -66,12 +67,9 @@ import {
66
67
  missingForContract,
67
68
  normalizeTargetUrl,
68
69
  parseMaxUnjudgedPercent,
69
- parseSegmentKey,
70
- parseSnapshot,
71
70
  recordVerification,
72
71
  replaceLoneSurrogates,
73
72
  resolveClaim,
74
- resolveOfflinePosition,
75
73
  retestDedupKey,
76
74
  serializeAttack,
77
75
  sha256Hex,
@@ -79,7 +77,7 @@ import {
79
77
  summarizeObfuscationVariants,
80
78
  version,
81
79
  withoutScoredApartVariants
82
- } from "./chunk-4A2UTKN5.js";
80
+ } from "./chunk-S3XEHIPB.js";
83
81
 
84
82
  // src/load-env.ts
85
83
  try {
@@ -158,6 +156,58 @@ function getCredentialsPath() {
158
156
  return getCredentialsFile();
159
157
  }
160
158
 
159
+ // src/lib/exit.ts
160
+ function setExitCode(code) {
161
+ process.exitCode = code;
162
+ }
163
+
164
+ // src/lib/account-suspended.ts
165
+ var ACCOUNT_SUSPENDED_CODE = "account_suspended";
166
+ function instanceName(apiUrl) {
167
+ try {
168
+ const host = new URL(apiUrl).host;
169
+ if (host) return host;
170
+ } catch {
171
+ }
172
+ return "this Shield instance";
173
+ }
174
+ function accountSuspendedMessage(apiUrl) {
175
+ return `Your account on ${instanceName(apiUrl)} is suspended: ask your Shield administrator.`;
176
+ }
177
+ var AccountSuspendedError = class extends Error {
178
+ constructor(apiUrl) {
179
+ super(accountSuspendedMessage(apiUrl));
180
+ this.apiUrl = apiUrl;
181
+ this.name = "AccountSuspendedError";
182
+ }
183
+ };
184
+ function isSuspendedBody(body) {
185
+ return typeof body === "object" && body !== null && body.code === ACCOUNT_SUSPENDED_CODE;
186
+ }
187
+ async function isAccountSuspended(res) {
188
+ if (res.status !== 403) return false;
189
+ try {
190
+ return isSuspendedBody(await res.clone().json());
191
+ } catch {
192
+ return false;
193
+ }
194
+ }
195
+ async function throwIfSuspended(res, apiUrl) {
196
+ if (await isAccountSuspended(res)) throw new AccountSuspendedError(apiUrl);
197
+ }
198
+ function reportAccountSuspended(err) {
199
+ if (!(err instanceof AccountSuspendedError)) return false;
200
+ console.error(err.message);
201
+ setExitCode(2);
202
+ return true;
203
+ }
204
+ async function reportIfSuspended(res, apiUrl) {
205
+ if (!await isAccountSuspended(res)) return false;
206
+ console.error(accountSuspendedMessage(apiUrl));
207
+ setExitCode(2);
208
+ return true;
209
+ }
210
+
161
211
  // src/attacks-loader.ts
162
212
  async function fetchAttacks(args) {
163
213
  const params = new URLSearchParams({ preset: args.preset });
@@ -174,6 +224,7 @@ async function fetchAttacks(args) {
174
224
  `Could not reach the Shield LLM backend at ${args.apiUrl} (${reason}). The CLI needs a backend connection to fetch the attack catalogue.`
175
225
  );
176
226
  }
227
+ await throwIfSuspended(res, args.apiUrl);
177
228
  if (res.status === 401) {
178
229
  throw new Error(
179
230
  "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
@@ -206,11 +257,6 @@ async function fetchAttacks(args) {
206
257
  }
207
258
  }
208
259
 
209
- // src/lib/exit.ts
210
- function setExitCode(code) {
211
- process.exitCode = code;
212
- }
213
-
214
260
  // src/commands/attacks.ts
215
261
  async function attacksCommand(opts) {
216
262
  const stored = loadCredentials();
@@ -229,6 +275,7 @@ async function attacksCommand(opts) {
229
275
  includeMultiTurn: true
230
276
  });
231
277
  } catch (err) {
278
+ if (reportAccountSuspended(err)) return;
232
279
  const msg = err instanceof Error ? err.message : "Unknown error";
233
280
  console.error(`Failed to fetch attacks: ${msg}`);
234
281
  setExitCode(3);
@@ -282,8 +329,9 @@ Attack catalogue \u2014 ${total} attack(s)${wanted ? ` (severity: ${wanted})` :
282
329
  );
283
330
  }
284
331
 
285
- // src/commands/benchmark.ts
286
- import { writeFileSync as writeFileSync2 } from "fs";
332
+ // src/commands/init.ts
333
+ import { existsSync as existsSync2, writeFileSync as writeFileSync2 } from "fs";
334
+ import { resolve } from "path";
287
335
 
288
336
  // src/lib/prompts.ts
289
337
  import * as readline from "readline/promises";
@@ -356,475 +404,27 @@ async function select(opts) {
356
404
  });
357
405
  }
358
406
 
359
- // src/benchmark/api.ts
360
- var BenchmarkApiError = class extends Error {
361
- constructor(status, body) {
362
- const detail = typeof body.message === "string" ? body.message : typeof body.error === "string" ? body.error : `HTTP ${status}`;
363
- super(detail);
364
- this.name = "BenchmarkApiError";
365
- this.status = status;
366
- this.body = body;
367
- }
368
- };
369
- async function request(creds, method, path, body) {
370
- let res;
371
- try {
372
- res = await fetch(`${creds.apiUrl}${path}`, {
373
- method,
374
- headers: {
375
- Authorization: `Bearer ${creds.apiKey}`,
376
- // The /api/benchmark/* routes are dual-auth (browser session OR API
377
- // key), so — unlike the API-key-only /api/cli/* routes — they are NOT
378
- // exempt from the middleware's CSRF same-origin check. A non-browser
379
- // client sends no Origin and is rejected with 403 "Invalid origin".
380
- // Send Origin = the configured backend so the same-origin check passes.
381
- // API-key auth carries no ambient-cookie CSRF risk, so this is safe.
382
- Origin: new URL(creds.apiUrl).origin,
383
- ...body !== void 0 && { "Content-Type": "application/json" }
384
- },
385
- ...body !== void 0 && { body: JSON.stringify(body) }
386
- });
387
- } catch (err) {
388
- const reason = err instanceof Error ? err.message : "Unknown error";
389
- throw new Error(
390
- `Could not reach the Shield LLM backend at ${creds.apiUrl} (${reason}).`
391
- );
392
- }
393
- const json = await res.json().catch(() => ({}));
394
- if (!res.ok) {
395
- if (res.status === 401) {
396
- throw new BenchmarkApiError(401, {
397
- error: "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
398
- });
399
- }
400
- if (res.status === 404 && json.error === "Not found") {
401
- throw new BenchmarkApiError(404, {
402
- error: "Benchmark module is not enabled on this backend (NEXT_PUBLIC_MODULE_BENCHMARK)."
403
- });
404
- }
405
- throw new BenchmarkApiError(res.status, json);
406
- }
407
- return json;
408
- }
409
- function listCohorts(creds) {
410
- return request(
411
- creds,
412
- "GET",
413
- "/api/benchmark/cohorts"
414
- );
415
- }
416
- function createCohort(creds, args) {
417
- return request(
418
- creds,
419
- "POST",
420
- "/api/benchmark/cohorts",
421
- args
422
- );
423
- }
424
- function getCohort(creds, cohortId) {
425
- return request(
426
- creds,
427
- "GET",
428
- `/api/benchmark/cohorts/${encodeURIComponent(cohortId)}`
429
- );
430
- }
431
- function grantConsent(creds, args) {
432
- return request(
433
- creds,
434
- "POST",
435
- `/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/targets/${encodeURIComponent(args.targetId)}/consent`,
436
- { scopes: args.scopes, grantedBy: args.grantedBy }
437
- );
438
- }
439
- function revokeConsent(creds, args) {
440
- return request(
441
- creds,
442
- "DELETE",
443
- `/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/targets/${encodeURIComponent(args.targetId)}/consent`
444
- );
445
- }
446
- function previewSubmission(creds, args) {
447
- return request(
448
- creds,
449
- "POST",
450
- `/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/submissions/preview`,
451
- { scanId: args.scanId, targetId: args.targetId }
452
- );
453
- }
454
- function submitAggregate(creds, args) {
455
- return request(
456
- creds,
457
- "POST",
458
- `/api/benchmark/cohorts/${encodeURIComponent(args.cohortId)}/submissions`,
459
- { scanId: args.scanId, targetId: args.targetId }
460
- );
461
- }
462
- function exportSnapshot(creds, cohortId) {
463
- return request(
464
- creds,
465
- "POST",
466
- `/api/benchmark/cohorts/${encodeURIComponent(cohortId)}/snapshot`
467
- );
468
- }
469
- function getPosition(creds, cohortId, query) {
470
- const params = new URLSearchParams();
471
- if ("scanId" in query) {
472
- params.set("scanId", query.scanId);
473
- params.set("targetId", query.targetId);
474
- } else {
475
- params.set("score", String(query.score));
476
- params.set("segmentKey", query.segmentKey);
477
- }
478
- return request(
479
- creds,
480
- "GET",
481
- `/api/benchmark/cohorts/${encodeURIComponent(cohortId)}/position?${params.toString()}`
482
- );
483
- }
484
-
485
- // src/benchmark/format.ts
486
- var LABELS = {
487
- above_p75: "Reinforced posture (above the 3rd quartile)",
488
- p25_p75: "Within cohort average",
489
- below_p25: "Above-median exposure"
490
- };
491
- function ordinal(n) {
492
- const rounded = Math.round(n);
493
- const mod100 = rounded % 100;
494
- if (mod100 >= 11 && mod100 <= 13) return `${rounded}th`;
495
- switch (rounded % 10) {
496
- case 1:
497
- return `${rounded}st`;
498
- case 2:
499
- return `${rounded}nd`;
500
- case 3:
501
- return `${rounded}rd`;
502
- default:
503
- return `${rounded}th`;
504
- }
505
- }
506
- function formatPosition(position, attackPackVersion) {
507
- if (position.status === "insufficient_cohort") {
508
- return `Benchmark building (N=${position.n}/${position.kMin}) \u2014 position unavailable below the k-anonymity threshold.`;
509
- }
510
- const percentile = position.clamped === "low" ? `\u2264 ${ordinal(position.percentile)} percentile` : position.clamped === "high" ? `\u2265 ${ordinal(position.percentile)} percentile` : `${ordinal(position.percentile)} percentile`;
511
- const scope = position.generalizationLevel === 0 ? "exact segment" : position.segmentKey === "s1|*|*|*|*|*" ? "whole cohort" : `generalized segment ${position.segmentKey}`;
512
- return [
513
- `${percentile} \u2014 ${LABELS[position.labelKey] ?? position.labelKey}`,
514
- `vs ${position.n} comparable organizations \xB7 ${scope} \xB7 attack pack v${attackPackVersion}`
515
- ].join("\n");
516
- }
517
-
518
- // src/benchmark/snapshot.ts
519
- import { readFileSync as readFileSync2 } from "fs";
520
- import { createPublicKey, verify } from "crypto";
521
- function verifyAndLoadSnapshot(args) {
522
- const bytes = readFileSync2(args.snapshotPath);
523
- const signature = Buffer.from(
524
- readFileSync2(args.signaturePath, "utf8").trim(),
525
- "base64"
526
- );
527
- let publicKey;
528
- try {
529
- publicKey = createPublicKey(readFileSync2(args.publicKeyPath, "utf8"));
530
- } catch (err) {
531
- throw new Error(
532
- `Could not load the public key at ${args.publicKeyPath}: ${err instanceof Error ? err.message : String(err)}`
533
- );
534
- }
535
- if (publicKey.asymmetricKeyType !== "ed25519") {
536
- throw new Error(
537
- `Public key must be Ed25519 (got ${publicKey.asymmetricKeyType ?? "unknown"})`
538
- );
539
- }
540
- const valid = verify(null, bytes, publicKey, signature);
541
- if (!valid) {
542
- throw new Error(
543
- "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."
544
- );
545
- }
546
- return parseSnapshot(JSON.parse(bytes.toString("utf8")));
547
- }
548
-
549
- // src/commands/benchmark.ts
550
- function requireCreds(opts) {
551
- const stored = loadCredentials();
552
- if (!stored) {
553
- console.error(
554
- "Not authenticated. Run `shield-llm login --key <api-key>` first."
555
- );
556
- setExitCode(2);
557
- return null;
558
- }
559
- return {
560
- apiUrl: resolveApiUrl(stored.apiUrl, opts.apiUrl),
561
- apiKey: stored.apiKey
562
- };
563
- }
564
- function reportError(err) {
565
- if (err instanceof BenchmarkApiError) {
566
- console.error(`Error: ${err.message}`);
567
- if (Array.isArray(err.body.reasons)) {
568
- console.error(`Reasons: ${err.body.reasons.join(", ")}`);
569
- }
570
- if (Array.isArray(err.body.violations)) {
571
- console.error(
572
- `Violations: ${err.body.violations.join("; ")}`
573
- );
574
- }
575
- setExitCode(2);
576
- } else {
577
- console.error(err instanceof Error ? err.message : String(err));
578
- setExitCode(3);
579
- }
580
- }
581
- function parseScopes(raw) {
582
- const scopes = [];
583
- for (const part of raw.split(",").map((s) => s.trim()).filter(Boolean)) {
584
- const full = part.startsWith("contribute:") ? part : `contribute:${part}`;
585
- if (!CONSENT_SCOPES.includes(full)) {
586
- throw new Error(
587
- `Unknown consent scope "${part}". Valid scopes: ` + CONSENT_SCOPES.map((s) => s.replace("contribute:", "")).join(", ")
588
- );
589
- }
590
- scopes.push(full);
591
- }
592
- return scopes;
593
- }
594
- async function cohortsCommand(opts) {
595
- const creds = requireCreds(opts);
596
- if (!creds) return;
597
- try {
598
- if (opts.create) {
599
- const created = await createCohort(creds, {
600
- displayName: String(opts.create),
601
- ...opts.kMin !== void 0 && { kMin: Number(opts.kMin) }
602
- });
603
- console.log(
604
- `Created cohort ${created.id} (attack pack v${created.activePackVersion}, k_min=${created.kMin})`
605
- );
606
- return;
607
- }
608
- const { cohorts } = await listCohorts(creds);
609
- if (cohorts.length === 0) {
610
- console.log(
611
- "No cohorts yet. Create one with `shield-llm benchmark cohorts --create <name>`."
612
- );
613
- return;
614
- }
615
- for (const c2 of cohorts) {
616
- console.log(
617
- `${c2.id} ${c2.displayName} pack v${c2.activePackVersion} k_min=${c2.kMin} targets=${c2.targetCount} submissions=${c2.submissionCount}`
618
- );
619
- }
620
- } catch (err) {
621
- reportError(err);
622
- }
623
- }
624
- async function consentShowCommand(opts) {
625
- const creds = requireCreds(opts);
626
- if (!creds) return;
627
- try {
628
- const preview = await previewSubmission(creds, {
629
- cohortId: opts.cohort,
630
- scanId: opts.scan,
631
- targetId: opts.target
632
- });
633
- console.log("Exact payload that WOULD be submitted (nothing sent):");
634
- console.log(JSON.stringify(preview.payload, null, 2));
635
- if (preview.wouldReplace) {
636
- console.log(
637
- "Note: this would REPLACE the previous contribution of this organization for this attack pack version."
638
- );
639
- }
640
- } catch (err) {
641
- reportError(err);
642
- }
643
- }
644
- async function consentGrantCommand(opts) {
645
- const creds = requireCreds(opts);
646
- if (!creds) return;
647
- try {
648
- const scopes = parseScopes(String(opts.scope ?? ""));
649
- const granted = await grantConsent(creds, {
650
- cohortId: opts.cohort,
651
- targetId: opts.target,
652
- scopes,
653
- grantedBy: String(opts.by)
654
- });
655
- console.log(
656
- `Consent recorded (${granted.id}) \u2014 scopes: ${granted.scopes.join(", ")}`
657
- );
658
- } catch (err) {
659
- reportError(err);
660
- }
661
- }
662
- async function consentRevokeCommand(opts) {
663
- const creds = requireCreds(opts);
664
- if (!creds) return;
665
- try {
666
- const result = await revokeConsent(creds, {
667
- cohortId: opts.cohort,
668
- targetId: opts.target
669
- });
670
- console.log(
671
- result.revoked ? "Consent revoked. Future contributions are blocked until a new grant." : "No active consent to revoke."
672
- );
673
- } catch (err) {
674
- reportError(err);
675
- }
676
- }
677
- async function confirmAndSubmit(creds, args, opts = {}) {
678
- const log = opts.log ?? console.log;
679
- const preview = await previewSubmission(creds, args);
680
- log("The following anonymous aggregate will be submitted to the cohort:");
681
- log(JSON.stringify(preview.payload, null, 2));
682
- if (preview.wouldReplace) {
683
- log("This will REPLACE the organization's previous contribution.");
684
- }
685
- const approved = opts.yes === true ? true : await confirm({ message: "Submit this aggregate?", default: false });
686
- if (!approved) {
687
- log("Aborted \u2014 nothing was submitted. Your scan stays 100% local.");
688
- return false;
689
- }
690
- const result = await submitAggregate(creds, args);
691
- log(
692
- result.replaced ? "Aggregate submitted (replaced the previous contribution)." : "Aggregate submitted."
693
- );
694
- return true;
695
- }
696
- async function submitCommand(opts) {
697
- const creds = requireCreds(opts);
698
- if (!creds) return;
699
- try {
700
- await confirmAndSubmit(
701
- creds,
702
- { cohortId: opts.cohort, scanId: opts.scan, targetId: opts.target },
703
- { yes: Boolean(opts.yes) }
704
- );
705
- } catch (err) {
706
- reportError(err);
707
- }
708
- }
709
- async function positionCommand(opts) {
710
- if (opts.offline || opts.snapshot) {
711
- return offlinePositionCommand(opts);
712
- }
713
- const creds = requireCreds(opts);
714
- if (!creds) return;
715
- try {
716
- 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;
717
- if (!query) {
718
- console.error(
719
- "Provide either --scan <id> --target <id>, or --score <n> --segment-key <key>."
720
- );
721
- setExitCode(2);
722
- return;
723
- }
724
- const response = await getPosition(creds, opts.cohort, query);
725
- if (response.scanEligibility && !response.scanEligibility.eligible) {
726
- console.log(
727
- `Warning: this scan is not benchmark-grade (${response.scanEligibility.reasons.join(", ")}) \u2014 position is indicative only.`
728
- );
729
- }
730
- console.log(formatPosition(response.position, response.attackPackVersion));
731
- } catch (err) {
732
- reportError(err);
733
- }
734
- }
735
- async function offlinePositionCommand(opts) {
736
- try {
737
- if (!opts.snapshot || !opts.publicKey) {
738
- console.error(
739
- "Offline mode requires --snapshot <file> and --public-key <pem> (pinned out-of-band)."
740
- );
741
- setExitCode(2);
742
- return;
743
- }
744
- if (opts.score === void 0 || !opts.segmentKey) {
745
- console.error(
746
- "Offline mode requires --score <n> and --segment-key <key>."
747
- );
748
- setExitCode(2);
749
- return;
750
- }
751
- const snapshot2 = verifyAndLoadSnapshot({
752
- snapshotPath: String(opts.snapshot),
753
- signaturePath: String(opts.sig ?? `${opts.snapshot}.sig`),
754
- publicKeyPath: String(opts.publicKey)
755
- });
756
- console.log(
757
- `Signature verified (Ed25519) \u2014 snapshot of ${snapshot2.computedAt}, attack pack v${snapshot2.attackPackVersion}.`
758
- );
759
- const position = resolveOfflinePosition(snapshot2, {
760
- segment: parseSegmentKey(String(opts.segmentKey)),
761
- score: Number(opts.score)
762
- });
763
- console.log(formatPosition(position, snapshot2.attackPackVersion));
764
- } catch (err) {
765
- console.error(err instanceof Error ? err.message : String(err));
766
- setExitCode(2);
767
- }
768
- }
769
- async function snapshotExportCommand(opts) {
770
- const creds = requireCreds(opts);
771
- if (!creds) return;
772
- try {
773
- const out = String(opts.out ?? "./snapshot.json");
774
- const result = await exportSnapshot(creds, opts.cohort);
775
- writeFileSync2(out, result.snapshotJson);
776
- writeFileSync2(`${out}.sig`, result.signature + "\n");
777
- writeFileSync2(`${out}.pub.pem`, result.publicKeyPem);
778
- console.log(`Snapshot written: ${out} (+ .sig, + .pub.pem)`);
779
- console.log(
780
- "Distribute the public key through a separate, trusted channel and pin it on the verifying side."
781
- );
782
- } catch (err) {
783
- reportError(err);
784
- }
785
- }
786
- async function interactiveSubmitFlow(creds, scanId, log) {
787
- try {
788
- const { cohorts } = await listCohorts(creds);
789
- if (cohorts.length === 0) {
790
- log(
791
- "Benchmark: no cohort on this backend \u2014 create one with `shield-llm benchmark cohorts --create <name>`."
792
- );
793
- return;
794
- }
795
- const cohortId = cohorts.length === 1 ? cohorts[0].id : await select({
796
- message: "Cohort to contribute to:",
797
- choices: cohorts.map((c2) => ({
798
- name: `${c2.displayName} (pack v${c2.activePackVersion})`,
799
- value: c2.id
800
- }))
801
- });
802
- const detail = await getCohort(creds, cohortId);
803
- if (detail.targets.length === 0) {
804
- log(
805
- "Benchmark: this cohort has no declared organizations yet \u2014 add targets in the dashboard or API first."
806
- );
807
- return;
808
- }
809
- const targetId = await select({
810
- message: "Organization this scan belongs to:",
811
- choices: detail.targets.map((t) => ({
812
- name: `${t.displayName}${t.consent ? "" : " (no consent on record)"}`,
813
- value: t.id
814
- }))
815
- });
816
- await confirmAndSubmit(creds, { cohortId, scanId, targetId }, { log });
817
- } catch (err) {
818
- log(
819
- `Benchmark submission skipped: ${err instanceof Error ? err.message : String(err)}`
820
- );
821
- }
822
- }
823
-
824
407
  // src/commands/init.ts
825
- import { existsSync as existsSync2, writeFileSync as writeFileSync3 } from "fs";
826
- import { resolve } from "path";
827
408
  var CONFIG_FILENAME = "shield.config.json";
409
+ var METHOD_CHOICES = [
410
+ { value: "POST", name: "POST (most chatbots)" },
411
+ { value: "PUT", name: "PUT" },
412
+ { value: "PATCH", name: "PATCH" }
413
+ ];
414
+ var PRESET_CHOICES = [
415
+ { value: "dev", name: "dev \u2014 Smoke test of the connection" },
416
+ { value: "quick", name: "quick \u2014 Find flaws fast" },
417
+ {
418
+ value: "owasp",
419
+ name: "owasp \u2014 One test per OWASP LLM Top 10 category"
420
+ },
421
+ { value: "frontier", name: "frontier \u2014 Recent attack techniques" },
422
+ { value: "standard", name: "standard \u2014 Recommended" },
423
+ {
424
+ value: "full",
425
+ name: "full \u2014 Everything, multi-turn attacks included"
426
+ }
427
+ ];
828
428
  async function initCommand() {
829
429
  console.log("\nShield LLM \u2014 Configuration wizard\n");
830
430
  if (!process.stdin.isTTY) {
@@ -858,11 +458,7 @@ async function initCommand() {
858
458
  });
859
459
  const method = await select({
860
460
  message: "HTTP method:",
861
- choices: [
862
- { value: "POST", name: "POST (most chatbots)" },
863
- { value: "GET", name: "GET" },
864
- { value: "PUT", name: "PUT" }
865
- ],
461
+ choices: METHOD_CHOICES,
866
462
  default: "POST"
867
463
  });
868
464
  const auth = await collectAuth();
@@ -870,15 +466,7 @@ async function initCommand() {
870
466
  const customHeaders = await collectCustomHeaders();
871
467
  const preset = await select({
872
468
  message: "Default scan preset:",
873
- choices: [
874
- { value: "owasp", name: "owasp \u2014 OWASP LLM Top 10 (10 tests)" },
875
- { value: "quick", name: "quick \u2014 Find flaws fast (7 tests)" },
876
- { value: "standard", name: "standard \u2014 Recommended (39 tests)" },
877
- {
878
- value: "full",
879
- name: "full \u2014 Comprehensive (all tests + crescendo)"
880
- }
881
- ],
469
+ choices: PRESET_CHOICES,
882
470
  default: "standard"
883
471
  });
884
472
  const endpoint = {
@@ -908,7 +496,7 @@ ${issues}`);
908
496
  setExitCode(3);
909
497
  return;
910
498
  }
911
- writeFileSync3(configPath, JSON.stringify(result.data, null, 2) + "\n");
499
+ writeFileSync2(configPath, JSON.stringify(result.data, null, 2) + "\n");
912
500
  console.log(`
913
501
  \u2713 Config written to ${CONFIG_FILENAME}
914
502
  `);
@@ -1070,6 +658,7 @@ async function loginCommand(opts) {
1070
658
  Authorization: `Bearer ${key}`
1071
659
  }
1072
660
  });
661
+ if (await reportIfSuspended(res, apiUrl)) return;
1073
662
  if (res.status === 401) {
1074
663
  console.error(
1075
664
  "API key is invalid or revoked. Check the key and run `shield-llm login` again."
@@ -1111,6 +700,7 @@ async function presetsCommand(opts) {
1111
700
  const res = await fetch(`${apiUrl}/api/cli/presets`, {
1112
701
  headers: { Authorization: `Bearer ${stored.apiKey}` }
1113
702
  });
703
+ if (await reportIfSuspended(res, apiUrl)) return;
1114
704
  if (res.status === 401) {
1115
705
  console.error(
1116
706
  "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
@@ -1143,11 +733,11 @@ async function presetsCommand(opts) {
1143
733
  }
1144
734
 
1145
735
  // src/commands/report.ts
1146
- import { writeFileSync as writeFileSync5 } from "fs";
736
+ import { writeFileSync as writeFileSync4 } from "fs";
1147
737
  import { resolve as resolve2 } from "path";
1148
738
 
1149
739
  // src/fix/claim-store.ts
1150
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "fs";
740
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
1151
741
  import { dirname, join as join2 } from "path";
1152
742
  var DEFAULT_CLAIM_FILE = ".shield-llm/claims.json";
1153
743
  var ClaimStore = class _ClaimStore {
@@ -1159,7 +749,7 @@ var ClaimStore = class _ClaimStore {
1159
749
  }
1160
750
  load() {
1161
751
  if (!existsSync3(this.path)) return null;
1162
- return JSON.parse(readFileSync3(this.path, "utf8"));
752
+ return JSON.parse(readFileSync2(this.path, "utf8"));
1163
753
  }
1164
754
  list() {
1165
755
  return this.load()?.claims ?? [];
@@ -1222,7 +812,7 @@ var ClaimStore = class _ClaimStore {
1222
812
  }
1223
813
  write(file) {
1224
814
  mkdirSync2(dirname(this.path), { recursive: true });
1225
- writeFileSync4(this.path, `${JSON.stringify(file, null, 2)}
815
+ writeFileSync3(this.path, `${JSON.stringify(file, null, 2)}
1226
816
  `, "utf8");
1227
817
  }
1228
818
  };
@@ -1437,6 +1027,10 @@ async function reportCommand(scanId, opts) {
1437
1027
  process.exitCode = 3;
1438
1028
  return;
1439
1029
  }
1030
+ if (await reportIfSuspended(res, apiUrl)) {
1031
+ await res.text().catch(() => void 0);
1032
+ return;
1033
+ }
1440
1034
  if (res.status === 401) {
1441
1035
  await res.text().catch(() => void 0);
1442
1036
  console.error(
@@ -1466,7 +1060,7 @@ async function reportCommand(scanId, opts) {
1466
1060
  content = JSON.stringify(withClaimStatus(scan, claims), null, 2);
1467
1061
  }
1468
1062
  if (opts.outputFile) {
1469
- writeFileSync5(resolve2(opts.outputFile), content, "utf-8");
1063
+ writeFileSync4(resolve2(opts.outputFile), content, "utf-8");
1470
1064
  console.error(`Report written to ${opts.outputFile}`);
1471
1065
  } else {
1472
1066
  console.log(content);
@@ -1480,6 +1074,7 @@ async function fetchCustomTests(apiUrl, apiKey) {
1480
1074
  Authorization: `Bearer ${apiKey}`
1481
1075
  }
1482
1076
  });
1077
+ await throwIfSuspended(res, apiUrl);
1483
1078
  if (res.status === 401) {
1484
1079
  throw new Error(
1485
1080
  "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
@@ -1527,10 +1122,32 @@ function truncateInput(input2) {
1527
1122
  };
1528
1123
  }
1529
1124
  var TRANSIENT_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
1125
+ var CONNECTION_FAILURE_CODES = /* @__PURE__ */ new Set([
1126
+ "ECONNREFUSED",
1127
+ "ECONNRESET",
1128
+ "EPIPE",
1129
+ "ETIMEDOUT",
1130
+ "EAI_AGAIN",
1131
+ "UND_ERR_SOCKET",
1132
+ "UND_ERR_CLOSED",
1133
+ "UND_ERR_CONNECT_TIMEOUT"
1134
+ ]);
1135
+ var CONNECTION_RETRY_DELAYS_MS = [2e3, 5e3, 1e4, 2e4];
1136
+ function connectionFailureCode(err) {
1137
+ if (!(err instanceof TypeError)) return void 0;
1138
+ const cause = err.cause;
1139
+ const code = cause?.code;
1140
+ return typeof code === "string" && CONNECTION_FAILURE_CODES.has(code) ? code : void 0;
1141
+ }
1530
1142
  var BackendEvaluator = class {
1531
1143
  constructor(apiUrl, apiKey, opts) {
1532
1144
  this.apiUrl = apiUrl;
1533
1145
  this.apiKey = apiKey;
1146
+ /**
1147
+ * Set once the backend refused a verdict because the account is suspended
1148
+ * (403 account_suspended). Sticky: every later call would be refused too.
1149
+ */
1150
+ this.accountSuspended = false;
1534
1151
  this.maxRetries = opts?.maxRetries ?? 3;
1535
1152
  this.backoffMs = opts?.backoffMs ?? 1e3;
1536
1153
  this.maxBackoffMs = opts?.maxBackoffMs ?? 3e4;
@@ -1538,6 +1155,7 @@ var BackendEvaluator = class {
1538
1155
  this.sleep = opts?.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1539
1156
  }
1540
1157
  async evaluate(input2) {
1158
+ if (this.accountSuspended) throw new AccountSuspendedError(this.apiUrl);
1541
1159
  const body = JSON.stringify(truncateInput(input2));
1542
1160
  let attempt = 0;
1543
1161
  for (; ; ) {
@@ -1556,9 +1174,12 @@ var BackendEvaluator = class {
1556
1174
  });
1557
1175
  } catch (err) {
1558
1176
  const isTimeout = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError");
1559
- if (isTimeout && attempt < this.maxRetries) {
1177
+ const connection = connectionFailureCode(err);
1178
+ if ((isTimeout || connection) && attempt < this.maxRetries) {
1560
1179
  attempt++;
1561
- await this.sleep(this.backoffFor(null, attempt - 1));
1180
+ await this.sleep(
1181
+ connection ? CONNECTION_RETRY_DELAYS_MS[Math.min(attempt - 1, CONNECTION_RETRY_DELAYS_MS.length - 1)] : this.backoffFor(null, attempt - 1)
1182
+ );
1562
1183
  continue;
1563
1184
  }
1564
1185
  if (isTimeout) {
@@ -1566,6 +1187,11 @@ var BackendEvaluator = class {
1566
1187
  `Judge did not respond within ${this.requestTimeoutMs}ms after ${this.maxRetries} retries.`
1567
1188
  );
1568
1189
  }
1190
+ if (connection) {
1191
+ throw new Error(
1192
+ `Could not reach the Shield LLM backend at ${this.apiUrl} (${connection}) after ${this.maxRetries} retries.`
1193
+ );
1194
+ }
1569
1195
  throw err;
1570
1196
  }
1571
1197
  if (TRANSIENT_STATUSES.has(response.status) && attempt < this.maxRetries) {
@@ -1581,6 +1207,10 @@ var BackendEvaluator = class {
1581
1207
  }
1582
1208
  if (response.status === 403) {
1583
1209
  const errBody = await response.json().catch(() => ({}));
1210
+ if (isSuspendedBody(errBody)) {
1211
+ this.accountSuspended = true;
1212
+ throw new AccountSuspendedError(this.apiUrl);
1213
+ }
1584
1214
  throw new Error(errBody.error ?? "Access denied by the backend (403).");
1585
1215
  }
1586
1216
  if (response.status === 429) {
@@ -1955,6 +1585,7 @@ async function retestCommand(scanId, opts) {
1955
1585
  `${credentials.apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}`,
1956
1586
  { headers: { Authorization: `Bearer ${credentials.apiKey}` } }
1957
1587
  );
1588
+ if (await reportIfSuspended(res, credentials.apiUrl)) return;
1958
1589
  if (res.status === 401) {
1959
1590
  await res.text().catch(() => void 0);
1960
1591
  console.error(
@@ -2014,19 +1645,8 @@ async function retestCommand(scanId, opts) {
2014
1645
  return;
2015
1646
  }
2016
1647
  const cliOverrides = {};
2017
- if (opts.endpoint) {
2018
- cliOverrides.endpoint = {
2019
- url: opts.endpoint,
2020
- auth: buildAuthFromFlags(opts),
2021
- request: {
2022
- method: "POST",
2023
- body: opts.requestBody ? JSON.parse(opts.requestBody) : { message: "{{prompt}}" }
2024
- },
2025
- response: { field: opts.responseField ?? "response" },
2026
- // Local testing against localhost / private IPs (opt-in).
2027
- ...opts.allowPrivateUrls ? { allowPrivateUrls: true } : {}
2028
- };
2029
- }
1648
+ const endpoint = buildEndpointOverride(opts);
1649
+ if (endpoint) cliOverrides.endpoint = endpoint;
2030
1650
  const config = loadConfig({ configPath: opts.config, cliOverrides });
2031
1651
  const systemPrompt = loadSystemPrompt(config);
2032
1652
  const endpointHost = safeHostname(config.endpoint?.url);
@@ -2053,6 +1673,7 @@ async function retestCommand(scanId, opts) {
2053
1673
  customTests: needsCustom ? await fetchCustomTests(credentials.apiUrl, credentials.apiKey) : []
2054
1674
  };
2055
1675
  } catch (err) {
1676
+ if (reportAccountSuspended(err)) return;
2056
1677
  const msg = err instanceof Error ? err.message : "Unknown error";
2057
1678
  console.error(`Failed to fetch the attack catalogue: ${msg}`);
2058
1679
  setExitCode(3);
@@ -2104,8 +1725,12 @@ async function retestCommand(scanId, opts) {
2104
1725
  const onEvent = opts.progress !== false ? handleEvent : void 0;
2105
1726
  const scanner = new Scanner(scanOptions, onEvent);
2106
1727
  const report = await scanner.run();
1728
+ if (evaluator.accountSuspended) {
1729
+ reportAccountSuspended(new AccountSuspendedError(credentials.apiUrl));
1730
+ return;
1731
+ }
2107
1732
  const outcome = buildRetestOutcome(report.attacks, plan.findingByResultId);
2108
- let verify2 = null;
1733
+ let verify = null;
2109
1734
  let verifyError = null;
2110
1735
  if (outcome.verifications.length > 0) {
2111
1736
  try {
@@ -2123,11 +1748,12 @@ async function retestCommand(scanId, opts) {
2123
1748
  })
2124
1749
  }
2125
1750
  );
1751
+ if (await reportIfSuspended(res, credentials.apiUrl)) return;
2126
1752
  if (!res.ok) {
2127
1753
  const body = await res.text().catch(() => "");
2128
1754
  verifyError = `HTTP ${res.status}: ${body.slice(0, 200)}`;
2129
1755
  } else {
2130
- verify2 = await res.json();
1756
+ verify = await res.json();
2131
1757
  }
2132
1758
  } catch (err) {
2133
1759
  verifyError = err instanceof Error ? err.message : "Unknown error";
@@ -2163,7 +1789,7 @@ async function retestCommand(scanId, opts) {
2163
1789
  attackId: f.attackId,
2164
1790
  name: f.name
2165
1791
  })),
2166
- verify: verify2 ?? void 0,
1792
+ verify: verify ?? void 0,
2167
1793
  verifyError: verifyError ?? void 0
2168
1794
  },
2169
1795
  null,
@@ -2193,13 +1819,13 @@ async function retestCommand(scanId, opts) {
2193
1819
  console.log(
2194
1820
  `Retest complete: ${fixed.length - variantsOpen.length} fixed & verified, ` + (variantsOpen.length ? `${variantsOpen.length} exploit closed but its fix not confirmed, ` : "") + `${stillVulnerable.length} still vulnerable` + (outcome.failed.length + plan.unavailable.length > 0 ? `, ${outcome.failed.length + plan.unavailable.length} not retested` : "") + "."
2195
1821
  );
2196
- if (verify2) {
1822
+ if (verify) {
2197
1823
  console.log(
2198
- `Dashboard updated (${verify2.updated} finding(s) stamped).`
1824
+ `Dashboard updated (${verify.updated} finding(s) stamped).`
2199
1825
  );
2200
- if (verify2.notFound.length > 0) {
1826
+ if (verify.notFound.length > 0) {
2201
1827
  console.warn(
2202
- `Warning: no matching dashboard row for: ${verify2.notFound.join(", ")}`
1828
+ `Warning: no matching dashboard row for: ${verify.notFound.join(", ")}`
2203
1829
  );
2204
1830
  }
2205
1831
  }
@@ -2221,6 +1847,7 @@ async function retestCommand(scanId, opts) {
2221
1847
  );
2222
1848
  return;
2223
1849
  } catch (error) {
1850
+ if (reportAccountSuspended(error)) return;
2224
1851
  if (error instanceof ConfigError) {
2225
1852
  console.error(`Configuration error: ${error.message}`);
2226
1853
  setExitCode(2);
@@ -2245,7 +1872,7 @@ function safeHostname(url) {
2245
1872
  import { resolve as resolve5 } from "path";
2246
1873
 
2247
1874
  // src/reporters/evidence.ts
2248
- import { writeFileSync as writeFileSync6 } from "fs";
1875
+ import { writeFileSync as writeFileSync5 } from "fs";
2249
1876
  import { resolve as resolve3 } from "path";
2250
1877
 
2251
1878
  // ../../packages/shared/src/compliance/evidence-bundle.ts
@@ -2419,6 +2046,10 @@ function bundleLimitations(classification, noScoredEvidence = false) {
2419
2046
  }
2420
2047
  return base;
2421
2048
  }
2049
+ function agenticOf(testId) {
2050
+ const category = VULN_TO_AGENTIC[testId];
2051
+ return category ? { agenticCategory: category } : {};
2052
+ }
2422
2053
  function budgetedTests(tests) {
2423
2054
  const spent = { bytes: 0 };
2424
2055
  const excerpts = /* @__PURE__ */ new Map();
@@ -2445,6 +2076,7 @@ function budgetedTests(tests) {
2445
2076
  excludedFromScore: t.excludedFromScore,
2446
2077
  evaluationMethod: t.evaluationMethod,
2447
2078
  confidence: t.confidence,
2079
+ ...agenticOf(t.testId),
2448
2080
  prompt: p.excerpt,
2449
2081
  promptTruncated: p.truncated,
2450
2082
  promptOmitted: p.omitted,
@@ -2504,9 +2136,12 @@ function buildEvidenceBundle(input2) {
2504
2136
  overallScore: input2.compliance.overallScore,
2505
2137
  status: input2.compliance.status,
2506
2138
  hardFailedArticles: [...input2.compliance.hardFailedArticles ?? []],
2139
+ // The bundle is an English document, whatever language the result was
2140
+ // computed in: it said "Art. 10 & RGPD" and "RGPD Art. 5 & 32"
2141
+ // (2026-10-30).
2507
2142
  aspects: input2.compliance.aspects.map((a) => ({
2508
2143
  aspect: a.aspect,
2509
- articleLabel: a.articleLabel,
2144
+ articleLabel: aspectArticleLabel(a.aspect, "en"),
2510
2145
  score: a.score,
2511
2146
  totalTests: a.totalTests,
2512
2147
  passedTests: a.passedTests,
@@ -2516,7 +2151,7 @@ function buildEvidenceBundle(input2) {
2516
2151
  testId: nc.testId,
2517
2152
  testName: nc.testName,
2518
2153
  severity: nc.severity,
2519
- articleNumber: nc.article.articleNumber,
2154
+ articleNumber: articleNumberEn(nc.article.articleNumber),
2520
2155
  complianceAspect: nc.article.complianceAspect,
2521
2156
  observedBreach: nc.article.observedBreach === true
2522
2157
  }))
@@ -2629,7 +2264,7 @@ function writeEvidenceBundle(input2) {
2629
2264
  });
2630
2265
  const outPath = resolve3(input2.path);
2631
2266
  const json = JSON.stringify(bundle, null, 2);
2632
- writeFileSync6(outPath, json, "utf8");
2267
+ writeFileSync5(outPath, json, "utf8");
2633
2268
  return {
2634
2269
  path: outPath,
2635
2270
  sha256: bundle.manifest.sha256,
@@ -2679,12 +2314,12 @@ function sanitizeReportForDisk(report, opts = {}) {
2679
2314
  }
2680
2315
 
2681
2316
  // src/lib/output-path.ts
2682
- import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync7 } from "fs";
2317
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync6 } from "fs";
2683
2318
  import { dirname as dirname2, resolve as resolve4 } from "path";
2684
2319
  function writeOutputFile(path, content) {
2685
2320
  const full = resolve4(path);
2686
2321
  mkdirSync3(dirname2(full), { recursive: true });
2687
- writeFileSync7(
2322
+ writeFileSync6(
2688
2323
  full,
2689
2324
  content,
2690
2325
  typeof content === "string" ? "utf-8" : void 0
@@ -2841,6 +2476,10 @@ async function uploadReportToBackend(report, credentials, scanId, attackPackVers
2841
2476
  body: JSON.stringify(payload)
2842
2477
  });
2843
2478
  if (!res.ok) {
2479
+ if (await isAccountSuspended(res)) {
2480
+ await res.text().catch(() => void 0);
2481
+ throw new AccountSuspendedError(credentials.apiUrl);
2482
+ }
2844
2483
  const body = await res.text().catch(() => "");
2845
2484
  const incomplete = incompleteRejection(res.status, body);
2846
2485
  if (incomplete) throw new IncompleteRejection(incomplete);
@@ -2880,6 +2519,7 @@ async function reserveScanSlot(credentials, targetUrl) {
2880
2519
  },
2881
2520
  body: JSON.stringify({ targetUrl })
2882
2521
  });
2522
+ if (await reportIfSuspended(res, credentials.apiUrl)) return null;
2883
2523
  if (res.status === 401) {
2884
2524
  console.error(
2885
2525
  "API key is invalid or revoked. Run `shield-llm login` to re-authenticate."
@@ -2916,21 +2556,8 @@ function resolveMutateSelection(value) {
2916
2556
  }
2917
2557
  function buildCliOverrides(opts) {
2918
2558
  const cliOverrides = {};
2919
- if (opts.endpoint) {
2920
- cliOverrides.endpoint = {
2921
- url: opts.endpoint,
2922
- auth: buildAuthFromFlags(opts),
2923
- request: {
2924
- method: "POST",
2925
- body: opts.requestBody ? JSON.parse(opts.requestBody) : { message: "{{prompt}}" }
2926
- },
2927
- response: {
2928
- field: opts.responseField ?? "response"
2929
- },
2930
- // Local testing against localhost / private IPs (opt-in).
2931
- ...opts.allowPrivateUrls ? { allowPrivateUrls: true } : {}
2932
- };
2933
- }
2559
+ const endpoint = buildEndpointOverride(opts);
2560
+ if (endpoint) cliOverrides.endpoint = endpoint;
2934
2561
  if (opts.preset) cliOverrides.preset = opts.preset;
2935
2562
  if (opts.systemPrompt) cliOverrides.systemPrompt = opts.systemPrompt;
2936
2563
  if (opts.crescendo) cliOverrides.includeCrescendo = true;
@@ -2960,6 +2587,7 @@ function buildCliOverrides(opts) {
2960
2587
  cliOverrides.maxNotExecutedPercent = opts.maxNotExecuted;
2961
2588
  return cliOverrides;
2962
2589
  }
2590
+ var PDF_FROM_DASHBOARD = "The CLI no longer writes PDF reports. Every scan is saved in your dashboard, which produces the official PDFs (security and compliance, English and French): open the scan there and use Download. For a file from the CLI, use -o json, -o markdown or -o sarif.";
2963
2591
  async function scanCommand(opts) {
2964
2592
  if (opts.mutate === "list") {
2965
2593
  console.log("Available attack mutators (--mutate <ids>):\n");
@@ -2968,6 +2596,11 @@ async function scanCommand(opts) {
2968
2596
  }
2969
2597
  return;
2970
2598
  }
2599
+ if (opts.output === "pdf") {
2600
+ console.error(PDF_FROM_DASHBOARD);
2601
+ setExitCode(2);
2602
+ return;
2603
+ }
2971
2604
  let reservedScanId = null;
2972
2605
  let scanFinalized = false;
2973
2606
  let failTarget = null;
@@ -3031,6 +2664,7 @@ async function scanCommand(opts) {
3031
2664
  }
3032
2665
  }
3033
2666
  } catch (err) {
2667
+ if (reportAccountSuspended(err)) return;
3034
2668
  const msg = err instanceof Error ? err.message : "Unknown error";
3035
2669
  console.error(`Failed to fetch custom tests: ${msg}`);
3036
2670
  setExitCode(3);
@@ -3154,6 +2788,11 @@ async function scanCommand(opts) {
3154
2788
  info("Scan started");
3155
2789
  const scanner = new Scanner(scanOptions, onEvent);
3156
2790
  const report = await scanner.run();
2791
+ if (evaluator.accountSuspended) {
2792
+ console.error(accountSuspendedMessage(credentials.apiUrl));
2793
+ setExitCode(2);
2794
+ return;
2795
+ }
3157
2796
  const attempted = report.attacks.length;
3158
2797
  const evaluated = scoredAttacks(report.attacks).length;
3159
2798
  const nothingRan = report.stopReason === "not_executed" && evaluated === 0;
@@ -3202,6 +2841,7 @@ async function scanCommand(opts) {
3202
2841
  );
3203
2842
  }
3204
2843
  } catch (err) {
2844
+ if (reportAccountSuspended(err)) return;
3205
2845
  if (err instanceof IncompleteRejection) {
3206
2846
  scanFinalized = true;
3207
2847
  console.error(`Scan stopped: ${err.message}`);
@@ -3229,21 +2869,6 @@ async function scanCommand(opts) {
3229
2869
  }
3230
2870
  }
3231
2871
  }
3232
- const benchmarkEligible = presetForScan === "full" && !customOnly && (config.customTests?.length ?? 0) === 0 && attackPackVersion !== void 0;
3233
- if (opts.consent || benchmarkEligible) {
3234
- info(
3235
- benchmarkEligible ? `Benchmark: scan is eligible (full preset, attack pack v${attackPackVersion})` : `Benchmark: scan is NOT eligible (requires the full preset with no custom tests)`
3236
- );
3237
- }
3238
- if (opts.consent && uploadedScanId) {
3239
- if (opts.ci) {
3240
- info(
3241
- "Benchmark: --consent is interactive and is skipped in --ci mode. Use `shield-llm benchmark submit --yes` instead."
3242
- );
3243
- } else {
3244
- await interactiveSubmitFlow(credentials, uploadedScanId, info);
3245
- }
3246
- }
3247
2872
  let thresholdResult = evaluateThresholds(report, config.thresholds);
3248
2873
  const thresholdsConfigured = config.thresholds !== void 0 || opts.complianceThreshold !== void 0;
3249
2874
  let evidenceBundleNote = "";
@@ -3300,8 +2925,16 @@ async function scanCommand(opts) {
3300
2925
  );
3301
2926
  }
3302
2927
  }
3303
- const format = config.output?.format ?? opts.output;
2928
+ let format = config.output?.format ?? opts.output;
3304
2929
  let outputFile = config.output?.file ?? opts.outputFile;
2930
+ if (format === "pdf") {
2931
+ info(
2932
+ `The CLI no longer writes PDF reports. Download it from the dashboard` + (uploadedScanId ? `: ${credentials.apiUrl}/scans/${uploadedScanId}` : "") + `. Writing the JSON report instead.`
2933
+ );
2934
+ format = "json";
2935
+ if (outputFile)
2936
+ outputFile = alignOutputExtension(outputFile, "json").path;
2937
+ }
3305
2938
  if (outputFile && format && opts.output && !opts.outputFile) {
3306
2939
  const aligned = alignOutputExtension(outputFile, format);
3307
2940
  if (aligned.changed) {
@@ -3312,16 +2945,13 @@ async function scanCommand(opts) {
3312
2945
  }
3313
2946
  }
3314
2947
  if (format || outputFile) {
3315
- if (format === "pdf") {
3316
- const pdfPath = outputFile ?? `shield-report-${report.id.slice(0, 8)}.pdf`;
3317
- const pdfBuffer = await generatePdf(report);
3318
- writeOutputFile(pdfPath, pdfBuffer);
3319
- info(`PDF report written to ${pdfPath}`);
3320
- } else {
2948
+ {
3321
2949
  let content;
3322
2950
  switch (format) {
3323
2951
  case "sarif":
3324
- content = formatSarif(report);
2952
+ content = formatSarif(report, {
2953
+ docsBaseUrl: credentials.apiUrl
2954
+ });
3325
2955
  break;
3326
2956
  case "markdown":
3327
2957
  content = formatMarkdown(report, thresholdResult, complianceResult);
@@ -3361,6 +2991,7 @@ async function scanCommand(opts) {
3361
2991
  setExitCode(thresholdResult.passed ? 0 : 1);
3362
2992
  return;
3363
2993
  } catch (error) {
2994
+ if (reportAccountSuspended(error)) return;
3364
2995
  if (failTarget && reservedScanId && !scanFinalized) {
3365
2996
  const reason = error instanceof ConfigError ? `Configuration error: ${error.message}` : `Scan run failed: ${error instanceof Error ? error.message : "Unknown error"}`;
3366
2997
  await reportScanFailure(failTarget, reservedScanId, reason);
@@ -3604,6 +3235,7 @@ async function testsCommand(opts) {
3604
3235
  try {
3605
3236
  remoteTests = await fetchCustomTests(apiUrl, stored.apiKey);
3606
3237
  } catch (err) {
3238
+ if (reportAccountSuspended(err)) return;
3607
3239
  const msg = err instanceof Error ? err.message : "Unknown error";
3608
3240
  console.error(`Failed to fetch remote tests: ${msg}`);
3609
3241
  setExitCode(3);
@@ -3680,12 +3312,12 @@ function validateCommand(opts) {
3680
3312
  }
3681
3313
 
3682
3314
  // src/commands/fix.ts
3683
- import { existsSync as existsSync6, readFileSync as readFileSync6, readdirSync } from "fs";
3315
+ import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync } from "fs";
3684
3316
  import { execFileSync as execFileSync3 } from "child_process";
3685
3317
  import { resolve as resolve7 } from "path";
3686
3318
 
3687
3319
  // src/fix/anchor-resolver.ts
3688
- import { existsSync as existsSync4, readFileSync as readFileSync4, statSync } from "fs";
3320
+ import { existsSync as existsSync4, readFileSync as readFileSync3, statSync } from "fs";
3689
3321
  import { isAbsolute, relative, resolve as resolve6, sep } from "path";
3690
3322
  var AnchorError = class extends Error {
3691
3323
  constructor(message, kind, status) {
@@ -3732,7 +3364,7 @@ function resolveAnchor(root, kind, anchor) {
3732
3364
  );
3733
3365
  }
3734
3366
  if (anchor.export) {
3735
- const source = readFileSync4(abs, "utf8");
3367
+ const source = readFileSync3(abs, "utf8");
3736
3368
  if (!declaresExport(source, anchor.export)) {
3737
3369
  throw new AnchorError(
3738
3370
  `${configHint}.export is "${anchor.export}" but ${anchor.file} does not declare it. (v1 resolves exports textually: a star re-export like \`export * from "./barrel"\` is not seen \u2014 point the anchor at the file that actually declares the symbol.)`,
@@ -3832,6 +3464,15 @@ function evaluateVerdict(input2, options = {}) {
3832
3464
 
3833
3465
  // src/fix/plan.ts
3834
3466
  var NO_RECIPE_DETAIL = `no v1 recipe covers these attacks: v1 patches ${RECIPES.flatMap((r) => r.appliesTo).join(", ")}; the others need a code or architecture change and become issues`;
3467
+ function unmatchedOnly(only, findings, targetUrl) {
3468
+ const known = new Set(
3469
+ findings.flatMap((f) => [
3470
+ f.attackId,
3471
+ fingerprintFromScan(targetUrl, f.attackId)
3472
+ ])
3473
+ );
3474
+ return only.filter((id) => !known.has(id));
3475
+ }
3835
3476
  function groupSkipped(skipped) {
3836
3477
  const groups = /* @__PURE__ */ new Map();
3837
3478
  for (const s of skipped) {
@@ -3855,7 +3496,13 @@ function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
3855
3496
  for (const f of findings) {
3856
3497
  const fingerprint = fingerprintFromScan(targetUrl, f.attackId);
3857
3498
  if (wanted && !wanted.has(fingerprint) && !wanted.has(f.attackId)) continue;
3858
- const push = (reason, detail) => skipped.push({ fingerprint, attackId: f.attackId, name: f.name, reason, detail });
3499
+ const push = (reason, detail) => skipped.push({
3500
+ fingerprint,
3501
+ attackId: f.attackId,
3502
+ name: f.name,
3503
+ reason,
3504
+ detail
3505
+ });
3859
3506
  const verdict = evaluateVerdict(
3860
3507
  {
3861
3508
  attackId: f.attackId,
@@ -3926,7 +3573,13 @@ function buildPlan(findings, targetUrl, codebase, cwd, options = {}) {
3926
3573
  verdictDetail: verdict.detail
3927
3574
  });
3928
3575
  }
3929
- return { targetId, planned, skipped, anchors, blockedByAnchor: blockedByAnchor(anchors) };
3576
+ return {
3577
+ targetId,
3578
+ planned,
3579
+ skipped,
3580
+ anchors,
3581
+ blockedByAnchor: blockedByAnchor(anchors)
3582
+ };
3930
3583
  }
3931
3584
  function languageCompatible(recipeLang, codebaseLang) {
3932
3585
  if (recipeLang === codebaseLang) return true;
@@ -3937,14 +3590,22 @@ function blockedByAnchor(anchors) {
3937
3590
  const out = [];
3938
3591
  for (const [kind, res] of anchors) {
3939
3592
  if (res.status === "resolved") continue;
3940
- const ids = RECIPES.filter((r) => r.requiresAnchors.includes(kind)).map((r) => r.id);
3593
+ const ids = RECIPES.filter((r) => r.requiresAnchors.includes(kind)).map(
3594
+ (r) => r.id
3595
+ );
3941
3596
  if (ids.length) out.push({ kind, recipeIds: ids });
3942
3597
  }
3943
3598
  return out;
3944
3599
  }
3945
3600
 
3946
3601
  // src/fix/operations.ts
3947
- import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync5, rmSync, writeFileSync as writeFileSync8 } from "fs";
3602
+ import {
3603
+ existsSync as existsSync5,
3604
+ mkdirSync as mkdirSync4,
3605
+ readFileSync as readFileSync4,
3606
+ rmSync,
3607
+ writeFileSync as writeFileSync7
3608
+ } from "fs";
3948
3609
  import { dirname as dirname3, relative as relative2 } from "path";
3949
3610
 
3950
3611
  // src/fix/marker-block.ts
@@ -4112,18 +3773,22 @@ var WorkingSet = class {
4112
3773
  const cached = this.files.get(relPath);
4113
3774
  if (cached) return cached.current;
4114
3775
  const abs = safeResolve(this.root, relPath);
4115
- const before = existsSync5(abs) ? readFileSync5(abs, "utf8") : "";
3776
+ const before = existsSync5(abs) ? readFileSync4(abs, "utf8") : "";
4116
3777
  this.files.set(relPath, { before, current: before });
4117
3778
  return before;
4118
3779
  }
4119
3780
  write(relPath, next) {
4120
- const entry = this.files.get(relPath) ?? { before: this.read(relPath), current: "" };
3781
+ const entry = this.files.get(relPath) ?? {
3782
+ before: this.read(relPath),
3783
+ current: ""
3784
+ };
4121
3785
  this.files.set(relPath, { before: entry.before, current: next });
4122
3786
  }
4123
3787
  changes(markerIds) {
4124
3788
  const out = [];
4125
3789
  for (const [path, { before, current }] of this.files) {
4126
- if (before !== current) out.push({ path, before, after: current, markerIds });
3790
+ if (before !== current)
3791
+ out.push({ path, before, after: current, markerIds });
4127
3792
  }
4128
3793
  return out;
4129
3794
  }
@@ -4136,7 +3801,7 @@ var WorkingSet = class {
4136
3801
  continue;
4137
3802
  }
4138
3803
  mkdirSync4(dirname3(abs), { recursive: true });
4139
- writeFileSync8(abs, current, "utf8");
3804
+ writeFileSync7(abs, current, "utf8");
4140
3805
  }
4141
3806
  }
4142
3807
  };
@@ -4181,12 +3846,17 @@ function recomposeEffective(source, effectiveExport) {
4181
3846
  );
4182
3847
  }
4183
3848
  const composition = parseComposition(m[2].trim(), effectiveExport);
4184
- const parts = composition.parts.filter((p) => !p.startsWith(GUARDRAIL_PREFIX));
3849
+ const parts = composition.parts.filter(
3850
+ (p) => !p.startsWith(GUARDRAIL_PREFIX)
3851
+ );
4185
3852
  const guardrails = [
4186
3853
  ...new Set(
4187
3854
  Array.from(
4188
3855
  source.matchAll(
4189
- new RegExp(`export\\s+const\\s+(${GUARDRAIL_PREFIX}[A-Z0-9_]+)\\s*=`, "g")
3856
+ new RegExp(
3857
+ `export\\s+const\\s+(${GUARDRAIL_PREFIX}[A-Z0-9_]+)\\s*=`,
3858
+ "g"
3859
+ )
4190
3860
  ),
4191
3861
  (g) => g[1]
4192
3862
  )
@@ -4197,7 +3867,10 @@ function recomposeEffective(source, effectiveExport) {
4197
3867
  return source.replace(re, `$1${next};`);
4198
3868
  }
4199
3869
  function effectiveExportOffset(source, effectiveExport) {
4200
- const m = new RegExp(`^.*export\\s+const\\s+${effectiveExport}\\s*=`, "m").exec(source);
3870
+ const m = new RegExp(
3871
+ `^.*export\\s+const\\s+${effectiveExport}\\s*=`,
3872
+ "m"
3873
+ ).exec(source);
4201
3874
  if (!m) {
4202
3875
  throw new Error(
4203
3876
  `cannot place block: no \`export const ${effectiveExport} = \u2026\` in the anchored file`
@@ -4209,7 +3882,8 @@ function effectiveExportOffset(source, effectiveExport) {
4209
3882
  if (prevEnd <= 0) break;
4210
3883
  const prevStart = source.lastIndexOf("\n", prevEnd - 1) + 1;
4211
3884
  const line = source.slice(prevStart, prevEnd).trim();
4212
- if (!line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*")) break;
3885
+ if (!line.startsWith("//") && !line.startsWith("*") && !line.startsWith("/*"))
3886
+ break;
4213
3887
  start = prevStart;
4214
3888
  }
4215
3889
  return start;
@@ -4217,7 +3891,9 @@ function effectiveExportOffset(source, effectiveExport) {
4217
3891
  function anchorPath(ctx, kind) {
4218
3892
  const res = ctx.anchors.get(kind);
4219
3893
  if (!res || res.status !== "resolved" || !res.resolvedPath) {
4220
- throw new Error(`anchor "${kind}" is not resolved \u2014 the recipe must not have been selected`);
3894
+ throw new Error(
3895
+ `anchor "${kind}" is not resolved \u2014 the recipe must not have been selected`
3896
+ );
4221
3897
  }
4222
3898
  return { rel: relative2(ctx.root, res.resolvedPath), abs: res.resolvedPath };
4223
3899
  }
@@ -4242,7 +3918,10 @@ function applyOperation(op, recipe, ctx, ws) {
4242
3918
  const state = src === "" ? "absent" : inspectBlock(src, op.path, recipe.id, body);
4243
3919
  if (state === "drifted") throw new DriftError(op.path, recipe.id);
4244
3920
  if (state === "identical") return true;
4245
- ws.write(op.path, appendBlock("", op.path, recipe.id, ctx.fingerprint, body));
3921
+ ws.write(
3922
+ op.path,
3923
+ appendBlock("", op.path, recipe.id, ctx.fingerprint, body)
3924
+ );
4246
3925
  return false;
4247
3926
  }
4248
3927
  case "prompt-guardrail": {
@@ -4253,7 +3932,10 @@ function applyOperation(op, recipe, ctx, ws) {
4253
3932
  const state = inspectBlock(src, rel, recipe.id, body);
4254
3933
  if (state === "drifted") throw new DriftError(rel, recipe.id);
4255
3934
  const effective = anchorExport(ctx, op.anchor);
4256
- if (!effective) throw new Error(`anchor "${op.anchor}" declares no export to compose into`);
3935
+ if (!effective)
3936
+ throw new Error(
3937
+ `anchor "${op.anchor}" declares no export to compose into`
3938
+ );
4257
3939
  const withBlock = state === "identical" ? src : insertBlockAt(
4258
3940
  src,
4259
3941
  rel,
@@ -4284,20 +3966,30 @@ export function ${op.exportName}(...args) {
4284
3966
  const foreign = foreignBlockOwning(withoutBlock, rel, recipe.id, declRe);
4285
3967
  if (foreign) throw new WrapCollisionError(rel, op.exportName, foreign);
4286
3968
  if (declRe.test(base)) {
4287
- base = base.replace(declRe, (_m, asyncKw) => `${asyncKw ?? ""}function ${op.renameTo}`);
3969
+ base = base.replace(
3970
+ declRe,
3971
+ (_m, asyncKw) => `${asyncKw ?? ""}function ${op.renameTo}`
3972
+ );
4288
3973
  } else if (!base.includes(`function ${op.renameTo}`)) {
4289
3974
  throw new Error(
4290
3975
  `cannot wrap: ${rel} declares neither \`export function ${op.exportName}\` nor the renamed \`${op.renameTo}\``
4291
3976
  );
4292
3977
  }
4293
- const next = appendBlock(base, rel, recipe.id, ctx.fingerprint, wrapperBody);
3978
+ const next = appendBlock(
3979
+ base,
3980
+ rel,
3981
+ recipe.id,
3982
+ ctx.fingerprint,
3983
+ wrapperBody
3984
+ );
4294
3985
  if (next === src) return true;
4295
3986
  ws.write(rel, next);
4296
3987
  return false;
4297
3988
  }
4298
3989
  case "add-dependency": {
4299
3990
  const src = ws.read("package.json");
4300
- if (!src) throw new Error("add-dependency: no package.json at the codebase root");
3991
+ if (!src)
3992
+ throw new Error("add-dependency: no package.json at the codebase root");
4301
3993
  const pkg = JSON.parse(src);
4302
3994
  const field = op.dev ? "devDependencies" : "dependencies";
4303
3995
  pkg[field] ??= {};
@@ -4337,7 +4029,10 @@ function revertRecipe(recipe, ctx) {
4337
4029
  const { rel } = anchorPath(ctx, op.anchor);
4338
4030
  const stripped = removeBlock(ws.read(rel), rel, recipe.id);
4339
4031
  const effective = anchorExport(ctx, op.anchor);
4340
- ws.write(rel, effective ? recomposeEffective(stripped, effective) : stripped);
4032
+ ws.write(
4033
+ rel,
4034
+ effective ? recomposeEffective(stripped, effective) : stripped
4035
+ );
4341
4036
  continue;
4342
4037
  }
4343
4038
  if (op.kind === "wrap-export") {
@@ -4602,7 +4297,8 @@ async function sync(opts) {
4602
4297
  if (!creds?.apiKey || !creds.apiUrl) {
4603
4298
  return { synced: false, reason: "not logged in" };
4604
4299
  }
4605
- const url = `${resolveApiUrl(creds.apiUrl, opts.apiUrl)}/api/cli/claims`;
4300
+ const apiUrl = resolveApiUrl(creds.apiUrl, opts.apiUrl);
4301
+ const url = `${apiUrl}/api/cli/claims`;
4606
4302
  const doFetch = opts.fetchImpl ?? fetch;
4607
4303
  let stored = 0;
4608
4304
  let ignored = 0;
@@ -4630,6 +4326,12 @@ async function sync(opts) {
4630
4326
  };
4631
4327
  }
4632
4328
  if (!res.ok) {
4329
+ if (await isAccountSuspended(res)) {
4330
+ return {
4331
+ synced: false,
4332
+ reason: accountSuspendedMessage(apiUrl).replace(/\.$/, "")
4333
+ };
4334
+ }
4633
4335
  return {
4634
4336
  synced: false,
4635
4337
  reason: res.status === 404 ? "the dashboard holds no scan of this target for this account" : `HTTP ${res.status}`
@@ -4856,11 +4558,15 @@ async function captureBenignBaseline(target, scope, judge) {
4856
4558
  try {
4857
4559
  verdicts1 = await judgeBenign(run1, BENIGN_CORE_V1, judge, {
4858
4560
  ...opts,
4859
- onProgress: phaseProgress("Judging the answers before the patch, run 1/2")
4561
+ onProgress: phaseProgress(
4562
+ "Judging the answers before the patch, run 1/2"
4563
+ )
4860
4564
  });
4861
4565
  verdicts2 = await judgeBenign(run2, BENIGN_CORE_V1, judge, {
4862
4566
  ...opts,
4863
- onProgress: phaseProgress("Judging the answers before the patch, run 2/2")
4567
+ onProgress: phaseProgress(
4568
+ "Judging the answers before the patch, run 2/2"
4569
+ )
4864
4570
  });
4865
4571
  } catch (e) {
4866
4572
  console.warn(
@@ -4952,15 +4658,24 @@ async function judgePatchedAnswers(baseline, cases, contract, target, judge) {
4952
4658
  onProgress: phaseProgress("Legitimate questions after the patch")
4953
4659
  });
4954
4660
  const unchanged = unchangedVerdicts(baseline, after);
4955
- const judged = await judgeBenign(
4956
- after.filter((a) => !unchanged.has(a.name)),
4957
- cases,
4958
- judge,
4959
- {
4960
- votes: BENIGN_VOTES,
4961
- onProgress: phaseProgress("Judging the answers that changed")
4962
- }
4963
- );
4661
+ let judged;
4662
+ try {
4663
+ judged = await judgeBenign(
4664
+ after.filter((a) => !unchanged.has(a.name)),
4665
+ cases,
4666
+ judge,
4667
+ {
4668
+ votes: BENIGN_VOTES,
4669
+ onProgress: phaseProgress("Judging the answers that changed")
4670
+ }
4671
+ );
4672
+ } catch (e) {
4673
+ return {
4674
+ green: false,
4675
+ ran: false,
4676
+ detail: `the judge could not be reached (${e instanceof Error ? e.message : String(e)}), so the gate could not run`
4677
+ };
4678
+ }
4964
4679
  const judgedByName = new Map(judged.map((r) => [r.name, r]));
4965
4680
  const afterRun = after.map(
4966
4681
  (a) => unchanged.get(a.name) ?? judgedByName.get(a.name)
@@ -5075,36 +4790,53 @@ function passDetail(baseline, cases, report, judged, afterRun) {
5075
4790
  const scope = kept ? `${cases.length} cases, ${cases.length - kept} judged after the patch, ${kept} unchanged answer(s) kept their pre-patch verdict` : `${cases.length} cases judged`;
5076
4791
  return `${scope}, ${report.flips.length} flip(s)${excluded}${splitNote}`;
5077
4792
  }
5078
- async function replayFamily(contract, target, catalogue, evaluator, judgeRetryDelayMs) {
5079
- const attacks = attacksForContract(contract, catalogue);
5080
- const report = await new Scanner({
5081
- target,
5082
- // CLI-only: expand $VAR auth references from the environment, as every
5083
- // other CLI scan path does. See scanner-core/src/env.ts.
5084
- resolveEnv: true,
5085
- preset: "dev",
5086
- attacks,
5087
- evaluator,
5088
- concurrency: 1,
5089
- delayMs: 0,
5090
- // Undefined keeps the scanner's default pause before its re-judge pass.
5091
- judgeRetryDelayMs
5092
- }).run();
4793
+ var DEFAULT_REPLAYS = 3;
4794
+ var MAX_REPLAYS = 10;
4795
+ async function replayFamily(contract, target, catalogue, evaluator, judgeRetryDelayMs, replays = DEFAULT_REPLAYS) {
4796
+ const runs = Math.min(Math.max(1, Math.floor(replays)), MAX_REPLAYS);
4797
+ let pending = attacksForContract(contract, catalogue);
5093
4798
  const verdicts = /* @__PURE__ */ new Map();
5094
- for (const a of report.attacks) {
5095
- if (a.error || a.rateLimited) continue;
5096
- verdicts.set(a.id, a.vulnerable);
4799
+ let judgeDegraded = false;
4800
+ for (let run = 0; run < runs && pending.length > 0; run++) {
4801
+ const report = await new Scanner({
4802
+ target,
4803
+ // CLI-only: expand $VAR auth references from the environment, as every
4804
+ // other CLI scan path does. See scanner-core/src/env.ts.
4805
+ resolveEnv: true,
4806
+ preset: "dev",
4807
+ attacks: pending,
4808
+ evaluator,
4809
+ concurrency: 1,
4810
+ delayMs: 0,
4811
+ // Undefined keeps the scanner's default pause before its re-judge pass.
4812
+ judgeRetryDelayMs
4813
+ }).run();
4814
+ if (analyzeJudgeHealth(report).degraded) judgeDegraded = true;
4815
+ const stillClosed = /* @__PURE__ */ new Set();
4816
+ for (const a of report.attacks) {
4817
+ if (a.error || a.rateLimited) {
4818
+ verdicts.delete(a.id);
4819
+ continue;
4820
+ }
4821
+ verdicts.set(a.id, a.vulnerable);
4822
+ if (!a.vulnerable) stillClosed.add(a.id);
4823
+ }
4824
+ for (const a of pending) {
4825
+ if (!report.attacks.some((r) => r.id === a.id)) verdicts.delete(a.id);
4826
+ }
4827
+ pending = pending.filter((a) => stillClosed.has(a.id));
5097
4828
  }
5098
- return { verdicts, judgeDegraded: analyzeJudgeHealth(report).degraded };
4829
+ return { verdicts, judgeDegraded, replays: runs };
5099
4830
  }
5100
4831
  async function verifyLive(input2) {
5101
4832
  const { contract } = input2;
5102
- const { verdicts, judgeDegraded } = await replayFamily(
4833
+ const { verdicts, judgeDegraded, replays } = await replayFamily(
5103
4834
  contract,
5104
4835
  input2.target,
5105
4836
  input2.catalogue,
5106
4837
  input2.evaluator,
5107
- input2.judgeRetryDelayMs
4838
+ input2.judgeRetryDelayMs,
4839
+ input2.replays
5108
4840
  );
5109
4841
  const cleared = (id) => verdicts.get(id) === false;
5110
4842
  const executed = (id) => verdicts.has(id);
@@ -5137,6 +4869,7 @@ async function verifyLive(input2) {
5137
4869
  },
5138
4870
  judgeDegraded,
5139
4871
  sessionIsolated: checkSessionIsolation(input2.target).isolated,
4872
+ replays,
5140
4873
  passed
5141
4874
  };
5142
4875
  }
@@ -5385,7 +5118,7 @@ function dirtyPathsExcluding(cwd, ours) {
5385
5118
 
5386
5119
  // src/fix/pr.ts
5387
5120
  import { execFileSync as execFileSync2 } from "child_process";
5388
- import { mkdtempSync, writeFileSync as writeFileSync9 } from "fs";
5121
+ import { mkdtempSync, writeFileSync as writeFileSync8 } from "fs";
5389
5122
  import { tmpdir } from "os";
5390
5123
  import { join as join3 } from "path";
5391
5124
  function ghStatus(cwd) {
@@ -5412,7 +5145,7 @@ function ghStatus(cwd) {
5412
5145
  function createPullRequest(input2) {
5413
5146
  const dir = mkdtempSync(join3(tmpdir(), "shield-pr-"));
5414
5147
  const bodyFile = join3(dir, "body.md");
5415
- writeFileSync9(bodyFile, input2.body, "utf8");
5148
+ writeFileSync8(bodyFile, input2.body, "utf8");
5416
5149
  const args = [
5417
5150
  "pr",
5418
5151
  "create",
@@ -5618,7 +5351,9 @@ async function fetchStoredScan(apiUrl, apiKey, scanId) {
5618
5351
  throw new Error(`Failed to reach the dashboard (${apiUrl}): ${msg}`);
5619
5352
  }
5620
5353
  if (!res.ok) {
5354
+ const suspended = await isAccountSuspended(res);
5621
5355
  await res.text().catch(() => void 0);
5356
+ if (suspended) throw new AccountSuspendedError(apiUrl);
5622
5357
  if (res.status === 401) {
5623
5358
  throw new Error(
5624
5359
  "API key invalid or revoked. Run `shield-llm login` to re-authenticate."
@@ -5685,7 +5420,8 @@ async function resolveCatalogue(opts) {
5685
5420
  } catch (err) {
5686
5421
  return {
5687
5422
  attacks: null,
5688
- reason: err instanceof Error ? err.message : "unknown error"
5423
+ reason: err instanceof Error ? err.message : "unknown error",
5424
+ suspended: err instanceof AccountSuspendedError
5689
5425
  };
5690
5426
  }
5691
5427
  })();
@@ -5693,7 +5429,7 @@ async function resolveCatalogue(opts) {
5693
5429
  return pending;
5694
5430
  }
5695
5431
  function findingsFromLocalReport(path) {
5696
- const parsed = JSON.parse(readFileSync6(path, "utf8"));
5432
+ const parsed = JSON.parse(readFileSync5(path, "utf8"));
5697
5433
  const r = parsed.report;
5698
5434
  if (!r?.attacks)
5699
5435
  throw new Error(`${path} is not a shield-llm --write-json report`);
@@ -5845,6 +5581,14 @@ async function fixCommand(opts) {
5845
5581
  setExitCode(2);
5846
5582
  return;
5847
5583
  }
5584
+ const unknownOnly = unmatchedOnly(opts.only ?? [], findings, targetUrl);
5585
+ if (unknownOnly.length) {
5586
+ console.error(
5587
+ `--only names no finding of this scan: ${unknownOnly.join(", ")}. Its findings: ${findings.map((f) => f.attackId).join(", ") || "none"}.`
5588
+ );
5589
+ setExitCode(2);
5590
+ return;
5591
+ }
5848
5592
  let plan;
5849
5593
  try {
5850
5594
  plan = buildPlan(findings, targetUrl, codebase, cwd, {
@@ -5852,7 +5596,8 @@ async function fixCommand(opts) {
5852
5596
  disagreementAvailable: findings.some(
5853
5597
  (f) => f.disagreementResolution != null
5854
5598
  ),
5855
- knownSecrets: config.endpoint?.knownSecrets
5599
+ knownSecrets: config.endpoint?.knownSecrets,
5600
+ only: opts.only
5856
5601
  });
5857
5602
  } catch (e) {
5858
5603
  console.error(
@@ -6097,14 +5842,18 @@ The patch is applied but UNVERIFIED.`
6097
5842
  \u26A0\uFE0F ${isolation.warning}
6098
5843
  `);
6099
5844
  const { evaluator, judgeAvailable } = resolveEvaluator(opts);
6100
- const { attacks: catalogue, reason } = await resolveCatalogue(opts);
5845
+ const {
5846
+ attacks: catalogue,
5847
+ reason,
5848
+ suspended
5849
+ } = await resolveCatalogue(opts);
6101
5850
  if (!catalogue) {
6102
5851
  console.error(
6103
5852
  `
6104
5853
  Cannot verify: the attack catalogue could not be fetched (${reason}).
6105
5854
  The patch is applied but UNVERIFIED \u2014 nothing was replayed against it.`
6106
5855
  );
6107
- setExitCode(3);
5856
+ setExitCode(suspended ? 2 : 3);
6108
5857
  return "aborted";
6109
5858
  }
6110
5859
  if (!judgeAvailable && catalogue.some((a) => !a.detectPatterns?.length)) {
@@ -6127,7 +5876,8 @@ The patch is applied but UNVERIFIED \u2014 nothing was replayed against it.`
6127
5876
  baseline,
6128
5877
  assumeBenignGreen: opts.assumeBenignGreen,
6129
5878
  redeployCommand: codebase.redeploy.command,
6130
- nowMs: Date.now()
5879
+ nowMs: Date.now(),
5880
+ replays: opts.replays
6131
5881
  });
6132
5882
  evidence.set(p.fingerprint, v);
6133
5883
  console.log(
@@ -6312,7 +6062,7 @@ function closurePathConfigured(root) {
6312
6062
  if (!existsSync6(dir)) return false;
6313
6063
  try {
6314
6064
  return readdirSync(dir).some(
6315
- (f) => readFileSync6(resolve7(dir, f), "utf8").includes("verify-claims")
6065
+ (f) => readFileSync5(resolve7(dir, f), "utf8").includes("verify-claims")
6316
6066
  );
6317
6067
  } catch {
6318
6068
  return false;
@@ -6408,13 +6158,15 @@ async function verifyClaimsCommand(opts) {
6408
6158
  }
6409
6159
  const { catalogue } = resolved;
6410
6160
  console.error(
6411
- `Verifying ${claim.recipeId} (${pending.indexOf(claim) + 1}/${pending.length}): replaying ${claim.contract.designAttackIds.length + claim.contract.holdoutAttackIds.length} attack(s), then the legitimate questions\u2026`
6161
+ `Verifying ${claim.recipeId} (${pending.indexOf(claim) + 1}/${pending.length}): replaying ${claim.contract.designAttackIds.length + claim.contract.holdoutAttackIds.length} attack(s) up to ${opts.replays ?? DEFAULT_REPLAYS} times each, then the legitimate questions\u2026`
6412
6162
  );
6413
- const { verdicts, judgeDegraded } = await replayFamily(
6163
+ const { verdicts, judgeDegraded, replays } = await replayFamily(
6414
6164
  claim.contract,
6415
6165
  target,
6416
6166
  catalogue,
6417
- evaluator
6167
+ evaluator,
6168
+ void 0,
6169
+ opts.replays
6418
6170
  );
6419
6171
  const benign = await runBenignGate({
6420
6172
  baseline: claim.benignBaseline,
@@ -6452,6 +6204,7 @@ async function verifyClaimsCommand(opts) {
6452
6204
  },
6453
6205
  judgeDegraded,
6454
6206
  sessionIsolated: checkSessionIsolation(target).isolated,
6207
+ replays,
6455
6208
  trigger: "verify-claims",
6456
6209
  nowMs: now
6457
6210
  });
@@ -6513,6 +6266,18 @@ function parsePercentArg(value) {
6513
6266
  }
6514
6267
  return n;
6515
6268
  }
6269
+ function parseListArg(value) {
6270
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
6271
+ }
6272
+ function parseReplaysArg(value) {
6273
+ const n = Number(value);
6274
+ if (!Number.isInteger(n) || n < 1 || n > MAX_REPLAYS) {
6275
+ throw new InvalidArgumentError(
6276
+ `Expected a whole number from 1 to ${MAX_REPLAYS}.`
6277
+ );
6278
+ }
6279
+ return n;
6280
+ }
6516
6281
  function parseFloatArg(value) {
6517
6282
  const n = Number.parseFloat(value);
6518
6283
  if (Number.isNaN(n)) {
@@ -6548,7 +6313,10 @@ process.on("uncaughtException", (err) => {
6548
6313
  var program = new Command();
6549
6314
  program.exitOverride();
6550
6315
  program.name("shield-llm").description("AI chatbot security scanner \u2014 automated red teaming for LLMs").version(version);
6551
- program.command("scan").description("Run a security scan against a target chatbot").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, oauth2").option("--token <value>", "Bearer token or API key value").option("--auth-header <name>", "Custom auth header name (for api-key auth)").option(
6316
+ program.command("scan").description("Run a security scan against a target chatbot").option("-c, --config <path>", "Path to shield.config.json").option("-e, --endpoint <url>", "Target chatbot HTTP endpoint URL").option(
6317
+ "--auth <type>",
6318
+ "Auth type: bearer, api-key (OAuth2: set endpoint.auth in shield.config.json)"
6319
+ ).option("--token <value>", "Bearer token or API key value").option("--auth-header <name>", "Custom auth header name (for api-key auth)").option(
6552
6320
  "--response-field <path>",
6553
6321
  "Dot-notation path to response text in JSON (default: response)"
6554
6322
  ).option(
@@ -6594,7 +6362,10 @@ program.command("scan").description("Run a security scan against a target chatbo
6594
6362
  ).option("--min-score <n>", "Minimum score threshold", parseFloat).option("--fail-on-critical", "Fail if any CRITICAL vulnerability found").option(
6595
6363
  "--no-fail-on-critical",
6596
6364
  "Report CRITICAL findings without failing the run"
6597
- ).option("-o, --output <format>", "Output format (json, markdown, sarif, pdf)").option("--output-file <path>", "Write report to file").option(
6365
+ ).option(
6366
+ "-o, --output <format>",
6367
+ "Output format (json, markdown, sarif). PDF reports come from the dashboard"
6368
+ ).option("--output-file <path>", "Write report to file").option(
6598
6369
  "--write-json <path>",
6599
6370
  "Always write a parseable JSON copy here, regardless of --output (useful for CI to extract score/grade alongside SARIF)"
6600
6371
  ).option(
@@ -6619,9 +6390,6 @@ program.command("scan").description("Run a security scan against a target chatbo
6619
6390
  ).option(
6620
6391
  "--api-url <url>",
6621
6392
  "Backend API URL (overrides SHIELD_API_URL env var and stored credentials)"
6622
- ).option(
6623
- "--consent",
6624
- "After the scan, offer to contribute an anonymous aggregate to a benchmark cohort (interactive preview + explicit confirmation)"
6625
6393
  ).option(
6626
6394
  "--no-resume",
6627
6395
  "Ignore any saved checkpoint and start fresh (the scan still checkpoints so it can resume if THIS run is interrupted)"
@@ -6629,36 +6397,6 @@ program.command("scan").description("Run a security scan against a target chatbo
6629
6397
  "--checkpoint-dir <path>",
6630
6398
  "Directory for resumable scan checkpoints (default: .shield-llm/checkpoints)"
6631
6399
  ).action(scanCommand);
6632
- var benchmark = program.command("benchmark").description("Cohort benchmarking \u2014 consent, submission, relative position");
6633
- benchmark.command("cohorts").description("List your cohorts, or create one with --create").option(
6634
- "--create <name>",
6635
- "Create a cohort pinned to the current attack pack version"
6636
- ).option("--k-min <n>", "K-anonymity threshold for --create (default 5)").option("--api-url <url>", "Backend API URL override").action(cohortsCommand);
6637
- var consent = benchmark.command("consent").description("Manage an organization's contribution consent");
6638
- consent.command("show").description(
6639
- "Preview the EXACT payload a submission would send (nothing is sent)"
6640
- ).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);
6641
- 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(
6642
- "--scope <scopes>",
6643
- "Comma-separated: global_score,category_scores,segment_metadata"
6644
- ).requiredOption(
6645
- "--by <identity>",
6646
- "Identity/role with authority granting the consent"
6647
- ).option("--api-url <url>", "Backend API URL override").action(consentGrantCommand);
6648
- 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);
6649
- benchmark.command("submit").description(
6650
- "Contribute a scan's anonymous aggregate (preview + confirmation)"
6651
- ).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);
6652
- benchmark.command("position").description(
6653
- "Relative position of a score within the cohort (read-only; --offline for air-gapped)"
6654
- ).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(
6655
- "--public-key <pem>",
6656
- "Issuer public key PEM, pinned out-of-band (offline mode, REQUIRED)"
6657
- ).option("--api-url <url>", "Backend API URL override").action(positionCommand);
6658
- var snapshot = benchmark.command("snapshot").description("Signed distribution snapshots for air-gapped positioning");
6659
- snapshot.command("export").description(
6660
- "Export the cohort's signed snapshot (segments under k_min are excluded)"
6661
- ).requiredOption("--cohort <id>", "Cohort id").option("--out <file>", "Output path (default ./snapshot.json)").option("--api-url <url>", "Backend API URL override").action(snapshotExportCommand);
6662
6400
  program.command("init").description("Generate a shield.config.json interactively").action(initCommand);
6663
6401
  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);
6664
6402
  program.command("presets").description("List available scan presets (fetched from your backend)").option("--api-url <url>", "Backend API URL override").action(presetsCommand);
@@ -6672,6 +6410,10 @@ program.command("fix [scanId]").description(
6672
6410
  "--explain",
6673
6411
  "Show which recipes apply and which anchors would unlock more"
6674
6412
  ).option("--revert", "Remove every shield-llm block this recipe set owns").option(
6413
+ "--only <ids>",
6414
+ "Patch only these findings: attack ids or finding fingerprints, comma-separated (ship and verify one fix alone)",
6415
+ parseListArg
6416
+ ).option(
6675
6417
  "--min-confidence <n>",
6676
6418
  "Override the verdict-gate threshold",
6677
6419
  parseFloatArg
@@ -6693,6 +6435,10 @@ program.command("fix [scanId]").description(
6693
6435
  ).option(
6694
6436
  "--assume-benign-green",
6695
6437
  "Confirm without running the benign gate when no judge is configured (recorded on the claim)"
6438
+ ).option(
6439
+ "--replays <n>",
6440
+ "Replay each attack n times; it counts as closed only if every replay is (default 3)",
6441
+ parseReplaysArg
6696
6442
  ).option(
6697
6443
  "--rescan",
6698
6444
  "After verifying, replay the original scan's attacks and report the score delta over a frozen denominator (informational \u2014 the holdout replay stays the gate)"
@@ -6718,6 +6464,10 @@ program.command("verify-claims").description(
6718
6464
  "--deployed-at <iso>",
6719
6465
  "Explicit deploy timestamp (implicit when run post-deploy)"
6720
6466
  ).option("--ci", "JSON output for pipelines").option(
6467
+ "--replays <n>",
6468
+ "Replay each attack n times; it counts as closed only if every replay is (default 3)",
6469
+ parseReplaysArg
6470
+ ).option(
6721
6471
  "--assume-benign-green",
6722
6472
  "Confirm without running the benign gate when no judge is configured (recorded on the claim)"
6723
6473
  ).action(async (o) => {