shield-llm 0.5.4 → 0.6.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.
@@ -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.0";
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,13 @@ 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;
5768
5826
  this.targetClient = createTargetClient(
5769
5827
  options.target,
5770
5828
  options.systemPrompt
@@ -5784,7 +5842,9 @@ var Scanner = class {
5784
5842
  includeCrescendo: options.includeCrescendo ?? false,
5785
5843
  maxRateLimitRetries: options.maxRateLimitRetries ?? 3,
5786
5844
  rateLimitBackoffMs: options.rateLimitBackoffMs ?? 1e3,
5787
- rateLimitMaxBackoffMs: options.rateLimitMaxBackoffMs ?? 3e4
5845
+ rateLimitMaxBackoffMs: options.rateLimitMaxBackoffMs ?? 3e4,
5846
+ maxDelayMs: options.maxDelayMs ?? 5e3,
5847
+ maxFloorThrottles: options.maxFloorThrottles ?? 3
5788
5848
  };
5789
5849
  this.onEvent = onEvent;
5790
5850
  }
@@ -5838,6 +5898,8 @@ var Scanner = class {
5838
5898
  let consecutiveFailures = 0;
5839
5899
  let attackIndex = 0;
5840
5900
  let rateLimited = false;
5901
+ this.currentDelayMs = this.options.delayMs;
5902
+ this.throttleFloorStreak = 0;
5841
5903
  const singleResults = new Array(
5842
5904
  attacks.length
5843
5905
  );
@@ -5888,23 +5950,23 @@ var Scanner = class {
5888
5950
  total: totalAttacks
5889
5951
  });
5890
5952
  void (async () => {
5891
- if (this.options.delayMs > 0) await sleep(this.options.delayMs);
5953
+ if (this.currentDelayMs > 0) await sleep(this.currentDelayMs);
5892
5954
  const result = await this.executeSingleTurnAttack(attack);
5893
5955
  singleResults[idx] = result;
5894
5956
  await store?.record(result);
5895
5957
  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
- });
5958
+ if (this.handleThrottle(
5959
+ idx,
5960
+ totalAttacks,
5961
+ parseRetryAfterSec(result.error)
5962
+ )) {
5963
+ rateLimited = true;
5964
+ }
5903
5965
  } else if (result.error) {
5904
5966
  if (!result.payloadRejected) consecutiveFailures++;
5905
5967
  } else {
5906
5968
  consecutiveFailures = 0;
5907
- this.aimdIncrease();
5969
+ this.handleSuccess();
5908
5970
  }
