shield-llm 0.5.4 → 0.6.1

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.
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __cjs_createRequire } from "module"; import { fileURLToPath as __cjs_fileURLToPath } from "url"; import { dirname as __cjs_dirname } from "path"; const __filename = __cjs_fileURLToPath(import.meta.url); const __dirname = __cjs_dirname(__filename); const require = __cjs_createRequire(import.meta.url);
2
2
 
3
3
  // package.json
4
- var version = "0.5.4";
4
+ var version = "0.6.1";
5
5
 
6
6
  // src/config/schema.ts
7
7
  import { z as z2 } from "zod";
@@ -304,8 +304,12 @@ var RATE_LIMIT_PATTERNS = [
304
304
  { pattern: /vous avez atteint la limite de messages/i, platform: "ChatGPT" },
305
305
  { pattern: /you[''’]ve reached the? message limit/i, platform: "ChatGPT" },
306
306
  {
307
- pattern: /too many requests[.\s]*please (slow down|try again)/i,
308
- platform: "ChatGPT"
307
+ // "Too many requests, please slow down." — the standard HTTP 429-style body,
308
+ // emitted by many backends (incl. WordPress chat plugins) sometimes with a
309
+ // NON-standard status like 500. The separator class includes the comma that
310
+ // the old /too many requests[.\s]*please/ form missed (the anao.io incident).
311
+ pattern: /\btoo many requests\b[\s,.:;-]*(please\s+)?(slow down|try again|retry|wait|come back|later)/i,
312
+ platform: "generic"
309
313
  },
310
314
  // Claude.ai (FR + EN)
311
315
  { pattern: /usage limit reached/i, platform: "Claude.ai" },
@@ -316,7 +320,12 @@ var RATE_LIMIT_PATTERNS = [
316
320
  },
317
321
  // Generic rate-limit banners (must include an action word to avoid false positives)
318
322
  {
319
- pattern: /\brate limit(ed)?\b.*\b(wait|try again|later|exceeded)\b/i,
323
+ pattern: /\brate limit(ed)?\b.*\b(wait|try again|later|exceeded|slow down|reached)\b/i,
324
+ platform: "generic"
325
+ },
326
+ {
327
+ // Quota / usage-cap exhaustion phrased without "rate limit".
328
+ pattern: /\b(quota|usage cap)\b.*\b(exceeded|reached|exhausted|hit)\b/i,
320
329
  platform: "generic"
321
330
  },
322
331
  {
@@ -334,6 +343,21 @@ function detectRateLimit(text) {
334
343
  return null;
335
344
  }
336
345
 
346
+ // ../../packages/shared/src/unicode.ts
347
+ function replaceLoneSurrogates(input) {
348
+ return input.replace(/[\uD800-\uDFFF]/g, (ch, index, str) => {
349
+ const code = ch.charCodeAt(0);
350
+ if (code <= 56319) {
351
+ const next = str.charCodeAt(index + 1);
352
+ if (next >= 56320 && next <= 57343) return ch;
353
+ } else {
354
+ const prev = str.charCodeAt(index - 1);
355
+ if (prev >= 55296 && prev <= 56319) return ch;
356
+ }
357
+ return "\uFFFD";
358
+ });
359
+ }
360
+
337
361
  // ../../packages/shared/src/attack-error.ts
338
362
  var MAX_ATTACK_ERROR_ITEMS = 50;
339
363
  function categorizeAttackError(error, rateLimited) {
@@ -5055,10 +5079,24 @@ function resolveEnvVar(value) {
5055
5079
  }
5056
5080
 
5057
5081
  // ../../packages/scanner-core/src/http-target-client.ts
5082
+ function sanitizeWireValue(value) {
5083
+ if (typeof value === "string") return replaceLoneSurrogates(value);
5084
+ if (Array.isArray(value)) return value.map(sanitizeWireValue);
5085
+ if (value && typeof value === "object") {
5086
+ return Object.fromEntries(
5087
+ Object.entries(value).map(([k, v]) => [
5088
+ k,
5089
+ sanitizeWireValue(v)
5090
+ ])
5091
+ );
5092
+ }
5093
+ return value;
5094
+ }
5058
5095
  function encodeRequestBody(body, encoding) {
5096
+ const safe = sanitizeWireValue(body);
5059
5097
  if (encoding === "form") {
5060
5098
  const params = new URLSearchParams();
5061
- for (const [k, v] of Object.entries(body)) {
5099
+ for (const [k, v] of Object.entries(safe)) {
5062
5100
  params.append(k, typeof v === "string" ? v : JSON.stringify(v));
5063
5101
  }
5064
5102
  return {
@@ -5068,12 +5106,12 @@ function encodeRequestBody(body, encoding) {
5068
5106
  }
5069
5107
  if (encoding === "multipart") {
5070
5108
  const form = new FormData();
5071
- for (const [k, v] of Object.entries(body)) {
5109
+ for (const [k, v] of Object.entries(safe)) {
5072
5110
  form.append(k, typeof v === "string" ? v : JSON.stringify(v));
5073
5111
  }
5074
5112
  return { body: form, contentType: null };
5075
5113
  }
5076
- return { body: JSON.stringify(body), contentType: "application/json" };
5114
+ return { body: JSON.stringify(safe), contentType: "application/json" };
5077
5115
  }
5078
5116
  var PRIVATE_HOSTNAME_PATTERNS = [
5079
5117
  /^localhost$/i,
@@ -5506,6 +5544,11 @@ async function resolveAuth(auth, timeoutMs = 3e4, allowPrivateUrls = false) {
5506
5544
  return { type: "bearer", token: "" };
5507
5545
  }
5508
5546
  }
5547
+ function retryAfterFromHeader(value) {
5548
+ if (!value) return null;
5549
+ const sec = parseInt(value, 10);
5550
+ return Number.isNaN(sec) ? null : sec;
5551
+ }
5509
5552
  async function fetchWithTimeout(url, init, timeoutMs, responseField, allowPrivateUrls = false) {
5510
5553
  if (!allowPrivateUrls) {
5511
5554
  await assertPublicHost(url);
@@ -5530,16 +5573,24 @@ async function fetchWithTimeout(url, init, timeoutMs, responseField, allowPrivat
5530
5573
  );
5531
5574
  }
5532
5575
  if (response.status === 429) {
5533
- const retryAfter = response.headers.get("retry-after");
5534
- const retryAfterSec = retryAfter ? parseInt(retryAfter, 10) : null;
5576
+ const retryAfterSec = retryAfterFromHeader(
5577
+ response.headers.get("retry-after")
5578
+ );
5535
5579
  const body2 = await response.text().catch(() => "");
5536
5580
  throw new RateLimitError(
5537
5581
  `Rate limited (HTTP 429)${retryAfterSec ? ` \u2014 retry after ${retryAfterSec}s` : ""}${body2 ? `: ${body2.slice(0, 500)}` : ""}`,
5538
- Number.isNaN(retryAfterSec) ? null : retryAfterSec
5582
+ retryAfterSec
5539
5583
  );
5540
5584
  }
5541
5585
  if (!response.ok) {
5542
5586
  const body2 = await response.text().catch(() => "");
5587
+ const throttle = detectRateLimit(body2);
5588
+ if (throttle) {
5589
+ throw new RateLimitError(
5590
+ `Rate limited (soft, HTTP ${response.status} \u2014 ${throttle})${body2 ? `: ${body2.slice(0, 500)}` : ""}`,
5591
+ retryAfterFromHeader(response.headers.get("retry-after"))
5592
+ );
5593
+ }
5543
5594
  throw new HttpTargetError(
5544
5595
  `HTTP ${response.status} ${response.statusText}${body2 ? `: ${body2.slice(0, 500)}` : ""}`,
5545
5596
  response.status
@@ -5765,6 +5816,18 @@ var Scanner = class {
5765
5816
  this.aimdLimit = 1;
5766
5817
  this.aimdSuccessStreak = 0;
5767
5818
  this.inConcurrentPhase = false;
5819
+ // Adaptive-pacing state (the second AIMD lever — the inter-request delay).
5820
+ // `currentDelayMs` rises multiplicatively on a throttle and decays additively
5821
+ // on success; `throttleFloorStreak` counts throttles suffered while already at
5822
+ // the floor (concurrency 1 + maxDelayMs) to tell a transient slow-down apart
5823
+ // from a hard quota/ban. Both reset at the start of run().
5824
+ this.currentDelayMs = 0;
5825
+ this.throttleFloorStreak = 0;
5826
+ // Pool-global not-before floor (ms epoch). Every send path waits until this
5827
+ // before issuing a turn, so a single observed Retry-After / throttle backoff
5828
+ // quiets the WHOLE worker pool — not just the worker that hit it. 0 = no pause
5829
+ // (the default and the no-throttle hot path, so it's a no-op when idle).
5830
+ this.pauseUntil = 0;
5768
5831
  this.targetClient = createTargetClient(
5769
5832
  options.target,
5770
5833
  options.systemPrompt
@@ -5784,7 +5847,9 @@ var Scanner = class {
5784
5847
  includeCrescendo: options.includeCrescendo ?? false,
5785
5848
  maxRateLimitRetries: options.maxRateLimitRetries ?? 3,
5786
5849
  rateLimitBackoffMs: options.rateLimitBackoffMs ?? 1e3,
5787
- rateLimitMaxBackoffMs: options.rateLimitMaxBackoffMs ?? 3e4
5850
+ rateLimitMaxBackoffMs: options.rateLimitMaxBackoffMs ?? 3e4,
5851
+ maxDelayMs: options.maxDelayMs ?? 5e3,
5852
+ maxFloorThrottles: options.maxFloorThrottles ?? 3
5788
5853
  };
5789
5854
  this.onEvent = onEvent;
5790
5855
  }
@@ -5838,6 +5903,9 @@ var Scanner = class {
5838
5903
  let consecutiveFailures = 0;
5839
5904
  let attackIndex = 0;
5840
5905
  let rateLimited = false;
5906
+ this.currentDelayMs = this.options.delayMs;
5907
+ this.throttleFloorStreak = 0;
5908
+ this.pauseUntil = 0;
5841
5909
  const singleResults = new Array(
5842
5910
  attacks.length
5843
5911
  );
@@ -5888,23 +5956,23 @@ var Scanner = class {
5888
5956
  total: totalAttacks
5889
5957
  });
5890
5958
  void (async () => {
5891
- if (this.options.delayMs > 0) await sleep(this.options.delayMs);
5959
+ if (this.currentDelayMs > 0) await sleep(this.currentDelayMs);
5892
5960
  const result = await this.executeSingleTurnAttack(attack);
5893
5961
  singleResults[idx] = result;
5894
5962
  await store?.record(result);
5895
5963
  if (result.rateLimited) {
5896
- rateLimited = true;
5897
- this.emit({
5898
- type: "scan:rate_limited",
5899
- attackIndex: idx,
5900
- total: totalAttacks,
5901
- retryAfterSec: parseRetryAfterSec(result.error)
5902
- });
5964
+ if (this.handleThrottle(
5965
+ idx,
5966
+ totalAttacks,
5967
+ parseRetryAfterSec(result.error)
5968
+ )) {
5969
+ rateLimited = true;
5970
+ }
5903
5971
  } else if (result.error) {
5904
5972
  if (!result.payloadRejected) consecutiveFailures++;
5905
5973
  } else {
5906
5974
  consecutiveFailures = 0;
5907
- this.aimdIncrease();
5975
+ this.handleSuccess();
5908
5976
  }
5909
5977
  this.emit({
5910
5978
  type: "attack:complete",
@@ -5928,6 +5996,37 @@ var Scanner = class {
5928
5996
  pump();
5929
5997
  });
5930
5998
  this.inConcurrentPhase = false;
5999
+ let madeProgress = !stop();
6000
+ while (madeProgress && !stop()) {
6001
+ madeProgress = false;
6002
+ for (let i = 0; i < attacks.length; i++) {
6003
+ if (stop()) break;
6004
+ const prior = singleResults[i];
6005
+ if (!prior || !prior.rateLimited) continue;
6006
+ if (this.currentDelayMs > 0) await sleep(this.currentDelayMs);
6007
+ const retry = await this.executeSingleTurnAttack(attacks[i]);
6008
+ singleResults[i] = retry;
6009
+ await store?.record(retry);
6010
+ if (retry.rateLimited) {
6011
+ if (this.handleThrottle(
6012
+ i,
6013
+ totalAttacks,
6014
+ parseRetryAfterSec(retry.error)
6015
+ )) {
6016
+ rateLimited = true;
6017
+ }
6018
+ } else {
6019
+ if (!retry.error) this.handleSuccess();
6020
+ madeProgress = true;
6021
+ }
6022
+ this.emit({
6023
+ type: "attack:complete",
6024
+ result: retry,
6025
+ index: i,
6026
+ total: totalAttacks
6027
+ });
6028
+ }
6029
+ }
5931
6030
  for (let i = 0; i < attacks.length; i++) {
5932
6031
  if (singleResults[i] === void 0) {
5933
6032
  const skip = this.createSkippedResult(
@@ -5989,17 +6088,14 @@ var Scanner = class {
5989
6088
  results.push(result);
5990
6089
  await store?.record(result);
5991
6090
  if (result.rateLimited) {
5992
- rateLimited = true;
5993
- this.emit({
5994
- type: "scan:rate_limited",
5995
- attackIndex,
5996
- total: totalAttacks,
5997
- retryAfterSec: null
5998
- });
6091
+ if (this.handleThrottle(attackIndex, totalAttacks, null)) {
6092
+ rateLimited = true;
6093
+ }
5999
6094
  } else if (result.error) {
6000
6095
  if (!result.payloadRejected) consecutiveFailures++;
6001
6096
  } else {
6002
6097
  consecutiveFailures = 0;
6098
+ this.handleSuccess();
6003
6099
  }
6004
6100
  this.emit({
6005
6101
  type: "attack:complete",
@@ -6008,8 +6104,42 @@ var Scanner = class {
6008
6104
  total: totalAttacks
6009
6105
  });
6010
6106
  attackIndex++;
6011
- if (attackIndex < totalAttacks && this.options.delayMs > 0) {
6012
- await sleep(this.options.delayMs);
6107
+ if (attackIndex < totalAttacks && this.currentDelayMs > 0) {
6108
+ await sleep(this.currentDelayMs);
6109
+ }
6110
+ }
6111
+ let mtProgress = !stop();
6112
+ while (mtProgress && !stop()) {
6113
+ mtProgress = false;
6114
+ for (let k = 0; k < crescendoAttacks.length; k++) {
6115
+ if (stop()) break;
6116
+ const at = attacks.length + k;
6117
+ const prior = results[at];
6118
+ if (!prior || !prior.rateLimited || prior.error?.startsWith("Skipped")) {
6119
+ continue;
6120
+ }
6121
+ if (this.currentDelayMs > 0) await sleep(this.currentDelayMs);
6122
+ const retry = await this.executeMultiTurnAttack(crescendoAttacks[k]);
6123
+ results[at] = retry;
6124
+ await store?.record(retry);
6125
+ if (retry.rateLimited) {
6126
+ if (this.handleThrottle(
6127
+ at,
6128
+ totalAttacks,
6129
+ parseRetryAfterSec(retry.error)
6130
+ )) {
6131
+ rateLimited = true;
6132
+ }
6133
+ } else {
6134
+ if (!retry.error) this.handleSuccess();
6135
+ mtProgress = true;
6136
+ }
6137
+ this.emit({
6138
+ type: "attack:complete",
6139
+ result: retry,
6140
+ index: at,
6141
+ total: totalAttacks
6142
+ });
6013
6143
  }
6014
6144
  }
6015
6145
  for (const customTest of customTests) {
@@ -6045,8 +6175,8 @@ var Scanner = class {
6045
6175
  total: totalAttacks
6046
6176
  });
6047
6177
  attackIndex++;
6048
- if (attackIndex < totalAttacks && this.options.delayMs > 0) {
6049
- await sleep(this.options.delayMs);
6178
+ if (attackIndex < totalAttacks && this.currentDelayMs > 0) {
6179
+ await sleep(this.currentDelayMs);
6050
6180
  }
6051
6181
  }
6052
6182
  const score = calculateScore(results);
@@ -6282,6 +6412,10 @@ var Scanner = class {
6282
6412
  async sendTurnWithRetry(session, prompt, attackId) {
6283
6413
  let attempt = 0;
6284
6414
  for (; ; ) {
6415
+ const pause = this.pauseUntil - Date.now();
6416
+ if (pause > 0) {
6417
+ await sleep(pause + Math.floor(Math.random() * PAUSE_JITTER_MS));
6418
+ }
6285
6419
  try {
6286
6420
  return await session.sendTurn(prompt, {
6287
6421
  abortSignal: AbortSignal.timeout(this.options.attackTimeoutMs),
@@ -6301,7 +6435,10 @@ var Scanner = class {
6301
6435
  waitMs,
6302
6436
  reason: error instanceof RateLimitError ? "rate_limited" : "server_error"
6303
6437
  });
6304
- if (error instanceof RateLimitError) this.aimdDecrease();
6438
+ if (error instanceof RateLimitError) {
6439
+ this.aimdDecrease();
6440
+ this.pauseUntil = Math.max(this.pauseUntil, Date.now() + waitMs);
6441
+ }
6305
6442
  await sleep(waitMs);
6306
6443
  }
6307
6444
  }
@@ -6317,7 +6454,11 @@ var Scanner = class {
6317
6454
  if (error instanceof RateLimitError && error.retryAfterSec != null && error.retryAfterSec > 0) {
6318
6455
  return Math.min(error.retryAfterSec * 1e3, cap);
6319
6456
  }
6320
- return Math.min(this.options.rateLimitBackoffMs * 2 ** attempt, cap);
6457
+ const window = Math.min(
6458
+ this.options.rateLimitBackoffMs * 2 ** attempt,
6459
+ cap
6460
+ );
6461
+ return Math.floor(Math.random() * window);
6321
6462
  }
6322
6463
  // ──────────────────────────────────────────────
6323
6464
  // AIMD adaptive concurrency
@@ -6355,6 +6496,68 @@ var Scanner = class {
6355
6496
  }
6356
6497
  }
6357
6498
  // ──────────────────────────────────────────────
6499
+ // Adaptive pacing (second AIMD lever — inter-request delay)
6500
+ // ──────────────────────────────────────────────
6501
+ /** Multiplicative increase of the inter-request delay on a throttle, capped
6502
+ * at maxDelayMs. Uses a 250ms floor so it still slows down when delayMs=0. */
6503
+ inflateDelay() {
6504
+ const base = Math.max(this.options.delayMs, 250);
6505
+ this.currentDelayMs = Math.min(
6506
+ this.options.maxDelayMs,
6507
+ Math.max(base, this.currentDelayMs * 2)
6508
+ );
6509
+ }
6510
+ /** Additive decrease of the delay on a clean success — slow reconvergence
6511
+ * toward the floor (delayMs) so we don't immediately re-trip the limiter. */
6512
+ decayDelay() {
6513
+ if (this.currentDelayMs <= this.options.delayMs) return;
6514
+ const step = Math.max(this.options.delayMs, 200);
6515
+ this.currentDelayMs = Math.max(
6516
+ this.options.delayMs,
6517
+ this.currentDelayMs - step
6518
+ );
6519
+ }
6520
+ /**
6521
+ * Process a throttle (a rate-limited result that survived the per-attack retry
6522
+ * budget). Back the pacer off — halve the concurrency cap AND inflate the
6523
+ * delay — and report whether the scan should HARD-STOP. It stops only when the
6524
+ * pacer is already at the floor (cap 1 + maxDelayMs) and STILL gets throttled
6525
+ * `maxFloorThrottles` times in a row: that is a hard quota/ban, not transient
6526
+ * congestion. Below the floor a throttle just slows the scan and it continues,
6527
+ * so a target that responds to backoff finishes the whole suite.
6528
+ */
6529
+ handleThrottle(attackIndex, total, retryAfterSec) {
6530
+ this.aimdDecrease();
6531
+ this.inflateDelay();
6532
+ const atFloor = this.aimdLimit <= 1 && this.currentDelayMs >= this.options.maxDelayMs;
6533
+ if (atFloor) this.throttleFloorStreak++;
6534
+ const stop = this.throttleFloorStreak >= this.options.maxFloorThrottles;
6535
+ if (stop) {
6536
+ this.emit({
6537
+ type: "scan:rate_limited",
6538
+ attackIndex,
6539
+ total,
6540
+ retryAfterSec
6541
+ });
6542
+ } else {
6543
+ this.emit({
6544
+ type: "scan:throttled",
6545
+ attackIndex,
6546
+ total,
6547
+ delayMs: this.currentDelayMs,
6548
+ atFloor
6549
+ });
6550
+ }
6551
+ return stop;
6552
+ }
6553
+ /** A clean success: reset the at-floor streak and speed the pacer back up
6554
+ * (decay the delay, grow the concurrency cap). */
6555
+ handleSuccess() {
6556
+ this.throttleFloorStreak = 0;
6557
+ this.decayDelay();
6558
+ this.aimdIncrease();
6559
+ }
6560
+ // ──────────────────────────────────────────────
6358
6561
  // Helpers
6359
6562
  // ──────────────────────────────────────────────
6360
6563
  buildEvaluation(evalResult) {
@@ -6388,6 +6591,7 @@ var Scanner = class {
6388
6591
  this.onEvent?.(event);
6389
6592
  }
6390
6593
  };
6594
+ var PAUSE_JITTER_MS = 250;
6391
6595
  function isRetryable(error) {
6392
6596
  if (error instanceof RateLimitError) return true;
6393
6597
  if (error instanceof HttpTargetError) {
@@ -6515,6 +6719,11 @@ var ConfigSchema = z2.object({
6515
6719
  maxRateLimitRetries: z2.number().int().min(0).max(10).optional(),
6516
6720
  rateLimitBackoffMs: z2.number().int().min(0).optional(),
6517
6721
  rateLimitMaxBackoffMs: z2.number().int().min(0).optional(),
6722
+ // Adaptive-pacing knobs. These existed in ScanOptions but were unreachable —
6723
+ // absent from this schema (stripped by Zod) AND from the scan.ts passthrough —
6724
+ // so they always fell back to the scanner defaults (5000 / 3). Now settable.
6725
+ maxDelayMs: z2.number().int().min(0).optional(),
6726
+ maxFloorThrottles: z2.number().int().min(1).optional(),
6518
6727
  thresholds: ThresholdSchema.optional(),
6519
6728
  output: OutputSchema.optional()
6520
6729
  });
@@ -9119,6 +9328,7 @@ function buildMessage(attack) {
9119
9328
 
9120
9329
  export {
9121
9330
  version,
9331
+ replaceLoneSurrogates,
9122
9332
  summarizeAttackErrors,
9123
9333
  deserializeAttack,
9124
9334
  deserializeMultiTurnAttack,
package/dist/cli.js CHANGED
@@ -25,10 +25,11 @@ import {
25
25
  loadSystemPrompt,
26
26
  parseSegmentKey,
27
27
  parseSnapshot,
28
+ replaceLoneSurrogates,
28
29
  resolveOfflinePosition,
29
30
  summarizeAttackErrors,
30
31
  version
31
- } from "./chunk-S2OWXRK6.js";
32
+ } from "./chunk-LGX52ZEL.js";
32
33
 
33
34
  // src/load-env.ts
34
35
  try {
@@ -37,7 +38,7 @@ try {
37
38
  }
38
39
 
39
40
  // src/cli.ts
40
- import { Command, CommanderError } from "commander";
41
+ import { Command, CommanderError, InvalidArgumentError } from "commander";
41
42
 
42
43
  // src/credentials.ts
43
44
  import {
@@ -1227,10 +1228,11 @@ ${text.slice(-TAIL_CHARS)}`;
1227
1228
  function truncateInput(input2) {
1228
1229
  return {
1229
1230
  ...input2,
1230
- response: truncateResponse(input2.response),
1231
+ attackPrompt: replaceLoneSurrogates(input2.attackPrompt),
1232
+ response: replaceLoneSurrogates(truncateResponse(input2.response)),
1231
1233
  turns: input2.turns?.map((t) => ({
1232
- prompt: t.prompt,
1233
- response: truncateResponse(t.response)
1234
+ prompt: replaceLoneSurrogates(t.prompt),
1235
+ response: replaceLoneSurrogates(truncateResponse(t.response))
1234
1236
  }))
1235
1237
  };
1236
1238
  }
@@ -1459,6 +1461,11 @@ function handleEvent(event) {
1459
1461
  `${currentAttackName} \u2014 ${event.reason === "rate_limited" ? "rate limited" : "server error"}, backing off ${(event.waitMs / 1e3).toFixed(1)}s (retry ${event.attempt}/${event.maxRetries})`
1460
1462
  );
1461
1463
  break;
1464
+ case "scan:throttled":
1465
+ spinner.text = c.yellow(
1466
+ `Target throttling \u2014 slowing to ${(event.delayMs / 1e3).toFixed(1)}s/req${event.atFloor ? " (at floor)" : ""}, continuing\u2026`
1467
+ );
1468
+ break;
1462
1469
  case "scan:rate_limited":
1463
1470
  spinner.fail(
1464
1471
  c.red(
@@ -1487,6 +1494,17 @@ function printSummary(report, thresholds) {
1487
1494
  console.log(
1488
1495
  ` ${c.red(`${vulnerable.length} vulnerable`)} \xB7 ${c.green(`${secure.length} secure`)} \xB7 ${c.yellow(`${errors.length} errors`)}`
1489
1496
  );
1497
+ const evaluated = vulnerable.length + secure.length;
1498
+ const total = report.attacks.length;
1499
+ if (evaluated < total) {
1500
+ console.log(
1501
+ c.yellow(
1502
+ ` Coverage: ${evaluated}/${total} evaluated \u2014 grade reflects only these; re-run to cover the ${total - evaluated} rate-limited/errored.`
1503
+ )
1504
+ );
1505
+ } else {
1506
+ console.log(` Coverage: ${evaluated}/${total} evaluated`);
1507
+ }
1490
1508
  if (vulnerable.length > 0) {
1491
1509
  console.log("");
1492
1510
  console.log(c.redBold(" Vulnerabilities:"));
@@ -2173,6 +2191,14 @@ async function scanCommand(opts) {
2173
2191
  ...opts.outputFile ? { file: opts.outputFile } : {}
2174
2192
  };
2175
2193
  }
2194
+ if (opts.concurrency !== void 0)
2195
+ cliOverrides.concurrency = opts.concurrency;
2196
+ if (opts.delay !== void 0) cliOverrides.delayMs = opts.delay;
2197
+ if (opts.maxDelay !== void 0) cliOverrides.maxDelayMs = opts.maxDelay;
2198
+ if (opts.retries !== void 0)
2199
+ cliOverrides.maxRateLimitRetries = opts.retries;
2200
+ if (opts.maxFloorThrottles !== void 0)
2201
+ cliOverrides.maxFloorThrottles = opts.maxFloorThrottles;
2176
2202
  const config = loadConfig({
2177
2203
  configPath: opts.config,
2178
2204
  cliOverrides
@@ -2285,6 +2311,8 @@ async function scanCommand(opts) {
2285
2311
  maxRateLimitRetries: config.maxRateLimitRetries,
2286
2312
  rateLimitBackoffMs: config.rateLimitBackoffMs,
2287
2313
  rateLimitMaxBackoffMs: config.rateLimitMaxBackoffMs,
2314
+ maxDelayMs: config.maxDelayMs,
2315
+ maxFloorThrottles: config.maxFloorThrottles,
2288
2316
  checkpoint: checkpointStore,
2289
2317
  evaluator
2290
2318
  };
@@ -2594,6 +2622,13 @@ function validateCommand(opts) {
2594
2622
  }
2595
2623
 
2596
2624
  // src/cli.ts
2625
+ function parseIntArg(value) {
2626
+ const n = Number.parseInt(value, 10);
2627
+ if (Number.isNaN(n)) {
2628
+ throw new InvalidArgumentError("Expected an integer.");
2629
+ }
2630
+ return n;
2631
+ }
2597
2632
  function reportFatal(label, err) {
2598
2633
  console.error(`
2599
2634
  ${label}:`);
@@ -2631,7 +2666,27 @@ program.command("scan").description("Run a security scan against a target chatbo
2631
2666
  ).option(
2632
2667
  "--preset <name>",
2633
2668
  "Scan preset (dev, quick, owasp, frontier, standard, full)"
2634
- ).option("--system-prompt <text>", "System prompt for target chatbot").option("--system-prompt-file <path>", "Path to system prompt file").option("--crescendo", "Include crescendo (multi-turn) attacks").option("--min-score <n>", "Minimum score threshold", parseFloat).option("--fail-on-critical", "Fail if any CRITICAL vulnerability found").option("-o, --output <format>", "Output format (json, markdown, sarif, pdf)").option("--output-file <path>", "Write report to file").option(
2669
+ ).option("--system-prompt <text>", "System prompt for target chatbot").option("--system-prompt-file <path>", "Path to system prompt file").option("--crescendo", "Include crescendo (multi-turn) attacks").option(
2670
+ "--concurrency <n>",
2671
+ "Max parallel single-turn attacks (AIMD backs off on throttling; default 4, set 1 for sequential)",
2672
+ parseIntArg
2673
+ ).option(
2674
+ "--delay <ms>",
2675
+ "Base inter-request delay in ms (the adaptive pacing floor)",
2676
+ parseIntArg
2677
+ ).option(
2678
+ "--max-delay <ms>",
2679
+ "Ceiling for the adaptive inter-request delay in ms (default 5000)",
2680
+ parseIntArg
2681
+ ).option(
2682
+ "--retries <n>",
2683
+ "Max retries on a 429 / gateway 5xx before giving up an attack (default 3)",
2684
+ parseIntArg
2685
+ ).option(
2686
+ "--max-floor-throttles <n>",
2687
+ "Consecutive throttles at the pacing floor before hard-stopping (default 3)",
2688
+ parseIntArg
2689
+ ).option("--min-score <n>", "Minimum score threshold", parseFloat).option("--fail-on-critical", "Fail if any CRITICAL vulnerability found").option("-o, --output <format>", "Output format (json, markdown, sarif, pdf)").option("--output-file <path>", "Write report to file").option(
2635
2690
  "--write-json <path>",
2636
2691
  "Always write a parseable JSON copy here, regardless of --output (useful for CI to extract score/grade alongside SARIF)"
2637
2692
  ).option(
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  generatePdf,
10
10
  loadConfig,
11
11
  loadSystemPrompt
12
- } from "./chunk-S2OWXRK6.js";
12
+ } from "./chunk-LGX52ZEL.js";
13
13
  export {
14
14
  ConfigError,
15
15
  ConfigSchema,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shield-llm",
3
- "version": "0.5.4",
3
+ "version": "0.6.1",
4
4
  "description": "AI chatbot security scanner — automated red teaming for LLMs",
5
5
  "type": "module",
6
6
  "publishConfig": {