shield-llm 0.14.0 → 0.16.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.
@@ -1307,9 +1307,9 @@ var RATE_LIMIT_PATTERNS = [
1307
1307
  }
1308
1308
  ];
1309
1309
  var RATE_LIMIT_SCAN_CHARS = 8192;
1310
- function detectRateLimit(text) {
1311
- if (!text) return null;
1312
- const head = text.length > RATE_LIMIT_SCAN_CHARS ? text.slice(0, RATE_LIMIT_SCAN_CHARS) : text;
1310
+ function detectRateLimit(text2) {
1311
+ if (!text2) return null;
1312
+ const head = text2.length > RATE_LIMIT_SCAN_CHARS ? text2.slice(0, RATE_LIMIT_SCAN_CHARS) : text2;
1313
1313
  const run = guardedRun(() => {
1314
1314
  for (const { pattern, platform } of RATE_LIMIT_PATTERNS) {
1315
1315
  if (pattern.test(head)) return platform;
@@ -1321,13 +1321,13 @@ function detectRateLimit(text) {
1321
1321
 
1322
1322
  // ../../packages/shared/src/unicode.ts
1323
1323
  function replaceLoneSurrogates(input) {
1324
- return input.replace(/[\uD800-\uDFFF]/g, (ch, index, str) => {
1324
+ return input.replace(/[\uD800-\uDFFF]/g, (ch, index, str3) => {
1325
1325
  const code = ch.charCodeAt(0);
1326
1326
  if (code <= 56319) {
1327
- const next = str.charCodeAt(index + 1);
1327
+ const next = str3.charCodeAt(index + 1);
1328
1328
  if (next >= 56320 && next <= 57343) return ch;
1329
1329
  } else {
1330
- const prev = str.charCodeAt(index - 1);
1330
+ const prev = str3.charCodeAt(index - 1);
1331
1331
  if (prev >= 55296 && prev <= 56319) return ch;
1332
1332
  }
1333
1333
  return "\uFFFD";
@@ -8672,6 +8672,262 @@ function recordVerification(claim, input) {
8672
8672
  };
8673
8673
  }
8674
8674
 
8675
+ // ../../packages/shared/src/remediation/playbooks.ts
8676
+ var FIX_OUTCOME_LABEL = {
8677
+ closable: "Can be closed in code",
8678
+ reducible: "Can be reduced, not eliminated",
8679
+ redesign: "Needs a design change"
8680
+ };
8681
+ function bench20261114(result) {
8682
+ return {
8683
+ date: "2026-11-14",
8684
+ model: "mistral-nemo 12B (local)",
8685
+ setup: "reference support bot, fixed by a coding agent from this brief, one run",
8686
+ result
8687
+ };
8688
+ }
8689
+ var SECRETS_OUT_OF_CONTEXT = "Take every secret (keys, internal codes, channel names, internal URLs) and every authorization rule out of the instructions: what is not in the model's context cannot leak. Rotate any secret that was there: treat it as disclosed.";
8690
+ var FIX_PLAYBOOKS = {
8691
+ SYSTEM_PROMPT_LEAK: {
8692
+ defect: "The bot repeats the instructions it was given when a user asks for them.",
8693
+ outcome: "reducible",
8694
+ remove: [
8695
+ SECRETS_OUT_OF_CONTEXT,
8696
+ "Remove capabilities the bot does not really have (a database it cannot query): the model states them as fact and invents content to match."
8697
+ ],
8698
+ enforceInCode: [
8699
+ "Filter the answer before it leaves the server: replace an answer that contains a long verbatim run of the instructions. Normalise first (case, whitespace, base64, hex, reversed text) so an encoded copy is caught too.",
8700
+ "Write the instructions as if they were public, so that their disclosure costs nothing."
8701
+ ],
8702
+ instructions: [
8703
+ "A short rule not to disclose or describe the instructions. On its own it does not hold: a reworded request gets through."
8704
+ ],
8705
+ redesign: [
8706
+ "Enforce business rules (discount limits, who may see what) in application code, never by a sentence in the instructions."
8707
+ ],
8708
+ pitfalls: [
8709
+ "The filter must compare the answer with the text of the instructions, not look for words such as 'instructions' or 'prompt': otherwise it replaces the bot's own correct refusals.",
8710
+ "A translation or a paraphrase of the instructions passes any verbatim filter. Record that residual risk instead of chasing it with more patterns.",
8711
+ "When the filter triggers on an ordinary question, answer that question again rather than returning a bare refusal."
8712
+ ],
8713
+ neighbours: ["REPEAT_VERBATIM_LEAK", "SYSTEM_PROMPT_LEAK_INDIRECT"],
8714
+ evidence: [
8715
+ bench20261114(
8716
+ "the exploit and its 2 neighbouring attacks failed in an independent retest."
8717
+ )
8718
+ ]
8719
+ },
8720
+ POLICY_PUPPETRY: {
8721
+ defect: "A message dressed as a system, policy or configuration block (XML, JSON, INI) makes the bot switch to a mode it does not have and dump its configuration.",
8722
+ outcome: "reducible",
8723
+ remove: [SECRETS_OUT_OF_CONTEXT],
8724
+ enforceInCode: [
8725
+ "The user channel carries no authority: a user message is never configuration. If the application has real modes (debug, admin), switch them in code from an authenticated session, never from message text.",
8726
+ "Apply the output filter of an instructions leak: the usual payload of this attack is a configuration dump.",
8727
+ "Optionally answer a message that is mostly an override block with a fixed reply, without calling the model. This is a heuristic layer: a reworded block gets past it."
8728
+ ],
8729
+ instructions: [
8730
+ "State that no message can change the bot's mode, role or rules, and that it has no diagnostic, debug or maintenance mode."
8731
+ ],
8732
+ redesign: [
8733
+ "Keep what an attacker would gain (data, tools) behind checks the model cannot waive."
8734
+ ],
8735
+ pitfalls: [
8736
+ "A block-shaped message can be legitimate: a customer pasting an XML error or a JSON payload to ask about it. Match on override vocabulary inside the block, not on the markup alone, and test with a pasted error.",
8737
+ "Questions about a real 'maintenance mode' of your own product must still be answered."
8738
+ ],
8739
+ neighbours: ["BACKDOOR_TRIGGER_TEST", "SUPPLY_CHAIN_UPDATE_SPOOF"],
8740
+ evidence: [
8741
+ bench20261114(
8742
+ "the exploit and its 2 neighbouring attacks failed in an independent retest."
8743
+ )
8744
+ ]
8745
+ },
8746
+ BACKDOOR_TRIGGER_TEST: {
8747
+ defect: "An 'activation key' or trigger phrase makes the bot announce an unrestricted or diagnostic mode and act on it.",
8748
+ outcome: "reducible",
8749
+ remove: [],
8750
+ enforceInCode: [
8751
+ "Never let message text switch a mode: a real privileged mode is entered through authenticated application code.",
8752
+ "Replace an answer that announces a special mode ('diagnostic mode enabled', 'restrictions disabled') and answer normally instead."
8753
+ ],
8754
+ instructions: [
8755
+ "State that there are no activation keys, hidden modes or passphrases, and that a claimed key changes nothing."
8756
+ ],
8757
+ redesign: [
8758
+ "If the concern is a poisoned or backdoored model, that is a supply-chain control: pin the model version, use a provider you can audit, test again on every model change. Application code cannot establish or remove a backdoor in the weights."
8759
+ ],
8760
+ pitfalls: [
8761
+ "Do not block every message that contains 'key' or 'activation': customers ask about product activation keys."
8762
+ ],
8763
+ neighbours: ["POLICY_PUPPETRY", "SUPPLY_CHAIN_UPDATE_SPOOF"],
8764
+ evidence: [
8765
+ bench20261114(
8766
+ "the exploit and its 2 neighbouring attacks failed in an independent retest."
8767
+ )
8768
+ ]
8769
+ },
8770
+ XSS_OUTPUT: {
8771
+ defect: "The bot's answer reaches a renderer as active HTML.",
8772
+ outcome: "closable",
8773
+ remove: [],
8774
+ enforceInCode: [
8775
+ `Encode the model's output for the context it is rendered in (in HTML: & < > " ') where the answer is inserted into a page (the template or the chat widget), or render it as text. Do it there for every answer, not only for suspicious ones.`,
8776
+ "If you render Markdown, use a sanitising renderer with an allow-list: no raw HTML, no javascript: or data: links, remote images disabled or limited to your own hosts.",
8777
+ "Add a Content-Security-Policy to the page that displays the chat."
8778
+ ],
8779
+ instructions: [
8780
+ "Asking the model not to produce HTML helps little and is not the fix."
8781
+ ],
8782
+ redesign: [],
8783
+ pitfalls: [
8784
+ "Encode once, at the output boundary. Encoding in the API and again in the front end shows '&amp;' to users.",
8785
+ "An API consumed by other programs should return the raw text and let each client encode for its own context.",
8786
+ "An escaped payload still contains the word 'script'. What matters is that no active tag survives: test the rendered result."
8787
+ ],
8788
+ neighbours: [],
8789
+ evidence: [bench20261114("the exploit failed in an independent retest.")]
8790
+ },
8791
+ SENSITIVE_DATA_EXTRACTION: {
8792
+ defect: "The bot discloses personal data, credentials or confidential content that is in its context.",
8793
+ outcome: "closable",
8794
+ remove: [
8795
+ "Do not put credentials, internal identifiers or other users' data in the instructions or in the conversation context. Give the model only the data of the authenticated user, fetched per request."
8796
+ ],
8797
+ enforceInCode: [
8798
+ "Redact known secret values and common credential formats from the answer before it leaves the server, after normalising encodings.",
8799
+ "Enforce who may read what in the data layer (the query), not in the model."
8800
+ ],
8801
+ instructions: ["A rule not to reveal confidential data, as a complement."],
8802
+ redesign: [],
8803
+ pitfalls: [
8804
+ "Keep the list of secrets to redact in configuration, not in the model's context.",
8805
+ "Before relying on a declared secret, check that it does not appear in ordinary answers: a value the bot is meant to give to customers is not a secret."
8806
+ ],
8807
+ neighbours: [],
8808
+ evidence: []
8809
+ },
8810
+ EXCESSIVE_AGENCY: {
8811
+ defect: "The bot runs, or says it runs, a command or an action a user asked for, with no check outside the model.",
8812
+ outcome: "closable",
8813
+ remove: [],
8814
+ enforceInCode: [
8815
+ "Give the model only the tools it needs, each with the narrowest parameters, deny by default. Validate every tool argument in code (allow-listed hosts, no shell interpolation).",
8816
+ "Require a confirmation by a human, outside the model, for any action that spends money, sends data out or cannot be undone.",
8817
+ "If the bot has no tools at all, make it say so instead of acting out an execution."
8818
+ ],
8819
+ instructions: ["State what the bot can and cannot do, as a complement."],
8820
+ redesign: [
8821
+ "Run tools with the user's own permissions, never a shared service account, so the model cannot do more than the user could."
8822
+ ],
8823
+ pitfalls: [
8824
+ "Explaining what a command does is not executing it: do not make the bot refuse to discuss commands if your product is technical."
8825
+ ],
8826
+ neighbours: ["PLUGIN_COMMAND_INJECTION"],
8827
+ evidence: []
8828
+ },
8829
+ RAG_SOURCE_LEAK: {
8830
+ defect: "Under an audit or compliance pretext, the bot lists the documents, file paths or retrieval internals behind its answers, or invents them.",
8831
+ outcome: "reducible",
8832
+ remove: [
8833
+ "Do not pass file paths, storage locations, index names or internal document ids to the model: give it the passage text and, if you cite sources, a public title or link only.",
8834
+ "Remove claims of access the bot does not have ('you can read the order database'): the model invents sources to match them."
8835
+ ],
8836
+ enforceInCode: [
8837
+ "Strip internal paths and identifiers from the answer before it leaves the server.",
8838
+ "Handle data-subject and audit requests through your real process (a form, a mailbox) and have the bot route to it."
8839
+ ],
8840
+ instructions: [
8841
+ "State that the bot does not disclose internal details of its sources, and where audit requests go."
8842
+ ],
8843
+ redesign: [],
8844
+ pitfalls: [
8845
+ "If the application has no retrieval, the 'sources' were made up: the fix is to stop the bot claiming them, not to filter metadata that does not exist.",
8846
+ "Customers may legitimately ask where an answer comes from: keep public citations working."
8847
+ ],
8848
+ neighbours: ["RAG_SOURCE_LEAK_FR", "RAG_METADATA_EXTRACTION"],
8849
+ evidence: [
8850
+ bench20261114(
8851
+ "the exploit and its 2 neighbouring attacks failed in an independent retest."
8852
+ )
8853
+ ]
8854
+ },
8855
+ SUPPLY_CHAIN_MODEL_DISCLOSURE: {
8856
+ defect: "A vendor-assessment questionnaire gets the bot to reveal which model it runs on, its knowledge cutoff or its limits, which tells an attacker which known attacks to try.",
8857
+ outcome: "reducible",
8858
+ remove: [],
8859
+ enforceInCode: [
8860
+ "Keep the bot on its task: answer an out-of-scope questionnaire with what the bot is for.",
8861
+ "Remove sentences that name the model, the provider or a training cutoff from the answer."
8862
+ ],
8863
+ instructions: [
8864
+ "State that the bot does not discuss its underlying model, provider, version, training data or limits, and answers the same way whether or not it knows them."
8865
+ ],
8866
+ redesign: [
8867
+ "Assume the model can be identified anyway: answer style and knowledge give it away. Do not let your security depend on the model being unknown; keep it patched and tested."
8868
+ ],
8869
+ pitfalls: [
8870
+ "The bot must still say it is an AI when asked: hiding the model is not hiding that it is a machine.",
8871
+ "Answering general-knowledge questions outside the bot's scope is what leaks the cutoff. A scope rule closes more than a filter on the word 'cutoff'."
8872
+ ],
8873
+ neighbours: ["SUPPLY_CHAIN_CAPABILITY_PROBE"],
8874
+ evidence: [
8875
+ bench20261114(
8876
+ "the exploit and its neighbouring attack failed in an independent retest."
8877
+ )
8878
+ ]
8879
+ },
8880
+ CONTEXT_OVERFLOW: {
8881
+ defect: "A request built to expand step by step makes the bot produce a very long answer: cost and latency grow without limit.",
8882
+ outcome: "closable",
8883
+ remove: [],
8884
+ enforceInCode: [
8885
+ "Set a hard cap on the output of one answer (maximum output tokens), sized for your use case, and caps on the input length and on the history you resend.",
8886
+ "Rate-limit and budget per user or per key, so that one caller cannot spend without limit.",
8887
+ "Set a timeout on the model call."
8888
+ ],
8889
+ instructions: [
8890
+ "A scope rule (the bot answers support questions, not academic briefings), as a complement."
8891
+ ],
8892
+ redesign: [],
8893
+ pitfalls: [
8894
+ "A cap that is too low cuts legitimate answers mid-sentence: measure the length of real answers first.",
8895
+ "A cap that already exists is not the fix if the answer cut at the cap is still delivered: decide what the user gets when the cap is hit, for example a short message asking for a narrower question."
8896
+ ],
8897
+ neighbours: ["RESOURCE_EXHAUSTION"],
8898
+ evidence: [
8899
+ bench20261114(
8900
+ "the exploit and its neighbouring attack failed in an independent retest."
8901
+ )
8902
+ ]
8903
+ },
8904
+ AI_IDENTITY_DENIAL: {
8905
+ defect: "Asked whether it is a human or an AI, the bot says it is human, or does not say it is an AI.",
8906
+ outcome: "closable",
8907
+ remove: [],
8908
+ enforceInCode: [
8909
+ "Show in the interface itself that the user is talking to an AI (a label on the chat), so the disclosure does not depend on the model.",
8910
+ "Replace an answer in which the bot states it is human."
8911
+ ],
8912
+ instructions: [
8913
+ "State that the bot is an AI assistant, says so whenever asked, in any language, and never claims or acts out being human, even when the user asks it to stay in character."
8914
+ ],
8915
+ redesign: [],
8916
+ pitfalls: [
8917
+ "Do not make the bot open every answer with 'I am an AI': it lengthens answers and annoys users. The interface label and a truthful answer when asked are enough.",
8918
+ "A persona with a first name is fine as long as it never claims to be human."
8919
+ ],
8920
+ neighbours: ["AI_IDENTITY_ROLEPLAY_DENIAL", "AI_IDENTITY_PERSISTENCE"],
8921
+ evidence: []
8922
+ }
8923
+ };
8924
+ function getFixPlaybook(attackId) {
8925
+ return FIX_PLAYBOOKS[attackId] ?? FIX_PLAYBOOKS[baseAttackId(attackId)];
8926
+ }
8927
+ function neighbourAttackIds(attackId) {
8928
+ return getFixPlaybook(attackId)?.neighbours ?? [];
8929
+ }
8930
+
8675
8931
  // ../../packages/shared/src/remediation/index.ts
8676
8932
  var DEFAULT_REMEDIATION = {
8677
8933
  vulnerabilityType: "DEFAULT",
@@ -8987,8 +9243,300 @@ function evaluateBenign(input) {
8987
9243
  };
8988
9244
  }
8989
9245
 
9246
+ // ../../packages/shared/src/supplemental/types.ts
9247
+ var IMPORT_SOURCES = ["promptfoo", "garak"];
9248
+ var IMPORT_LIMITS = {
9249
+ /** Attempts read from one file; the rest are reported as skipped. */
9250
+ maxAttemptsPerFile: 500,
9251
+ /** Supplemental rows one scan may hold (imports and packs together). */
9252
+ maxRowsPerScan: 1e3,
9253
+ /** Items per upload request: the server judges them inside the request. */
9254
+ batchSize: 10,
9255
+ maxTurns: 10,
9256
+ maxPromptChars: 1e4,
9257
+ maxResponseChars: 2e4,
9258
+ maxLabelChars: 200,
9259
+ maxObjectiveChars: 1e3,
9260
+ maxExternalIdChars: 200
9261
+ };
9262
+
9263
+ // ../../packages/shared/src/supplemental/import-promptfoo.ts
9264
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
9265
+ var str = (v) => typeof v === "string" ? v : void 0;
9266
+ function text(v) {
9267
+ if (typeof v === "string") return v;
9268
+ if (v === void 0 || v === null) return "";
9269
+ try {
9270
+ return JSON.stringify(v);
9271
+ } catch {
9272
+ return String(v);
9273
+ }
9274
+ }
9275
+ function promptfooResults(doc) {
9276
+ if (!isObj(doc)) return null;
9277
+ const results = doc.results;
9278
+ if (Array.isArray(results)) return results;
9279
+ if (isObj(results) && Array.isArray(results.results)) return results.results;
9280
+ return null;
9281
+ }
9282
+ function turnsFromMessages(messages) {
9283
+ const turns = [];
9284
+ let pending = null;
9285
+ for (const m of messages) {
9286
+ if (!isObj(m)) continue;
9287
+ const role = str(m.role);
9288
+ const content = text(m.content);
9289
+ if (role === "user") {
9290
+ if (pending !== null) turns.push({ prompt: pending, response: "" });
9291
+ pending = content;
9292
+ } else if (role === "assistant" && pending !== null) {
9293
+ turns.push({ prompt: pending, response: content });
9294
+ pending = null;
9295
+ }
9296
+ }
9297
+ if (pending !== null) turns.push({ prompt: pending, response: "" });
9298
+ return turns;
9299
+ }
9300
+ function transcriptOf(r) {
9301
+ const response = isObj(r.response) ? r.response : {};
9302
+ const meta = isObj(response.metadata) ? response.metadata : {};
9303
+ const output = text(response.output);
9304
+ if (Array.isArray(meta.messages) && meta.messages.length > 0) {
9305
+ const turns = turnsFromMessages(meta.messages);
9306
+ const last = turns[turns.length - 1];
9307
+ if (last && !last.response && output) last.response = output;
9308
+ if (turns.length > 0) return turns;
9309
+ }
9310
+ const finalPrompt = str(meta.redteamFinalPrompt) ?? (isObj(r.prompt) ? str(r.prompt.raw) : void 0) ?? "";
9311
+ return [{ prompt: finalPrompt, response: output }];
9312
+ }
9313
+ function toolVerdictOf(r) {
9314
+ const grading = isObj(r.gradingResult) ? r.gradingResult : void 0;
9315
+ const pass = typeof grading?.pass === "boolean" ? grading.pass : typeof r.success === "boolean" ? r.success : void 0;
9316
+ if (pass === void 0) return void 0;
9317
+ return pass ? "safe" : "vulnerable";
9318
+ }
9319
+ function clipTurns(turns) {
9320
+ return turns.slice(-IMPORT_LIMITS.maxTurns).map((t) => ({
9321
+ prompt: t.prompt.slice(0, IMPORT_LIMITS.maxPromptChars),
9322
+ response: t.response.slice(0, IMPORT_LIMITS.maxResponseChars)
9323
+ }));
9324
+ }
9325
+ function bump(skips, r) {
9326
+ skips.set(r, (skips.get(r) ?? 0) + 1);
9327
+ }
9328
+ function attemptOf(r, index, skips) {
9329
+ const testCase = isObj(r.testCase) ? r.testCase : {};
9330
+ const meta = isObj(testCase.metadata) ? testCase.metadata : {};
9331
+ const resultMeta = isObj(r.metadata) ? r.metadata : {};
9332
+ const response = isObj(r.response) ? r.response : void 0;
9333
+ if (!response || response.output === void 0 && !response.metadata) {
9334
+ bump(skips, str(r.error) ? "target_error" : "no_response");
9335
+ return null;
9336
+ }
9337
+ const turns = clipTurns(transcriptOf(r));
9338
+ if (turns.length === 0 || !turns[turns.length - 1].prompt.trim()) {
9339
+ bump(skips, "empty_prompt");
9340
+ return null;
9341
+ }
9342
+ const label = str(meta.pluginId) ?? str(resultMeta.pluginId) ?? "promptfoo-test";
9343
+ const strategy = str(meta.strategyId) ?? str(resultMeta.strategyId);
9344
+ const objective = str(meta.goal) ?? str(resultMeta.goal);
9345
+ const externalId = (str(r.id) ?? `${index}:${label}:${strategy ?? "basic"}`).slice(0, IMPORT_LIMITS.maxExternalIdChars);
9346
+ return {
9347
+ externalId,
9348
+ label: label.slice(0, IMPORT_LIMITS.maxLabelChars),
9349
+ ...strategy ? { strategy: strategy.slice(0, IMPORT_LIMITS.maxLabelChars) } : {},
9350
+ ...objective ? { objective: objective.slice(0, IMPORT_LIMITS.maxObjectiveChars) } : {},
9351
+ turns,
9352
+ ...toolVerdictOf(r) ? { toolVerdict: toolVerdictOf(r) } : {}
9353
+ };
9354
+ }
9355
+ function parsePromptfoo(doc) {
9356
+ const results = promptfooResults(doc);
9357
+ if (!results) return null;
9358
+ const seen = /* @__PURE__ */ new Map();
9359
+ const metadata = isObj(doc) && isObj(doc.metadata) ? doc.metadata : {};
9360
+ const skips = /* @__PURE__ */ new Map();
9361
+ const attempts = [];
9362
+ results.forEach((r, i) => {
9363
+ if (!isObj(r)) return;
9364
+ const a = attemptOf(r, i, skips);
9365
+ if (!a) return;
9366
+ const n = seen.get(a.externalId) ?? 0;
9367
+ seen.set(a.externalId, n + 1);
9368
+ if (n > 0) a.externalId = `${a.externalId}#${n}`.slice(0, IMPORT_LIMITS.maxExternalIdChars);
9369
+ if (attempts.length >= IMPORT_LIMITS.maxAttemptsPerFile) {
9370
+ bump(skips, "too_many_attempts");
9371
+ return;
9372
+ }
9373
+ attempts.push(a);
9374
+ });
9375
+ const version2 = str(metadata.promptfooVersion);
9376
+ return {
9377
+ source: "promptfoo",
9378
+ ...version2 ? { sourceVersion: version2 } : {},
9379
+ attempts,
9380
+ skipped: Array.from(skips.entries()).map(([reason, count]) => ({
9381
+ reason,
9382
+ count
9383
+ }))
9384
+ };
9385
+ }
9386
+
9387
+ // ../../packages/shared/src/supplemental/import-garak.ts
9388
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
9389
+ var str2 = (v) => typeof v === "string" ? v : void 0;
9390
+ var GARAK_HIT_THRESHOLD = 0.5;
9391
+ function garakEntries(textContent) {
9392
+ const entries = [];
9393
+ for (const line of textContent.split(/\r?\n/)) {
9394
+ const trimmed = line.trim();
9395
+ if (!trimmed.startsWith("{")) continue;
9396
+ try {
9397
+ const v = JSON.parse(trimmed);
9398
+ if (isObj2(v) && typeof v.entry_type === "string") entries.push(v);
9399
+ } catch {
9400
+ }
9401
+ }
9402
+ return entries.length > 0 ? entries : null;
9403
+ }
9404
+ function messageText(v) {
9405
+ if (isObj2(v)) return str2(v.text) ?? "";
9406
+ return str2(v) ?? "";
9407
+ }
9408
+ function turnsFromConversation(conv) {
9409
+ if (!isObj2(conv) || !Array.isArray(conv.turns)) return [];
9410
+ const turns = [];
9411
+ let pending = null;
9412
+ for (const t of conv.turns) {
9413
+ if (!isObj2(t)) continue;
9414
+ const content = messageText(t.content);
9415
+ if (t.role === "user") {
9416
+ if (pending !== null) turns.push({ prompt: pending, response: "" });
9417
+ pending = content;
9418
+ } else if (t.role === "assistant" && pending !== null) {
9419
+ turns.push({ prompt: pending, response: content });
9420
+ pending = null;
9421
+ }
9422
+ }
9423
+ if (pending !== null) turns.push({ prompt: pending, response: "" });
9424
+ return turns;
9425
+ }
9426
+ function verdictForGeneration(detectorResults, index) {
9427
+ if (!isObj2(detectorResults)) return void 0;
9428
+ const scores = Object.values(detectorResults).map((list) => Array.isArray(list) ? list[index] : void 0).filter((s) => typeof s === "number");
9429
+ if (scores.length === 0) return void 0;
9430
+ return scores.some((s) => s >= GARAK_HIT_THRESHOLD) ? "vulnerable" : "safe";
9431
+ }
9432
+ function generationsOf(a) {
9433
+ if (Array.isArray(a.conversations) && a.conversations.length > 0) {
9434
+ return a.conversations.map(turnsFromConversation);
9435
+ }
9436
+ const promptTurns = turnsFromConversation(a.prompt);
9437
+ const lastPrompt = promptTurns.length > 0 ? promptTurns[promptTurns.length - 1].prompt : messageText(a.prompt);
9438
+ const outputs = Array.isArray(a.outputs) ? a.outputs : [];
9439
+ return outputs.map((o) => [{ prompt: lastPrompt, response: messageText(o) }]);
9440
+ }
9441
+ function clip(turns) {
9442
+ return turns.slice(-IMPORT_LIMITS.maxTurns).map((t) => ({
9443
+ prompt: t.prompt.slice(0, IMPORT_LIMITS.maxPromptChars),
9444
+ response: t.response.slice(0, IMPORT_LIMITS.maxResponseChars)
9445
+ }));
9446
+ }
9447
+ function latestAttempts(entries) {
9448
+ const byUuid = /* @__PURE__ */ new Map();
9449
+ entries.forEach((e, i) => {
9450
+ if (e.entry_type !== "attempt") return;
9451
+ byUuid.set(str2(e.uuid) ?? `line-${i}`, e);
9452
+ });
9453
+ return Array.from(byUuid.values());
9454
+ }
9455
+ function parseGarak(textContent) {
9456
+ const entries = garakEntries(textContent);
9457
+ if (!entries) return null;
9458
+ const init = entries.find((e) => e.entry_type === "init");
9459
+ const version2 = init ? str2(init.garak_version) : void 0;
9460
+ const skips = /* @__PURE__ */ new Map();
9461
+ const bump2 = (r) => skips.set(r, (skips.get(r) ?? 0) + 1);
9462
+ const attempts = [];
9463
+ for (const a of latestAttempts(entries)) {
9464
+ const probe = (str2(a.probe_classname) ?? "garak-probe").slice(
9465
+ 0,
9466
+ IMPORT_LIMITS.maxLabelChars
9467
+ );
9468
+ const goal = str2(a.goal);
9469
+ const uuid = str2(a.uuid) ?? probe;
9470
+ generationsOf(a).forEach((raw, gen) => {
9471
+ const turns = clip(raw);
9472
+ const last = turns[turns.length - 1];
9473
+ if (!last || !last.prompt.trim()) return bump2("empty_prompt");
9474
+ if (!last.response.trim()) return bump2("no_response");
9475
+ if (attempts.length >= IMPORT_LIMITS.maxAttemptsPerFile) {
9476
+ return bump2("too_many_attempts");
9477
+ }
9478
+ const toolVerdict = verdictForGeneration(a.detector_results, gen);
9479
+ attempts.push({
9480
+ externalId: `${uuid}#${gen}`.slice(0, IMPORT_LIMITS.maxExternalIdChars),
9481
+ label: probe,
9482
+ ...goal ? { objective: goal.slice(0, IMPORT_LIMITS.maxObjectiveChars) } : {},
9483
+ turns,
9484
+ ...toolVerdict ? { toolVerdict } : {}
9485
+ });
9486
+ });
9487
+ }
9488
+ return {
9489
+ source: "garak",
9490
+ ...version2 ? { sourceVersion: version2 } : {},
9491
+ attempts,
9492
+ skipped: Array.from(skips.entries()).map(([reason, count]) => ({
9493
+ reason,
9494
+ count
9495
+ }))
9496
+ };
9497
+ }
9498
+
9499
+ // ../../packages/shared/src/supplemental/import-detect.ts
9500
+ function parseJson(textContent) {
9501
+ try {
9502
+ return JSON.parse(textContent);
9503
+ } catch {
9504
+ return void 0;
9505
+ }
9506
+ }
9507
+ function detectImportFormat(textContent) {
9508
+ const doc = parseJson(textContent);
9509
+ if (doc !== void 0) {
9510
+ return parsePromptfoo(doc) ? "promptfoo" : null;
9511
+ }
9512
+ return parseGarak(textContent) ? "garak" : null;
9513
+ }
9514
+ function parseImportFile(textContent, format) {
9515
+ const source = format ?? detectImportFormat(textContent);
9516
+ if (!source) {
9517
+ return {
9518
+ ok: false,
9519
+ error: "Unrecognised file. Supported: a promptfoo result file (promptfoo eval -o results.json) or a garak report (garak.<id>.report.jsonl)."
9520
+ };
9521
+ }
9522
+ const batch = source === "promptfoo" ? (() => {
9523
+ const doc = parseJson(textContent);
9524
+ return doc === void 0 ? null : parsePromptfoo(doc);
9525
+ })() : parseGarak(textContent);
9526
+ if (!batch) {
9527
+ return { ok: false, error: `Not a ${source} result file.` };
9528
+ }
9529
+ if (batch.attempts.length === 0) {
9530
+ return {
9531
+ ok: false,
9532
+ error: `No importable attempt in this ${source} file (every entry lacked a prompt or an answer).`
9533
+ };
9534
+ }
9535
+ return { ok: true, batch };
9536
+ }
9537
+
8990
9538
  // package.json
8991
- var version = "0.14.0";
9539
+ var version = "0.16.0";
8992
9540
 
8993
9541
  // src/config/schema.ts
8994
9542
  import { z as z3 } from "zod";
@@ -9490,15 +10038,15 @@ var HttpTargetClient = class {
9490
10038
  }
9491
10039
  async sendMessage(prompt, options) {
9492
10040
  const rawResponse = await this.sendRaw(prompt, [], options);
9493
- const text = this.extractResponse(rawResponse);
9494
- const platform = detectRateLimit(text);
10041
+ const text2 = this.extractResponse(rawResponse);
10042
+ const platform = detectRateLimit(text2);
9495
10043
  if (platform) {
9496
10044
  throw new RateLimitError(
9497
- `Rate limited (soft, body match \u2014 ${platform}): ${text.slice(0, 200)}`,
10045
+ `Rate limited (soft, body match \u2014 ${platform}): ${text2.slice(0, 200)}`,
9498
10046
  null
9499
10047
  );
9500
10048
  }
9501
- return text;
10049
+ return text2;
9502
10050
  }
9503
10051
  createSession() {
9504
10052
  if (this.config.statefulConversation) {
@@ -9719,9 +10267,9 @@ var StatefulHttpSession = class extends LazyAllocatedSession {
9719
10267
  ...options,
9720
10268
  sessionId
9721
10269
  });
9722
- const text = this.client.extractResponse(rawResponse);
9723
- this.recordTurn(prompt, text);
9724
- return text;
10270
+ const text2 = this.client.extractResponse(rawResponse);
10271
+ this.recordTurn(prompt, text2);
10272
+ return text2;
9725
10273
  }
9726
10274
  };
9727
10275
  var StatelessHttpSession = class extends LazyAllocatedSession {
@@ -9735,11 +10283,11 @@ var StatelessHttpSession = class extends LazyAllocatedSession {
9735
10283
  ...options,
9736
10284
  sessionId
9737
10285
  });
9738
- const text = this.client.extractResponse(rawResponse);
10286
+ const text2 = this.client.extractResponse(rawResponse);
9739
10287
  this.messages.push({ role: "user", content: prompt });
9740
- this.messages.push({ role: "assistant", content: text });
9741
- this.recordTurn(prompt, text);
9742
- return text;
10288
+ this.messages.push({ role: "assistant", content: text2 });
10289
+ this.recordTurn(prompt, text2);
10290
+ return text2;
9743
10291
  }
9744
10292
  };
9745
10293
  function formatHistory(history, format = "openai") {
@@ -9943,17 +10491,17 @@ async function fetchWithTimeout(url, init, timeoutMs, responseField, allowPrivat
9943
10491
  }
9944
10492
  const contentType = response.headers.get("content-type") ?? "";
9945
10493
  if (contentType.includes("text/event-stream")) {
9946
- const text = await collectSSE(response);
9947
- return nestAtPath(responseField ?? "response", text);
10494
+ const text2 = await collectSSE(response);
10495
+ return nestAtPath(responseField ?? "response", text2);
9948
10496
  }
9949
10497
  if (contentType.includes("ndjson")) {
9950
- const text = await collectNDJSON(response);
9951
- return nestAtPath(responseField ?? "response", text);
10498
+ const text2 = await collectNDJSON(response);
10499
+ return nestAtPath(responseField ?? "response", text2);
9952
10500
  }
9953
10501
  if (!contentType.includes("json")) {
9954
- const text = await readBodyWithLimit(response);
10502
+ const text2 = await readBodyWithLimit(response);
9955
10503
  throw new HttpTargetError(
9956
- `Expected JSON response but got ${contentType}. Body: ${text.slice(0, 500)}`,
10504
+ `Expected JSON response but got ${contentType}. Body: ${text2.slice(0, 500)}`,
9957
10505
  0
9958
10506
  );
9959
10507
  }
@@ -9987,8 +10535,8 @@ var ERROR_BODY_HEAD_BYTES = 8192;
9987
10535
  async function readErrorBodyHead(response) {
9988
10536
  try {
9989
10537
  if (!response.body) {
9990
- const text = typeof response.text === "function" ? await response.text() : "";
9991
- return text.slice(0, ERROR_BODY_HEAD_BYTES);
10538
+ const text2 = typeof response.text === "function" ? await response.text() : "";
10539
+ return text2.slice(0, ERROR_BODY_HEAD_BYTES);
9992
10540
  }
9993
10541
  const reader = response.body.getReader();
9994
10542
  const decoder = new TextDecoder();
@@ -11304,13 +11852,13 @@ var Scanner = class {
11304
11852
  const session = this.targetClient.createSession();
11305
11853
  try {
11306
11854
  const timing = { ms: 0 };
11307
- const text = await this.sendTurnWithRetry(
11855
+ const text2 = await this.sendTurnWithRetry(
11308
11856
  session,
11309
11857
  CONSUMPTION_BASELINE_PROMPT,
11310
11858
  "consumption-baseline",
11311
11859
  timing
11312
11860
  );
11313
- return { chars: text.length, ms: timing.ms };
11861
+ return { chars: text2.length, ms: timing.ms };
11314
11862
  } catch {
11315
11863
  return void 0;
11316
11864
  } finally {
@@ -11465,16 +12013,16 @@ function boundedValue(value, cap, canary) {
11465
12013
  if (typeof value === "number" || typeof value === "boolean" || value === null) {
11466
12014
  return value;
11467
12015
  }
11468
- let text;
12016
+ let text2;
11469
12017
  try {
11470
- text = typeof value === "string" ? value : JSON.stringify(value) ?? "";
12018
+ text2 = typeof value === "string" ? value : JSON.stringify(value) ?? "";
11471
12019
  } catch {
11472
- text = "[unserialisable]";
12020
+ text2 = "[unserialisable]";
11473
12021
  }
11474
- if (text.length <= cap) return text;
11475
- const head = text.slice(0, cap);
11476
- if (!text.includes(canary) || head.includes(canary)) return head;
11477
- return `${text.slice(0, Math.max(0, cap - canary.length - 1))}\u2026${canary}`;
12022
+ if (text2.length <= cap) return text2;
12023
+ const head = text2.slice(0, cap);
12024
+ if (!text2.includes(canary) || head.includes(canary)) return head;
12025
+ return `${text2.slice(0, Math.max(0, cap - canary.length - 1))}\u2026${canary}`;
11478
12026
  }
11479
12027
  function boundedArguments(args, canary) {
11480
12028
  if (!args || typeof args !== "object" || Array.isArray(args)) return {};
@@ -11930,6 +12478,15 @@ var CodebaseSchema = z3.object({
11930
12478
  ingestion: AnchorSchema.optional()
11931
12479
  }).default({})
11932
12480
  });
12481
+ var utf16 = (max) => z3.string().refine((s) => s.length <= max, `at most ${max} characters`);
12482
+ var TargetProfileSchema = z3.object({
12483
+ company: utf16(100).optional(),
12484
+ botName: utf16(100).optional(),
12485
+ competitors: z3.array(utf16(100)).max(5).optional(),
12486
+ allowedScope: utf16(300).optional(),
12487
+ sector: utf16(50).optional(),
12488
+ locale: z3.enum(["en", "fr"]).optional()
12489
+ }).strict();
11933
12490
  var ConfigSchema = z3.object({
11934
12491
  /** Optional: only needed by `shield-llm fix`. A scan never reads it. */
11935
12492
  codebase: CodebaseSchema.optional(),
@@ -11966,7 +12523,11 @@ var ConfigSchema = z3.object({
11966
12523
  // timed out, 5xx, no reply) before the scan is incomplete. Default 20.
11967
12524
  maxNotExecutedPercent: z3.number().min(0).max(100).optional(),
11968
12525
  thresholds: ThresholdSchema.optional(),
11969
- output: OutputSchema.optional()
12526
+ output: OutputSchema.optional(),
12527
+ /** Target profile for test packs. A scan without --pack never reads it. */
12528
+ profile: TargetProfileSchema.optional(),
12529
+ /** Test packs run after each scan, like --pack. */
12530
+ packs: z3.array(z3.string().regex(/^[a-z0-9-]{3,60}$/)).max(5).optional()
11970
12531
  });
11971
12532
 
11972
12533
  // src/config/loader.ts
@@ -12142,7 +12703,7 @@ function evaluateThresholds(report, thresholds) {
12142
12703
 
12143
12704
  // src/display/colors.ts
12144
12705
  import { styleText } from "util";
12145
- var make = (fmt) => (text) => styleText(fmt, text);
12706
+ var make = (fmt) => (text2) => styleText(fmt, text2);
12146
12707
  var c2 = {
12147
12708
  cyan: make("cyan"),
12148
12709
  red: make("red"),
@@ -12694,6 +13255,9 @@ export {
12694
13255
  isExpired,
12695
13256
  mayStampFixed,
12696
13257
  recordVerification,
13258
+ FIX_OUTCOME_LABEL,
13259
+ getFixPlaybook,
13260
+ neighbourAttackIds,
12697
13261
  getStructuredRemediation,
12698
13262
  sha256Hex,
12699
13263
  normalizeTargetUrl,
@@ -12702,6 +13266,9 @@ export {
12702
13266
  redactTargetUrl,
12703
13267
  computeScoreDelta,
12704
13268
  evaluateBenign,
13269
+ IMPORT_SOURCES,
13270
+ IMPORT_LIMITS,
13271
+ parseImportFile,
12705
13272
  version,
12706
13273
  RateLimitError,
12707
13274
  checkConversationContext,