5909
5971
  this.emit({
5910
5972
  type: "attack:complete",
@@ -5928,6 +5990,37 @@ var Scanner = class {
5928
5990
  pump();
5929
5991
  });
5930
5992
  this.inConcurrentPhase = false;
5993
+ let madeProgress = !stop();
5994
+ while (madeProgress && !stop()) {
5995
+ madeProgress = false;
5996
+ for (let i = 0; i < attacks.length; i++) {
5997
+ if (stop()) break;
5998
+ const prior = singleResults[i];
5999
+ if (!prior || !prior.rateLimited) continue;
6000
+ if (this.currentDelayMs > 0) await sleep(this.currentDelayMs);
6001
+ const retry = await this.executeSingleTurnAttack(attacks[i]);
6002
+ singleResults[i] = retry;
6003
+ await store?.record(retry);
6004
+ if (retry.rateLimited) {
6005
+ if (this.handleThrottle(
6006
+ i,
6007
+ totalAttacks,
6008
+ parseRetryAfterSec(retry.error)
6009
+ )) {
6010
+ rateLimited = true;
6011
+ }
6012
+ } else {
6013
+ if (!retry.error) this.handleSuccess();
6014
+ madeProgress = true;
6015
+ }
6016
+ this.emit({
6017
+ type: "attack:complete",
6018
+ result: retry,
6019
+ index: i,
6020
+ total: totalAttacks
6021
+ });
6022
+ }
6023
+ }
5931
6024
  for (let i = 0; i < attacks.length; i++) {
5932
6025
  if (singleResults[i] === void 0) {
5933
6026
  const skip = this.createSkippedResult(
@@ -5989,17 +6082,14 @@ var Scanner = class {
5989
6082
  results.push(result);
5990
6083
  await store?.record(result);
5991
6084
  if (result.rateLimited) {
5992
- rateLimited = true;
5993
- this.emit({
5994
- type: "scan:rate_limited",
5995
- attackIndex,
5996
- total: totalAttacks,
5997
- retryAfterSec: null
5998
- });
6085
+ if (this.handleThrottle(attackIndex, totalAttacks, null)) {
6086
+ rateLimited = true;
6087
+ }
5999
6088
  } else if (result.error) {
6000
6089
  if (!result.payloadRejected) consecutiveFailures++;
6001
6090
  } else {
6002
6091
  consecutiveFailures = 0;
6092
+ this.handleSuccess();
6003
6093
  }
6004
6094
  this.emit({
6005
6095
  type: "attack:complete",
@@ -6008,8 +6098,42 @@ var Scanner = class {
6008
6098
  total: totalAttacks
6009
6099
  });
6010
6100
  attackIndex++;
6011
- if (attackIndex < totalAttacks && this.options.delayMs > 0) {
6012
- await sleep(this.options.delayMs);
6101
+ if (attackIndex < totalAttacks && this.currentDelayMs > 0) {
6102
+ await sleep(this.currentDelayMs);
6103
+ }
6104
+ }
6105
+ let mtProgress = !stop();
6106
+ while (mtProgress && !stop()) {
6107
+ mtProgress = false;
6108
+ for (let k = 0; k < crescendoAttacks.length; k++) {
6109
+ if (stop()) break;
6110
+ const at = attacks.length + k;
6111
+ const prior = results[at];
6112
+ if (!prior || !prior.rateLimited || prior.error?.startsWith("Skipped")) {
6113
+ continue;
6114
+ }
6115
+ if (this.currentDelayMs > 0) await sleep(this.currentDelayMs);
6116
+ const retry = await this.executeMultiTurnAttack(crescendoAttacks[k]);
6117
+ results[at] = retry;
6118
+ await store?.record(retry);
6119
+ if (retry.rateLimited) {
6120
+ if (this.handleThrottle(
6121
+ at,
6122
+ totalAttacks,
6123
+ parseRetryAfterSec(retry.error)
6124
+ )) {
6125
+ rateLimited = true;
6126
+ }
6127
+ } else {
6128
+ if (!retry.error) this.handleSuccess();
6129
+ mtProgress = true;
6130
+ }
6131
+ this.emit({
6132
+ type: "attack:complete",
6133
+ result: retry,
6134
+ index: at,
6135
+ total: totalAttacks
6136
+ });
6013
6137
  }
6014
6138
  }
6015
6139
  for (const customTest of customTests) {
@@ -6045,8 +6169,8 @@ var Scanner = class {
6045
6169
  total: totalAttacks
6046
6170
  });
6047
6171
  attackIndex++;
6048
- if (attackIndex < totalAttacks && this.options.delayMs > 0) {
6049
- await sleep(this.options.delayMs);
6172
+ if (attackIndex < totalAttacks && this.currentDelayMs > 0) {
6173
+ await sleep(this.currentDelayMs);
6050
6174
  }
6051
6175
  }
6052
6176
  const score = calculateScore(results);
@@ -6317,7 +6441,11 @@ var Scanner = class {
6317
6441
  if (error instanceof RateLimitError && error.retryAfterSec != null && error.retryAfterSec > 0) {
6318
6442
  return Math.min(error.retryAfterSec * 1e3, cap);
6319
6443
  }
6320
- return Math.min(this.options.rateLimitBackoffMs * 2 ** attempt, cap);
6444
+ const window = Math.min(
6445
+ this.options.rateLimitBackoffMs * 2 ** attempt,
6446
+ cap
6447
+ );
6448
+ return Math.floor(Math.random() * window);
6321
6449
  }
6322
6450
  // ──────────────────────────────────────────────
6323
6451
  // AIMD adaptive concurrency
@@ -6355,6 +6483,68 @@ var Scanner = class {
6355
6483
  }
6356
6484
  }
6357
6485
  // ──────────────────────────────────────────────
6486
+ // Adaptive pacing (second AIMD lever — inter-request delay)
6487
+ // ──────────────────────────────────────────────
6488
+ /** Multiplicative increase of the inter-request delay on a throttle, capped
6489
+ * at maxDelayMs. Uses a 250ms floor so it still slows down when delayMs=0. */
6490
+ inflateDelay() {
6491
+ const base = Math.max(this.options.delayMs, 250);
6492
+ this.currentDelayMs = Math.min(
6493
+ this.options.maxDelayMs,
6494
+ Math.max(base, this.currentDelayMs * 2)
6495
+ );
6496
+ }
6497
+ /** Additive decrease of the delay on a clean success — slow reconvergence
6498
+ * toward the floor (delayMs) so we don't immediately re-trip the limiter. */
6499
+ decayDelay() {
6500
+ if (this.currentDelayMs <= this.options.delayMs) return;
6501
+ const step = Math.max(this.options.delayMs, 200);
6502
+ this.currentDelayMs = Math.max(
6503
+ this.options.delayMs,
6504
+ this.currentDelayMs - step
6505
+ );
6506
+ }
6507
+ /**
6508
+ * Process a throttle (a rate-limited result that survived the per-attack retry
6509
+ * budget). Back the pacer off — halve the concurrency cap AND inflate the
6510
+ * delay — and report whether the scan should HARD-STOP. It stops only when the
6511
+ * pacer is already at the floor (cap 1 + maxDelayMs) and STILL gets throttled
6512
+ * `maxFloorThrottles` times in a row: that is a hard quota/ban, not transient
6513
+ * congestion. Below the floor a throttle just slows the scan and it continues,
6514
+ * so a target that responds to backoff finishes the whole suite.
6515
+ */
6516
+ handleThrottle(attackIndex, total, retryAfterSec) {
6517
+ this.aimdDecrease();
6518
+ this.inflateDelay();
6519
+ const atFloor = this.aimdLimit <= 1 && this.currentDelayMs >= this.options.maxDelayMs;
6520
+ if (atFloor) this.throttleFloorStreak++;
6521
+ const stop = this.throttleFloorStreak >= this.options.maxFloorThrottles;
6522
+ if (stop) {
6523
+ this.emit({
6524
+ type: "scan:rate_limited",
6525
+ attackIndex,
6526
+ total,
6527
+ retryAfterSec
6528
+ });
6529
+ } else {
6530
+ this.emit({
6531
+ type: "scan:throttled",
6532
+ attackIndex,
6533
+ total,
6534
+ delayMs: this.currentDelayMs,
6535
+ atFloor
6536
+ });
6537
+ }
6538
+ return stop;
6539
+ }
6540
+ /** A clean success: reset the at-floor streak and speed the pacer back up
6541
+ * (decay the delay, grow the concurrency cap). */
6542
+ handleSuccess() {
6543
+ this.throttleFloorStreak = 0;
6544
+ this.decayDelay();
6545
+ this.aimdIncrease();
6546
+ }
6547
+ // ──────────────────────────────────────────────
6358
6548
  // Helpers
6359
6549
  // ──────────────────────────────────────────────
6360
6550
  buildEvaluation(evalResult) {
@@ -9119,6 +9309,7 @@ function buildMessage(attack) {
9119
9309
 
9120
9310
  export {
9121
9311
  version,
9312
+ replaceLoneSurrogates,
9122
9313
  summarizeAttackErrors,
9123
9314
  deserializeAttack,
9124
9315
  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-6AYERWP2.js";
32
33
 
33
34
  // src/load-env.ts
34
35
  try {
@@ -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:"));
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-6AYERWP2.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.0",
4
4
  "description": "AI chatbot security scanner — automated red teaming for LLMs",
5
5
  "type": "module",
6
6
  "publishConfig": {