shield-llm 0.16.0 → 0.17.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.
@@ -1357,6 +1357,7 @@ function describeNotExecuted(byCategory, categories = NOT_EXECUTED_CATEGORIES) {
1357
1357
 
1358
1358
  // ../../packages/shared/src/attack-error.ts
1359
1359
  var MAX_ATTACK_ERROR_ITEMS = 50;
1360
+ var MAX_ATTACK_ERROR_WIRE_ITEMS = 2500;
1360
1361
  function categorizeAttackError(error, rateLimited) {
1361
1362
  if (rateLimited) return "rate_limited";
1362
1363
  if (error?.startsWith(NOT_JUDGED_PREFIX)) return "judge_error";
@@ -1379,7 +1380,7 @@ function categorizeAttackError(error, rateLimited) {
1379
1380
  if (/\b4\d\d\b/.test(e)) return "blocked";
1380
1381
  return "other";
1381
1382
  }
1382
- function summarizeAttackErrors(attacks) {
1383
+ function summarizeAttackErrors(attacks, itemCap = MAX_ATTACK_ERROR_ITEMS) {
1383
1384
  const all = [];
1384
1385
  const byCategory = {};
1385
1386
  for (const a of attacks) {
@@ -1392,7 +1393,7 @@ function summarizeAttackErrors(attacks) {
1392
1393
  const items = [
1393
1394
  ...all.filter((it) => it.category === "judge_error"),
1394
1395
  ...all.filter((it) => it.category !== "judge_error")
1395
- ].slice(0, MAX_ATTACK_ERROR_ITEMS);
1396
+ ].slice(0, itemCap);
1396
1397
  return { total: all.length, byCategory, items };
1397
1398
  }
1398
1399
 
@@ -9536,7 +9537,7 @@ function parseImportFile(textContent, format) {
9536
9537
  }
9537
9538
 
9538
9539
  // package.json
9539
- var version = "0.16.0";
9540
+ var version = "0.17.0";
9540
9541
 
9541
9542
  // src/config/schema.ts
9542
9543
  import { z as z3 } from "zod";
@@ -11279,65 +11280,17 @@ var Scanner = class {
11279
11280
  });
11280
11281
  }
11281
11282
  }
11282
- for (const customTest of customTests) {
11283
- const resumed = done.get(`custom_${customTest.name}`);
11284
- if (resumed) {
11285
- results.push(resumed);
11286
- this.emit({
11287
- type: "attack:complete",
11288
- result: resumed,
11289
- index: attackIndex,
11290
- total: totalAttacks
11291
- });
11292
- attackIndex++;
11293
- continue;
11294
- }
11295
- if (authFailed) {
11296
- const skip = {
11297
- id: `custom_${customTest.name}`,
11298
- name: customTest.name,
11299
- severity: customTestSeverity(customTest),
11300
- vulnerable: false,
11301
- prompt: customTest.prompt,
11302
- response: "",
11303
- durationMs: 0,
11304
- error: SKIP_AUTH
11305
- };
11306
- results.push(skip);
11307
- this.emit({
11308
- type: "attack:complete",
11309
- result: skip,
11310
- index: attackIndex,
11311
- total: totalAttacks
11312
- });
11313
- attackIndex++;
11314
- continue;
11315
- }
11316
- this.emit({
11317
- type: "attack:start",
11318
- attack: {
11319
- id: `custom_${customTest.name}`,
11320
- name: customTest.name,
11321
- severity: customTestSeverity(customTest)
11322
- },
11323
- index: attackIndex,
11324
- total: totalAttacks
11325
- });
11326
- const result = await this.executeCustomTest(customTest);
11327
- results.push(result);
11328
- await store?.record(result);
11329
- if (result.authFailed) authFailed = true;
11330
- this.emit({
11331
- type: "attack:complete",
11332
- result,
11333
- index: attackIndex,
11334
- total: totalAttacks
11335
- });
11336
- attackIndex++;
11337
- if (attackIndex < totalAttacks && this.currentDelayMs > 0) {
11338
- await sleep(this.currentDelayMs);
11339
- }
11340
- }
11283
+ const custom = await this.runCustomTests(
11284
+ customTests,
11285
+ done,
11286
+ store,
11287
+ attackIndex,
11288
+ totalAttacks,
11289
+ authFailed
11290
+ );
11291
+ results.push(...custom.results);
11292
+ authFailed = custom.authFailed;
11293
+ attackIndex += customTests.length;
11341
11294
  const recovery = await rejudgePass(results, {
11342
11295
  evaluator: this.evaluator,
11343
11296
  inputs: this.rejudgeInputs,
@@ -11602,6 +11555,102 @@ var Scanner = class {
11602
11555
  // ──────────────────────────────────────────────
11603
11556
  // Custom Test Execution
11604
11557
  // ──────────────────────────────────────────────
11558
+ /**
11559
+ * Custom tests through the same adaptive pool as the single-turn attacks
11560
+ * (lot C slice 3): they ran one at a time, so an account's 300 tests took
11561
+ * 300 target round trips and 300 judge calls end to end. Up to the
11562
+ * current AIMD cap run at once (`concurrency`, 1 with an MCP harness); a
11563
+ * 429 shrinks it as in the attack phase. Results keep the tests' order.
11564
+ * Refused credentials stop new launches and the rest are skipped; a
11565
+ * breaker trip or throttle keeps its historical behaviour here (custom
11566
+ * tests still run).
11567
+ */
11568
+ async runCustomTests(customTests, done, store, firstIndex, totalAttacks, authFailedBefore) {
11569
+ let authFailed = authFailedBefore;
11570
+ const out = new Array(
11571
+ customTests.length
11572
+ );
11573
+ const pending = [];
11574
+ customTests.forEach((test, i) => {
11575
+ const resumed = done.get(`custom_${test.name}`);
11576
+ if (!resumed) {
11577
+ pending.push(i);
11578
+ return;
11579
+ }
11580
+ out[i] = resumed;
11581
+ this.emit({
11582
+ type: "attack:complete",
11583
+ result: resumed,
11584
+ index: firstIndex + i,
11585
+ total: totalAttacks
11586
+ });
11587
+ });
11588
+ this.inConcurrentPhase = true;
11589
+ let next = 0;
11590
+ await new Promise((resolve2, reject) => {
11591
+ let active = 0;
11592
+ const pump = () => {
11593
+ while (active < this.aimdLimit && next < pending.length && !authFailed) {
11594
+ const idx = pending[next++];
11595
+ active++;
11596
+ void this.runOneCustomTest(
11597
+ customTests[idx],
11598
+ firstIndex + idx,
11599
+ totalAttacks,
11600
+ store
11601
+ ).then((result) => {
11602
+ out[idx] = result;
11603
+ if (result.authFailed) authFailed = true;
11604
+ active--;
11605
+ pump();
11606
+ }, reject);
11607
+ }
11608
+ if (active === 0 && (next >= pending.length || authFailed)) resolve2();
11609
+ };
11610
+ pump();
11611
+ });
11612
+ this.inConcurrentPhase = false;
11613
+ customTests.forEach((test, i) => {
11614
+ if (out[i]) return;
11615
+ const skip = {
11616
+ id: `custom_${test.name}`,
11617
+ name: test.name,
11618
+ severity: customTestSeverity(test),
11619
+ vulnerable: false,
11620
+ prompt: test.prompt,
11621
+ response: "",
11622
+ durationMs: 0,
11623
+ error: SKIP_AUTH
11624
+ };
11625
+ out[i] = skip;
11626
+ this.emit({
11627
+ type: "attack:complete",
11628
+ result: skip,
11629
+ index: firstIndex + i,
11630
+ total: totalAttacks
11631
+ });
11632
+ });
11633
+ return { results: out, authFailed };
11634
+ }
11635
+ /** One custom test in the pool: pace, send, judge, record, report. */
11636
+ async runOneCustomTest(test, index, totalAttacks, store) {
11637
+ this.emit({
11638
+ type: "attack:start",
11639
+ attack: {
11640
+ id: `custom_${test.name}`,
11641
+ name: test.name,
11642
+ severity: customTestSeverity(test)
11643
+ },
11644
+ index,
11645
+ total: totalAttacks
11646
+ });
11647
+ if (this.currentDelayMs > 0) await sleep(this.currentDelayMs);
11648
+ const result = await this.executeCustomTest(test);
11649
+ await store?.record(result);
11650
+ if (!result.error && !result.rateLimited) this.handleSuccess();
11651
+ this.emit({ type: "attack:complete", result, index, total: totalAttacks });
11652
+ return result;
11653
+ }
11605
11654
  async executeCustomTest(test) {
11606
11655
  const startTime = Date.now();
11607
11656
  const session = this.targetClient.createSession();
@@ -12537,7 +12586,9 @@ var CONFIG_FILENAMES = ["shield.config.json"];
12537
12586
  function loadConfig(options) {
12538
12587
  const { configPath, cliOverrides } = options;
12539
12588
  let fileConfig = {};
12589
+ let fileFound = false;
12540
12590
  if (configPath) {
12591
+ fileFound = true;
12541
12592
  const fullPath = resolve(configPath);
12542
12593
  if (!existsSync(fullPath)) {
12543
12594
  throw new ConfigError(`Config file not found: ${fullPath}`);
@@ -12548,10 +12599,17 @@ function loadConfig(options) {
12548
12599
  const fullPath = resolve(filename);
12549
12600
  if (existsSync(fullPath)) {
12550
12601
  fileConfig = readJsonFile(fullPath);
12602
+ fileFound = true;
12551
12603
  break;
12552
12604
  }
12553
12605
  }
12554
12606
  }
12607
+ if (!fileFound && !cliOverrides?.endpoint?.url) {
12608
+ throw new ConfigError(
12609
+ `No ${CONFIG_FILENAMES[0]} in ${process.cwd()}.
12610
+ Run \`shield-llm init\` to create one, or pass --config <path>.`
12611
+ );
12612
+ }
12555
12613
  const merged = deepMerge(fileConfig, cliOverrides ?? {});
12556
12614
  const result = ConfigSchema.safeParse(merged);
12557
12615
  if (!result.success) {
@@ -12887,8 +12945,36 @@ var CATEGORY_LABELS = {
12887
12945
  provider_error: "LLM provider returned a server error",
12888
12946
  unknown: "LLM judge failed (see backend logs)"
12889
12947
  };
12948
+ var SHIELD_BUDGET_LABELS = {
12949
+ shield_daily_user_budget: "your daily judge budget on this Shield instance is spent; it resets at 00:00 UTC, or ask your Shield administrator to raise it",
12950
+ shield_daily_total_budget: "this Shield instance's daily judge budget is spent; it resets at 00:00 UTC"
12951
+ };
12952
+ function summaryFor(category, codes) {
12953
+ const seen = codes.get(category);
12954
+ if (seen?.size === 1) {
12955
+ const label = budgetLabel(Array.from(seen)[0]);
12956
+ if (label) return label;
12957
+ }
12958
+ return CATEGORY_LABELS[category];
12959
+ }
12960
+ function shieldBudgetReason(report) {
12961
+ const codes = /* @__PURE__ */ new Set();
12962
+ for (const a of report.attacks) {
12963
+ if (!a.llmEvaluation) continue;
12964
+ const judgeError = extractJudgeError(a.llmEvaluation);
12965
+ if (judgeError && !isFloorConfirmed(a.llmEvaluation)) {
12966
+ codes.add(judgeError.providerCode);
12967
+ }
12968
+ }
12969
+ if (codes.size !== 1) return null;
12970
+ return budgetLabel(Array.from(codes)[0]);
12971
+ }
12972
+ function budgetLabel(code) {
12973
+ return code && Object.prototype.hasOwnProperty.call(SHIELD_BUDGET_LABELS, code) ? SHIELD_BUDGET_LABELS[code] : null;
12974
+ }
12890
12975
  function analyzeJudgeHealth(report) {
12891
12976
  const counts = /* @__PURE__ */ new Map();
12977
+ const codes = /* @__PURE__ */ new Map();
12892
12978
  let degradedCount = 0;
12893
12979
  let totalEvaluated = 0;
12894
12980
  for (const a of report.attacks) {
@@ -12897,7 +12983,13 @@ function analyzeJudgeHealth(report) {
12897
12983
  const judgeError = extractJudgeError(a.llmEvaluation);
12898
12984
  if (judgeError && !isFloorConfirmed(a.llmEvaluation)) {
12899
12985
  degradedCount += 1;
12900
- counts.set(judgeError.category, (counts.get(judgeError.category) ?? 0) + 1);
12986
+ counts.set(
12987
+ judgeError.category,
12988
+ (counts.get(judgeError.category) ?? 0) + 1
12989
+ );
12990
+ const seen = codes.get(judgeError.category) ?? /* @__PURE__ */ new Set();
12991
+ seen.add(judgeError.providerCode);
12992
+ codes.set(judgeError.category, seen);
12901
12993
  }
12902
12994
  }
12903
12995
  const rejudged = report.judgeRecovery?.rejudged ?? 0;
@@ -12920,7 +13012,7 @@ function analyzeJudgeHealth(report) {
12920
13012
  degradedCount,
12921
13013
  totalEvaluated,
12922
13014
  category,
12923
- errorSummary: CATEGORY_LABELS[category],
13015
+ errorSummary: summaryFor(category, codes),
12924
13016
  rejudged,
12925
13017
  notJudged: notJudged2
12926
13018
  };
@@ -13227,6 +13319,8 @@ export {
13227
13319
  NOT_EXECUTED_CATEGORIES,
13228
13320
  formatShareAboveLimit,
13229
13321
  describeNotExecuted,
13322
+ MAX_ATTACK_ERROR_ITEMS,
13323
+ MAX_ATTACK_ERROR_WIRE_ITEMS,
13230
13324
  summarizeAttackErrors,
13231
13325
  serializeAttack,
13232
13326
  deserializeAttack,
@@ -13271,6 +13365,8 @@ export {
13271
13365
  parseImportFile,
13272
13366
  version,
13273
13367
  RateLimitError,
13368
+ isPrivateUrl,
13369
+ assertPublicHost,
13274
13370
  checkConversationContext,
13275
13371
  checkSessionIsolation,
13276
13372
  createTargetClient,
@@ -13291,6 +13387,7 @@ export {
13291
13387
  buildEndpointOverride,
13292
13388
  ConfigError,
13293
13389
  c2 as c,
13390
+ shieldBudgetReason,
13294
13391
  analyzeJudgeHealth,
13295
13392
  evaluateThresholds,
13296
13393
  formatComplianceTerminal,
package/dist/cli.js CHANGED
@@ -19,6 +19,8 @@ import {
19
19
  IMPORT_SOURCES,
20
20
  JUDGE_OUTAGE_REASON_PREFIX,
21
21
  LAYER_META,
22
+ MAX_ATTACK_ERROR_ITEMS,
23
+ MAX_ATTACK_ERROR_WIRE_ITEMS,
22
24
  MUTATORS,
23
25
  McpHarness,
24
26
  NOT_EXECUTED_CATEGORIES,
@@ -33,6 +35,7 @@ import {
33
35
  analyzeJudgeHealth,
34
36
  articleNumberEn,
35
37
  aspectArticleLabel,
38
+ assertPublicHost,
36
39
  attacksForContract,
37
40
  baseAttackId,
38
41
  buildEndpointOverride,
@@ -69,6 +72,7 @@ import {
69
72
  isExpired,
70
73
  isFloorConfirmed,
71
74
  isHardFailBreach,
75
+ isPrivateUrl,
72
76
  loadConfig,
73
77
  loadSystemPrompt,
74
78
  mayStampFixed,
@@ -84,11 +88,12 @@ import {
84
88
  retestDedupKey,
85
89
  serializeAttack,
86
90
  sha256Hex,
91
+ shieldBudgetReason,
87
92
  summarizeAttackErrors,
88
93
  summarizeObfuscationVariants,
89
94
  version,
90
95
  withoutScoredApartVariants
91
- } from "./chunk-O2K6SD5X.js";
96
+ } from "./chunk-24WGTB3E.js";
92
97
 
93
98
  // src/load-env.ts
94
99
  var PROTECTED_ENV_KEYS = [
@@ -463,6 +468,20 @@ var PRESET_CHOICES = [
463
468
  name: "full \u2014 Everything, multi-turn attacks included"
464
469
  }
465
470
  ];
471
+ function buildInitEndpoint(answers) {
472
+ const { url, method, auth, body, responseField, customHeaders } = answers;
473
+ return {
474
+ url,
475
+ ...isPrivateUrl(url) && { allowPrivateUrls: true },
476
+ request: {
477
+ method,
478
+ ...Object.keys(customHeaders).length > 0 && { headers: customHeaders },
479
+ body
480
+ },
481
+ response: { field: responseField },
482
+ auth: auth.type !== "none" ? auth : { type: "none" }
483
+ };
484
+ }
466
485
  async function initCommand() {
467
486
  console.log("\nShield LLM \u2014 Configuration wizard\n");
468
487
  if (!process.stdin.isTTY) {
@@ -507,19 +526,18 @@ async function initCommand() {
507
526
  choices: PRESET_CHOICES,
508
527
  default: "standard"
509
528
  });
510
- const endpoint = {
529
+ const endpoint = buildInitEndpoint({
511
530
  url,
512
- request: {
513
- method,
514
- ...Object.keys(customHeaders).length > 0 && { headers: customHeaders },
515
- body
516
- },
517
- response: { field: responseField }
518
- };
519
- if (auth.type !== "none") {
520
- endpoint.auth = auth;
521
- } else {
522
- endpoint.auth = { type: "none" };
531
+ method,
532
+ auth,
533
+ body,
534
+ responseField,
535
+ customHeaders
536
+ });
537
+ if (endpoint.allowPrivateUrls) {
538
+ console.log(
539
+ '\nThis is a local or private address: the config sets "allowPrivateUrls": true so the scan accepts it.'
540
+ );
523
541
  }
524
542
  const config = { endpoint, preset };
525
543
  const result = ConfigSchema.safeParse(config);
@@ -855,6 +873,16 @@ var ClaimStore = class _ClaimStore {
855
873
  }
856
874
  };
857
875
 
876
+ // src/lib/scan-not-found.ts
877
+ var SHORT_LABEL_MAX = 12;
878
+ function shortIdHint(scanId) {
879
+ if (scanId.length > SHORT_LABEL_MAX) return "";
880
+ return "\n This looks like the short label shown on the dashboard. Use the full scan id:\n it is in the scan page's address and in its Scan Info panel (copy button).";
881
+ }
882
+ function scanNotFoundMessage(scanId) {
883
+ return `Scan "${scanId}" not found.${shortIdHint(scanId)}`;
884
+ }
885
+
858
886
  // src/lib/format.ts
859
887
  function truncate(str, max) {
860
888
  const oneLine = str.replace(/\n/g, " ").trim();
@@ -962,6 +990,44 @@ function buildRetestOutcome(results, findingByResultId) {
962
990
  }
963
991
  return outcome;
964
992
  }
993
+ var VERIFY_BATCH_ITEMS = 200;
994
+ var VERIFY_BATCH_BYTES = 3.5 * 1024 * 1024;
995
+ function verifyBatches(entries, maxItems = VERIFY_BATCH_ITEMS, maxBytes = VERIFY_BATCH_BYTES) {
996
+ const batches = [];
997
+ let batch = [];
998
+ let bytes = 0;
999
+ for (const e of entries) {
1000
+ const size = Buffer.byteLength(JSON.stringify(e), "utf8") + 1;
1001
+ if (batch.length > 0 && (batch.length >= maxItems || bytes + size > maxBytes)) {
1002
+ batches.push(batch);
1003
+ batch = [];
1004
+ bytes = 0;
1005
+ }
1006
+ batch.push(e);
1007
+ bytes += size;
1008
+ }
1009
+ if (batch.length > 0) batches.push(batch);
1010
+ return batches;
1011
+ }
1012
+ async function postVerifyBatches(entries, post) {
1013
+ let total = null;
1014
+ let sent = 0;
1015
+ for (const batch of verifyBatches(entries)) {
1016
+ const res = await post(batch);
1017
+ if (!res.ok) {
1018
+ const error = sent > 0 ? `${res.error} (${sent} of ${entries.length} verdicts were recorded before it)` : res.error;
1019
+ return { response: total, error };
1020
+ }
1021
+ total = {
1022
+ updated: (total?.updated ?? 0) + res.response.updated,
1023
+ fixed: (total?.fixed ?? 0) + res.response.fixed,
1024
+ stillVulnerable: (total?.stillVulnerable ?? 0) + res.response.stillVulnerable,
1025
+ notFound: [...total?.notFound ?? [], ...res.response.notFound]
1026
+ };
1027
+ sent += batch.length;
1028
+ }
1029
+ return { response: total, error: null };
1030
+ }
965
1031
  function emptyNeighbourPlan() {
966
1032
  return { extraAttacks: [], byFinding: /* @__PURE__ */ new Map() };
967
1033
  }
@@ -1171,7 +1237,7 @@ async function reportCommand(scanId, opts) {
1171
1237
  }
1172
1238
  if (res.status === 404) {
1173
1239
  await res.text().catch(() => void 0);
1174
- console.error(`Scan "${scanId}" not found.`);
1240
+ console.error(scanNotFoundMessage(scanId));
1175
1241
  process.exitCode = 2;
1176
1242
  return;
1177
1243
  }
@@ -1693,6 +1759,28 @@ function gradeColor(grade) {
1693
1759
  }
1694
1760
  }
1695
1761
 
1762
+ // src/lib/private-target.ts
1763
+ function refusal(url) {
1764
+ return `${redactTargetUrl(url)} is a local or private address. Shield refuses those unless you allow it:
1765
+ - add "allowPrivateUrls": true to the "endpoint" block of shield.config.json, or
1766
+ - pass --allow-private-urls to \`shield-llm scan\` or \`shield-llm retest\` for one run.`;
1767
+ }
1768
+ function privateTargetProblem(endpoint) {
1769
+ if (endpoint.allowPrivateUrls || !isPrivateUrl(endpoint.url)) return null;
1770
+ return refusal(endpoint.url);
1771
+ }
1772
+ async function resolvedPrivateTargetProblem(endpoint, assertPublic = assertPublicHost) {
1773
+ if (endpoint.allowPrivateUrls) return null;
1774
+ if (isPrivateUrl(endpoint.url)) return refusal(endpoint.url);
1775
+ try {
1776
+ await assertPublic(endpoint.url);
1777
+ return null;
1778
+ } catch (error) {
1779
+ const message = error instanceof Error ? error.message : "";
1780
+ return /private\/internal address/.test(message) ? refusal(endpoint.url) : null;
1781
+ }
1782
+ }
1783
+
1696
1784
  // src/commands/retest.ts
1697
1785
  function findingLabel(finding) {
1698
1786
  return `${finding.name} (${finding.severity})`;
@@ -1734,7 +1822,7 @@ async function retestCommand(scanId, opts) {
1734
1822
  }
1735
1823
  if (res.status === 404) {
1736
1824
  await res.text().catch(() => void 0);
1737
- console.error(`Scan "${scanId}" not found.`);
1825
+ console.error(scanNotFoundMessage(scanId));
1738
1826
  setExitCode(2);
1739
1827
  return;
1740
1828
  }
@@ -1780,6 +1868,12 @@ async function retestCommand(scanId, opts) {
1780
1868
  const endpoint = buildEndpointOverride(opts);
1781
1869
  if (endpoint) cliOverrides.endpoint = endpoint;
1782
1870
  const config = loadConfig({ configPath: opts.config, cliOverrides });
1871
+ const privateProblem = await resolvedPrivateTargetProblem(config.endpoint);
1872
+ if (privateProblem) {
1873
+ console.error(privateProblem);
1874
+ setExitCode(2);
1875
+ return;
1876
+ }
1783
1877
  const systemPrompt = loadSystemPrompt(config);
1784
1878
  const endpointHost = safeHostname(config.endpoint?.url);
1785
1879
  const shownTarget = config.endpoint?.url ? redactTargetUrl(config.endpoint.url) : void 0;
@@ -1905,31 +1999,48 @@ async function retestCommand(scanId, opts) {
1905
1999
  let verify = null;
1906
2000
  let verifyError = null;
1907
2001
  if (outcome.verifications.length > 0) {
1908
- try {
1909
- const res = await fetch(
1910
- `${credentials.apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}/verify`,
1911
- {
1912
- method: "POST",
1913
- headers: {
1914
- "Content-Type": "application/json",
1915
- Authorization: `Bearer ${credentials.apiKey}`
1916
- },
1917
- body: JSON.stringify({
1918
- targetUrl: shownTarget,
1919
- results: outcome.verifications
1920
- })
2002
+ let suspended = false;
2003
+ const sent = await postVerifyBatches(
2004
+ outcome.verifications,
2005
+ async (batch) => {
2006
+ try {
2007
+ const res = await fetch(
2008
+ `${credentials.apiUrl}/api/cli/reports/${encodeURIComponent(scanId)}/verify`,
2009
+ {
2010
+ method: "POST",
2011
+ headers: {
2012
+ "Content-Type": "application/json",
2013
+ Authorization: `Bearer ${credentials.apiKey}`
2014
+ },
2015
+ body: JSON.stringify({
2016
+ targetUrl: shownTarget,
2017
+ results: batch
2018
+ })
2019
+ }
2020
+ );
2021
+ if (await reportIfSuspended(res, credentials.apiUrl)) {
2022
+ suspended = true;
2023
+ return { ok: false, error: "account suspended" };
2024
+ }
2025
+ if (!res.ok) {
2026
+ const body = await res.text().catch(() => "");
2027
+ return {
2028
+ ok: false,
2029
+ error: `HTTP ${res.status}: ${body.slice(0, 200)}`
2030
+ };
2031
+ }
2032
+ return { ok: true, response: await res.json() };
2033
+ } catch (err) {
2034
+ return {
2035
+ ok: false,
2036
+ error: err instanceof Error ? err.message : "Unknown error"
2037
+ };
1921
2038
  }
1922
- );
1923
- if (await reportIfSuspended(res, credentials.apiUrl)) return;
1924
- if (!res.ok) {
1925
- const body = await res.text().catch(() => "");
1926
- verifyError = `HTTP ${res.status}: ${body.slice(0, 200)}`;
1927
- } else {
1928
- verify = await res.json();
1929
2039
  }
1930
- } catch (err) {
1931
- verifyError = err instanceof Error ? err.message : "Unknown error";
1932
- }
2040
+ );
2041
+ if (suspended) return;
2042
+ verify = sent.response;
2043
+ verifyError = sent.error;
1933
2044
  }
1934
2045
  const fixed = outcome.verifications.filter((v) => !v.vulnerable);
1935
2046
  const stillVulnerable = outcome.verifications.filter((v) => v.vulnerable);
@@ -2101,7 +2212,7 @@ async function postSupplementBatch(credentials, scanId, body) {
2101
2212
  if (res.status === 401) {
2102
2213
  message = "API key is invalid or revoked. Run `shield-llm login` to re-authenticate.";
2103
2214
  } else if (res.status === 404) {
2104
- message = `Scan "${scanId}" not found, or not completed, in your account.`;
2215
+ message = `Scan "${scanId}" not found, or not completed, in your account.${shortIdHint(scanId)}`;
2105
2216
  }
2106
2217
  throw new SupplementUploadError(
2107
2218
  `HTTP ${res.status}: ${message}`,
@@ -3010,7 +3121,15 @@ function alignOutputExtension(file, format) {
3010
3121
  }
3011
3122
 
3012
3123
  // src/lib/incomplete-scan.ts
3013
- function incompleteScan(report, judged, total) {
3124
+ function judgeUnavailableReason(report, judged, budgetReason) {
3125
+ const notJudged = report.judgeRecovery?.notJudged ?? 0;
3126
+ const max = report.judgeRecovery?.maxUnjudgedPercent;
3127
+ const answered = judged + notJudged;
3128
+ const share = answered > 0 ? Math.round(notJudged / answered * 100) : 0;
3129
+ const head = `${JUDGE_OUTAGE_REASON_PREFIX} for ${notJudged} of ${answered} answered attacks (${share}%), above the ${max}% limit (--max-unjudged), so nothing was scored`;
3130
+ return budgetReason ? `${head}: ${budgetReason}. Re-run the same command after 00:00 UTC or once the budget is raised: the ${judged} judged attack(s) resume from the checkpoint.` : `${head}. Re-run the same command later: the ${judged} judged attack(s) resume from the checkpoint.`;
3131
+ }
3132
+ function incompleteScan(report, judged, total, budgetReason = null) {
3014
3133
  const resume = `Re-run the same command: the ${judged} judged attack(s) resume from the checkpoint.`;
3015
3134
  switch (report.stopReason) {
3016
3135
  case "auth":
@@ -3028,16 +3147,11 @@ function incompleteScan(report, judged, total) {
3028
3147
  reason: `The scan stopped after repeated failed requests to the target, ${judged}/${total} attacks judged \u2014 the target is failing or unreachable. ${resume}`,
3029
3148
  exitCode: 3
3030
3149
  };
3031
- case "judge_unavailable": {
3032
- const notJudged = report.judgeRecovery?.notJudged ?? 0;
3033
- const max = report.judgeRecovery?.maxUnjudgedPercent;
3034
- const answered = judged + notJudged;
3035
- const share = answered > 0 ? Math.round(notJudged / answered * 100) : 0;
3150
+ case "judge_unavailable":
3036
3151
  return {
3037
- reason: `${JUDGE_OUTAGE_REASON_PREFIX} for ${notJudged} of ${answered} answered attacks (${share}%), above the ${max}% limit (--max-unjudged), so nothing was scored. Re-run the same command later: the ${judged} judged attack(s) resume from the checkpoint.`,
3152
+ reason: judgeUnavailableReason(report, judged, budgetReason),
3038
3153
  exitCode: 3
3039
3154
  };
3040
- }
3041
3155
  case "not_executed": {
3042
3156
  const coverage = report.runCoverage;
3043
3157
  const notExecuted = coverage?.notExecuted ?? 0;
@@ -3059,37 +3173,112 @@ function incompleteScan(report, judged, total) {
3059
3173
  }
3060
3174
 
3061
3175
  // src/commands/scan.ts
3062
- function buildUploadVulnerabilities(attacks) {
3063
- return scoredAttacks(attacks).map((a) => ({
3064
- // attackId lets the backend validate against its known catalogue + the
3065
- // user's custom tests, rejecting fabricated vulnerability rows.
3066
- attackId: a.id,
3067
- name: a.name,
3068
- severity: a.severity,
3069
- vulnerabilityType: a.id,
3070
- vulnerable: a.vulnerable,
3071
- description: a.name,
3072
- evidence: a.prompt && a.response ? JSON.stringify({
3073
- prompt: a.prompt,
3074
- response: excerpt(a.response, 2e3)
3075
- }) : a.response ? JSON.stringify({
3076
- prompt: "",
3077
- response: excerpt(a.response, 2e3)
3078
- }) : void 0,
3079
- status: a.vulnerable ? "DETECTED" : "PASSED",
3080
- evaluationMethod: a.llmEvaluation?.evaluationMethod,
3081
- // The judge that produced this verdict (backend meta.judgeId): the server
3082
- // composes the scan's judgeVersion from these instead of guessing.
3083
- judgeId: a.llmEvaluation?.judgeId,
3084
- confidence: a.llmEvaluation?.confidence,
3085
- reasoning: a.llmEvaluation?.reasoning,
3086
- captureStatus: a.captureStatus ?? "captured",
3087
- // Problems outside this attack's target, as the server's judge bounded
3088
- // them. Absent when there are none (and from an older server).
3089
- ...a.llmEvaluation?.incidental?.length && {
3090
- incidentalFindings: a.llmEvaluation.incidental
3176
+ function buildUploadVulnerabilities(attacks, responseMax = {
3177
+ detected: 2e3,
3178
+ passed: 2e3
3179
+ }) {
3180
+ return scoredAttacks(attacks).map((a) => {
3181
+ const keep = a.vulnerable ? responseMax.detected : responseMax.passed;
3182
+ return {
3183
+ // attackId lets the backend validate against its known catalogue + the
3184
+ // user's custom tests, rejecting fabricated vulnerability rows.
3185
+ attackId: a.id,
3186
+ name: a.name,
3187
+ severity: a.severity,
3188
+ vulnerabilityType: a.id,
3189
+ vulnerable: a.vulnerable,
3190
+ description: a.name,
3191
+ evidence: a.prompt && a.response ? JSON.stringify({
3192
+ prompt: a.prompt,
3193
+ response: excerpt(a.response, keep)
3194
+ }) : a.response ? JSON.stringify({
3195
+ prompt: "",
3196
+ response: excerpt(a.response, keep)
3197
+ }) : void 0,
3198
+ status: a.vulnerable ? "DETECTED" : "PASSED",
3199
+ evaluationMethod: a.llmEvaluation?.evaluationMethod,
3200
+ // The judge that produced this verdict (backend meta.judgeId): the server
3201
+ // composes the scan's judgeVersion from these instead of guessing.
3202
+ judgeId: a.llmEvaluation?.judgeId,
3203
+ confidence: a.llmEvaluation?.confidence,
3204
+ reasoning: a.llmEvaluation?.reasoning,
3205
+ captureStatus: a.captureStatus ?? "captured",
3206
+ // Problems outside this attack's target, as the server's judge bounded
3207
+ // them. Absent when there are none (and from an older server).
3208
+ ...a.llmEvaluation?.incidental?.length && {
3209
+ incidentalFindings: a.llmEvaluation.incidental
3210
+ }
3211
+ };
3212
+ });
3213
+ }
3214
+ function buildUploadAttackErrors(attacks) {
3215
+ const summary = summarizeAttackErrors(attacks, MAX_ATTACK_ERROR_WIRE_ITEMS);
3216
+ return summary ? { items: summary.items, complete: true } : void 0;
3217
+ }
3218
+ var UPLOAD_BYTE_BUDGET = 9.5 * 1024 * 1024;
3219
+ var EVIDENCE_STEPS = [
3220
+ { detected: 2e3, passed: 2e3 },
3221
+ { detected: 2e3, passed: 200 },
3222
+ { detected: 1e3, passed: 200 },
3223
+ { detected: 500, passed: 200 },
3224
+ { detected: 200, passed: 200 }
3225
+ ];
3226
+ function buildUploadPayload(report, scanId, attackPackVersion) {
3227
+ const testsRun = scoredAttacks(report.attacks).length;
3228
+ const attackErrors = buildUploadAttackErrors(report.attacks);
3229
+ let payload;
3230
+ for (const responseMax of EVIDENCE_STEPS) {
3231
+ payload = {
3232
+ scanId,
3233
+ targetUrl: report.target,
3234
+ chatbotType: "api",
3235
+ summary: `CLI scan \u2014 ${report.config.preset} preset \u2014 ${testsRun}/${report.config.totalAttacks} tests`,
3236
+ testsRun,
3237
+ testsTotal: report.config.totalAttacks,
3238
+ durationMs: report.durationMs,
3239
+ preset: report.config.preset,
3240
+ ...attackPackVersion && { attackPackVersion },
3241
+ ...attackErrors && { attackErrors },
3242
+ vulnerabilities: buildUploadVulnerabilities(report.attacks, responseMax)
3243
+ };
3244
+ if (Buffer.byteLength(JSON.stringify(payload)) <= UPLOAD_BYTE_BUDGET) break;
3245
+ }
3246
+ return payload;
3247
+ }
3248
+ var BUSY_TRIES = 6;
3249
+ var BUSY_MIN_TOTAL_MS = 13e4;
3250
+ var BUSY_HARD_TRIES = 12;
3251
+ var BUSY_MAX_WAIT_MS = 12e4;
3252
+ var BUSY_DEFAULT_WAIT_MS = 3e4;
3253
+ async function postWithBusyRetry(post, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), random = Math.random) {
3254
+ let res = await post();
3255
+ let waited = 0;
3256
+ for (let tries = 1; res.status === 503 && tries < BUSY_HARD_TRIES && (tries < BUSY_TRIES || waited < BUSY_MIN_TOTAL_MS); tries += 1) {
3257
+ const after = Number(res.headers.get("retry-after"));
3258
+ const base = Number.isFinite(after) && after > 0 ? after * 1e3 : BUSY_DEFAULT_WAIT_MS;
3259
+ const wait = Math.min(Math.round(base * (0.5 + random())), BUSY_MAX_WAIT_MS);
3260
+ await res.text().catch(() => void 0);
3261
+ await sleep2(wait);
3262
+ waited += wait;
3263
+ res = await post();
3264
+ }
3265
+ return res;
3266
+ }
3267
+ function slowUploadMessage(status) {
3268
+ if (status !== 504) return null;
3269
+ return "The upload took longer than the server allows (120 s) to arrive. Check the network connection between this machine and the server, then run the same command again: the scan resumes from its checkpoint.";
3270
+ }
3271
+ function refusedLongErrorList(status, body) {
3272
+ return status === 400 && body.includes("attackErrors");
3273
+ }
3274
+ function withLegacyErrorList(payload) {
3275
+ if (!payload.attackErrors) return payload;
3276
+ return {
3277
+ ...payload,
3278
+ attackErrors: {
3279
+ items: payload.attackErrors.items.slice(0, MAX_ATTACK_ERROR_ITEMS)
3091
3280
  }
3092
- }));
3281
+ };
3093
3282
  }
3094
3283
  var INCOMPLETE_CODES = /* @__PURE__ */ new Set(["judge_unavailable", "not_executed"]);
3095
3284
  var NOT_STORED_CODE = "no_verdict";
@@ -3103,12 +3292,12 @@ function serverRefusal(status, body) {
3103
3292
  }
3104
3293
  }
3105
3294
  function incompleteRejection(status, body) {
3106
- const refusal = serverRefusal(status, body);
3107
- return refusal && INCOMPLETE_CODES.has(refusal.code) ? refusal.reason : null;
3295
+ const refusal2 = serverRefusal(status, body);
3296
+ return refusal2 && INCOMPLETE_CODES.has(refusal2.code) ? refusal2.reason : null;
3108
3297
  }
3109
3298
  function notStoredRejection(status, body) {
3110
- const refusal = serverRefusal(status, body);
3111
- return refusal?.code === NOT_STORED_CODE ? refusal.reason : null;
3299
+ const refusal2 = serverRefusal(status, body);
3300
+ return refusal2?.code === NOT_STORED_CODE ? refusal2.reason : null;
3112
3301
  }
3113
3302
  function printableServerText(text) {
3114
3303
  return text.replace(/[\r\n\t]+/g, " ").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").slice(0, 300);
@@ -3118,32 +3307,22 @@ var IncompleteRejection = class extends Error {
3118
3307
  var NotStoredRejection = class extends Error {
3119
3308
  };
3120
3309
  async function uploadReportToBackend(report, credentials, scanId, attackPackVersion) {
3121
- const vulnerabilities = buildUploadVulnerabilities(report.attacks);
3122
- const testsRun = scoredAttacks(report.attacks).length;
3123
- const attackErrorSummary = summarizeAttackErrors(report.attacks);
3124
- const payload = {
3125
- scanId,
3126
- targetUrl: report.target,
3127
- chatbotType: "api",
3128
- summary: `CLI scan \u2014 ${report.config.preset} preset \u2014 ${testsRun}/${report.config.totalAttacks} tests`,
3129
- testsRun,
3130
- testsTotal: report.config.totalAttacks,
3131
- durationMs: report.durationMs,
3132
- preset: report.config.preset,
3133
- ...attackPackVersion && { attackPackVersion },
3134
- ...attackErrorSummary && {
3135
- attackErrors: { items: attackErrorSummary.items }
3136
- },
3137
- vulnerabilities
3138
- };
3139
- const res = await fetch(`${credentials.apiUrl}/api/cli/reports`, {
3310
+ const payload = buildUploadPayload(report, scanId, attackPackVersion);
3311
+ const post = (body) => fetch(`${credentials.apiUrl}/api/cli/reports`, {
3140
3312
  method: "POST",
3141
3313
  headers: {
3142
3314
  "Content-Type": "application/json",
3143
3315
  Authorization: `Bearer ${credentials.apiKey}`
3144
3316
  },
3145
- body: JSON.stringify(payload)
3317
+ body: JSON.stringify(body)
3146
3318
  });
3319
+ let res = await postWithBusyRetry(() => post(payload));
3320
+ if (res.status === 400) {
3321
+ const refusal2 = await res.clone().text().catch(() => "");
3322
+ if (refusedLongErrorList(res.status, refusal2)) {
3323
+ res = await postWithBusyRetry(() => post(withLegacyErrorList(payload)));
3324
+ }
3325
+ }
3147
3326
  if (!res.ok) {
3148
3327
  if (await isAccountSuspended(res)) {
3149
3328
  await res.text().catch(() => void 0);
@@ -3154,6 +3333,8 @@ async function uploadReportToBackend(report, credentials, scanId, attackPackVers
3154
3333
  if (incomplete) throw new IncompleteRejection(incomplete);
3155
3334
  const notStored = notStoredRejection(res.status, body);
3156
3335
  if (notStored) throw new NotStoredRejection(notStored);
3336
+ const slow = slowUploadMessage(res.status);
3337
+ if (slow) throw new Error(slow);
3157
3338
  throw new Error(
3158
3339
  `HTTP ${res.status}: ${printableServerText(body.slice(0, 200))}`
3159
3340
  );
@@ -3218,8 +3399,9 @@ function resolveMutateSelection(value) {
3218
3399
  const unknown = [];
3219
3400
  for (const id of ids) {
3220
3401
  const m = getMutator(id);
3221
- if (m) mutators.push(m);
3222
- else unknown.push(id);
3402
+ if (m) {
3403
+ if (!mutators.includes(m)) mutators.push(m);
3404
+ } else unknown.push(id);
3223
3405
  }
3224
3406
  return { mutators, unknown };
3225
3407
  }
@@ -3404,6 +3586,12 @@ async function scanCommand(opts) {
3404
3586
  }
3405
3587
  }
3406
3588
  const target = buildTargetConfig(config);
3589
+ const privateProblem = await resolvedPrivateTargetProblem(target);
3590
+ if (privateProblem) {
3591
+ console.error(privateProblem);
3592
+ setExitCode(2);
3593
+ return;
3594
+ }
3407
3595
  const isolation = checkSessionIsolation(target);
3408
3596
  if (!isolation.isolated) console.warn(`
3409
3597
  \u26A0\uFE0F ${isolation.warning}
@@ -3486,7 +3674,12 @@ async function scanCommand(opts) {
3486
3674
  const attempted = report.attacks.length;
3487
3675
  const evaluated = scoredAttacks(report.attacks).length;
3488
3676
  const nothingRan = report.stopReason === "not_executed" && evaluated === 0;
3489
- const incomplete = nothingRan ? null : incompleteScan(report, evaluated, attempted);
3677
+ const incomplete = nothingRan ? null : incompleteScan(
3678
+ report,
3679
+ evaluated,
3680
+ attempted,
3681
+ shieldBudgetReason(report)
3682
+ );
3490
3683
  if (incomplete) {
3491
3684
  await reportScanFailure(credentials, reservedScanId, incomplete.reason);
3492
3685
  scanFinalized = true;
@@ -3726,6 +3919,12 @@ async function testConnectionCommand(opts) {
3726
3919
  return;
3727
3920
  }
3728
3921
  const target = buildTargetConfig(config);
3922
+ const privateProblem = await resolvedPrivateTargetProblem(target);
3923
+ if (privateProblem) {
3924
+ console.error(privateProblem);
3925
+ setExitCode(2);
3926
+ return;
3927
+ }
3729
3928
  const systemPrompt = loadSystemPrompt(config);
3730
3929
  const message = opts.message ?? DEFAULT_MESSAGE;
3731
3930
  console.log(`Target: ${redactTargetUrl(target.url)}`);
@@ -3931,7 +4130,9 @@ async function testsCommand(opts) {
3931
4130
  if (opts.remote) {
3932
4131
  const stored = loadCredentials();
3933
4132
  if (!stored) {
3934
- console.error("Not logged in. Run: shield-llm login --key <your-key>\n");
4133
+ console.error(
4134
+ "Not logged in. Run: shield-llm login --key <api-key> --api-url <your-instance-url>\n"
4135
+ );
3935
4136
  setExitCode(2);
3936
4137
  return;
3937
4138
  }
@@ -4003,6 +4204,9 @@ function validateCommand(opts) {
4003
4204
  if (config.customTests?.length) {
4004
4205
  console.log(` Custom tests: ${config.customTests.length}`);
4005
4206
  }
4207
+ const privateProblem = privateTargetProblem(config.endpoint);
4208
+ if (privateProblem) console.warn(`
4209
+ \u26A0\uFE0F ${privateProblem}`);
4006
4210
  setExitCode(0);
4007
4211
  return;
4008
4212
  } catch (error) {
@@ -6063,7 +6267,7 @@ async function fetchStoredScan(apiUrl, apiKey, scanId) {
6063
6267
  "API key invalid or revoked. Run `shield-llm login` to re-authenticate."
6064
6268
  );
6065
6269
  }
6066
- if (res.status === 404) throw new Error(`Scan "${scanId}" not found.`);
6270
+ if (res.status === 404) throw new Error(scanNotFoundMessage(scanId));
6067
6271
  throw new Error(`The dashboard returned HTTP ${res.status} for the scan.`);
6068
6272
  }
6069
6273
  const scan = await res.json();
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  formatSarif,
9
9
  loadConfig,
10
10
  loadSystemPrompt
11
- } from "./chunk-O2K6SD5X.js";
11
+ } from "./chunk-24WGTB3E.js";
12
12
  export {
13
13
  ConfigError,
14
14
  ConfigSchema,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shield-llm",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "AI chatbot security scanner — automated red teaming for LLMs",
5
5
  "type": "module",
6
6
  "publishConfig": {