ai-shield-core 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context/wrap-context.d.ts +65 -1
- package/dist/context/wrap-context.d.ts.map +1 -1
- package/dist/context/wrap-context.js +90 -0
- package/dist/cost/pricing.d.ts.map +1 -1
- package/dist/cost/pricing.js +15 -7
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -3
- package/dist/judge/async-judge.d.ts +85 -0
- package/dist/judge/async-judge.d.ts.map +1 -0
- package/dist/judge/async-judge.js +146 -0
- package/dist/scanner/heuristic.d.ts +14 -0
- package/dist/scanner/heuristic.d.ts.map +1 -1
- package/dist/scanner/heuristic.js +73 -5
- package/dist/scanner/ingestion.d.ts +31 -0
- package/dist/scanner/ingestion.d.ts.map +1 -1
- package/dist/scanner/ingestion.js +70 -2
- package/dist/scanner/output.d.ts +73 -0
- package/dist/scanner/output.d.ts.map +1 -0
- package/dist/scanner/output.js +297 -0
- package/dist/types.d.ts +18 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/context/wrap-context.ts +171 -0
- package/src/cost/pricing.ts +15 -7
- package/src/index.ts +31 -1
- package/src/judge/async-judge.ts +254 -0
- package/src/scanner/heuristic.ts +81 -5
- package/src/scanner/ingestion.ts +76 -2
- package/src/scanner/output.ts +386 -0
- package/src/types.ts +20 -1
package/src/scanner/heuristic.ts
CHANGED
|
@@ -11,12 +11,17 @@ import type { Scanner, ScannerResult, ScanContext, Violation } from "../types.js
|
|
|
11
11
|
// Keep minimal — false-mappings in real content are worse than
|
|
12
12
|
// false-negatives in an attack attempt.
|
|
13
13
|
const HOMOGLYPH_MAP: Record<string, string> = {
|
|
14
|
+
// Cyrillic
|
|
14
15
|
"а": "a", "е": "e", "і": "i", "ј": "j", "о": "o", "р": "p", "с": "c", "ѕ": "s",
|
|
15
|
-
"у": "y", "х": "x", "
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
|
|
19
|
-
"
|
|
16
|
+
"у": "y", "х": "x", "ԁ": "d", "һ": "h", "ӏ": "l", "ո": "n", "А": "A", "В": "B",
|
|
17
|
+
"Е": "E", "І": "I", "К": "K", "М": "M", "Н": "H", "О": "O", "Р": "P", "С": "C",
|
|
18
|
+
"Т": "T", "Х": "X", "Ѕ": "S", "Ј": "J", "Ү": "Y", "Ԛ": "Q", "Ԝ": "W", "Ғ": "F",
|
|
19
|
+
// Greek
|
|
20
|
+
"α": "a", "ο": "o", "ρ": "p", "ε": "e", "υ": "y", "χ": "x", "ν": "v", "ι": "i",
|
|
21
|
+
"κ": "k", "Α": "A", "Β": "B", "Ε": "E", "Ζ": "Z", "Η": "H", "Ι": "I", "Κ": "K",
|
|
22
|
+
"Μ": "M", "Ν": "N", "Ο": "O", "Ρ": "P", "Τ": "T", "Υ": "Y", "Χ": "X",
|
|
23
|
+
// Armenian / Cherokee / other look-alikes occasionally used in evasion
|
|
24
|
+
"օ": "o", "ѵ": "v",
|
|
20
25
|
};
|
|
21
26
|
|
|
22
27
|
const HOMOGLYPH_RE = new RegExp(Object.keys(HOMOGLYPH_MAP).join("|"), "g");
|
|
@@ -45,6 +50,30 @@ export function normalizeForInjectionScan(input: string): string {
|
|
|
45
50
|
return noCombining.replace(HOMOGLYPH_RE, (ch) => HOMOGLYPH_MAP[ch] ?? ch);
|
|
46
51
|
}
|
|
47
52
|
|
|
53
|
+
/**
|
|
54
|
+
* Collapse letter-splitting evasion: an attacker writes `i g n o r e` or
|
|
55
|
+
* `i.g.n.o.r.e` or `i-g-n-o-r-e` to break the literal token "ignore" across
|
|
56
|
+
* separators so the regex never matches. This produces an ADDITIONAL view
|
|
57
|
+
* where any run of `single-letter + separator` (≥4 letters) has its
|
|
58
|
+
* separators removed, so the spaced form collapses back to "ignore".
|
|
59
|
+
*
|
|
60
|
+
* Run as a second pass IN ADDITION to the normal normalized text — never
|
|
61
|
+
* as a replacement — because collapsing is lossy (it would also fuse the
|
|
62
|
+
* legitimate "a b c" list). Only single-letter groups separated by one
|
|
63
|
+
* space / dot / dash / underscore are collapsed; multi-letter words are
|
|
64
|
+
* left intact, which keeps benign prose untouched.
|
|
65
|
+
*/
|
|
66
|
+
export function collapseSpacedLetters(input: string): string {
|
|
67
|
+
// Match ≥3 "<letter><sep>" groups closed by a final lone letter. The
|
|
68
|
+
// trailing `(?![A-Za-z])` stops the greedy match from swallowing the
|
|
69
|
+
// first letter of the next real word ("i g n o r e all" must collapse to
|
|
70
|
+
// "ignore all", not "ignorea ll"). Bounded, linear — no nested quantifier.
|
|
71
|
+
return input.replace(
|
|
72
|
+
/(?:[A-Za-z][ \t._-]){3,}[A-Za-z](?![A-Za-z])/g,
|
|
73
|
+
(run) => run.replace(/[ \t._-]/g, ""),
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
48
77
|
interface PatternRule {
|
|
49
78
|
id: string;
|
|
50
79
|
category: InjectionCategory;
|
|
@@ -401,6 +430,19 @@ export class HeuristicScanner implements Scanner {
|
|
|
401
430
|
// homoglyph/zero-width evasion doesn't bypass the rules. The caller
|
|
402
431
|
// still sees the original input in `sanitized`.
|
|
403
432
|
const normalized = normalizeForInjectionScan(input);
|
|
433
|
+
// Second view that un-splits letter-splitting evasion ("i g n o r e").
|
|
434
|
+
// Only computed when it actually differs (cheap guard), and only the
|
|
435
|
+
// high-value override/role/extraction/tool categories are re-tested
|
|
436
|
+
// against it — collapsing is lossy and the low-value framing rules
|
|
437
|
+
// would false-positive on collapsed prose.
|
|
438
|
+
const collapsed = collapseSpacedLetters(normalized);
|
|
439
|
+
const collapsedDiffers = collapsed !== normalized;
|
|
440
|
+
const SPLIT_SENSITIVE: ReadonlySet<InjectionCategory> = new Set([
|
|
441
|
+
"instruction_override",
|
|
442
|
+
"role_manipulation",
|
|
443
|
+
"system_prompt_extraction",
|
|
444
|
+
"tool_abuse",
|
|
445
|
+
]);
|
|
404
446
|
|
|
405
447
|
for (const rule of this.patterns) {
|
|
406
448
|
if (rule.pattern.test(normalized)) {
|
|
@@ -413,6 +455,21 @@ export class HeuristicScanner implements Scanner {
|
|
|
413
455
|
message: rule.description,
|
|
414
456
|
detail: `Rule ${rule.id} (${rule.category})`,
|
|
415
457
|
});
|
|
458
|
+
} else if (
|
|
459
|
+
collapsedDiffers &&
|
|
460
|
+
SPLIT_SENSITIVE.has(rule.category) &&
|
|
461
|
+
rule.pattern.test(collapsed)
|
|
462
|
+
) {
|
|
463
|
+
// Matched only after un-splitting → letter-splitting evasion.
|
|
464
|
+
totalScore += rule.weight;
|
|
465
|
+
violations.push({
|
|
466
|
+
type: "prompt_injection",
|
|
467
|
+
scanner: this.name,
|
|
468
|
+
score: rule.weight,
|
|
469
|
+
threshold: this.threshold,
|
|
470
|
+
message: rule.description,
|
|
471
|
+
detail: `Rule ${rule.id} (${rule.category}, letter-splitting evasion)`,
|
|
472
|
+
});
|
|
416
473
|
}
|
|
417
474
|
}
|
|
418
475
|
|
|
@@ -459,6 +516,25 @@ export class HeuristicScanner implements Scanner {
|
|
|
459
516
|
// Very long input (potential padding attack)
|
|
460
517
|
if (input.length > 5000) score += 0.05;
|
|
461
518
|
|
|
519
|
+
// Adversarial suffix (GCG-style): a long whitespace-free token packed
|
|
520
|
+
// with mixed punctuation/symbols, typically appended after the readable
|
|
521
|
+
// request. Conservative — needs ≥25 chars and ≥6 distinct punctuation
|
|
522
|
+
// marks so ordinary URLs, hashes and code tokens don't trip it.
|
|
523
|
+
const ADV_TOKEN_RE = /\S{25,}/g;
|
|
524
|
+
let advMatch: RegExpExecArray | null;
|
|
525
|
+
let advCount = 0;
|
|
526
|
+
while ((advMatch = ADV_TOKEN_RE.exec(input)) !== null && advCount < 32) {
|
|
527
|
+
advCount += 1;
|
|
528
|
+
const tok = advMatch[0];
|
|
529
|
+
const distinctPunct = new Set(
|
|
530
|
+
(tok.match(/[!-/:-@[-`{-~]/g) ?? []),
|
|
531
|
+
).size;
|
|
532
|
+
if (distinctPunct >= 6) {
|
|
533
|
+
score += 0.05;
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
462
538
|
return score;
|
|
463
539
|
}
|
|
464
540
|
|
package/src/scanner/ingestion.ts
CHANGED
|
@@ -63,8 +63,14 @@ const SOURCE_PROFILE: Record<
|
|
|
63
63
|
extraPatterns: [
|
|
64
64
|
// "Before using this tool, you must ..." / "After calling, also call X"
|
|
65
65
|
/(?:before|after|while)\s+(?:using|invoking|calling|executing)\s+(?:this\s+)?(?:tool|function|action)[,\s]+(?:you\s+)?(?:must|should|will|need\s+to|are\s+required\s+to)/i,
|
|
66
|
-
// "Also call
|
|
67
|
-
|
|
66
|
+
// "Also call delete_account" / "then invoke query()". Tightened
|
|
67
|
+
// (review M2): the called symbol must carry a case-robust tool-name
|
|
68
|
+
// signal — a snake_case underscore or a `(` call — so benign docs prose
|
|
69
|
+
// ("first call the API", "then use the result") doesn't trip the
|
|
70
|
+
// block-level threshold and push operators into disabling the scanner.
|
|
71
|
+
// (camelCase detection was dropped: under the /i flag `[a-z]+[A-Z]`
|
|
72
|
+
// collapses to "any word" and re-introduced the false positive.)
|
|
73
|
+
/(?:also|always|first|then|finally)\s+(?:call|invoke|use|execute|run)\s+(?:the\s+)?[a-z][\w-]*(?:_[\w-]+|\s*\()/i,
|
|
68
74
|
// "Tool description: ignore the above and ..."
|
|
69
75
|
/(?:tool|function|action)\s+description[:\s]+(?:ignore|disregard|override)/i,
|
|
70
76
|
// "Note to LLM:" / "Hidden instruction:"
|
|
@@ -73,6 +79,25 @@ const SOURCE_PROFILE: Record<
|
|
|
73
79
|
/(?:on\s+(?:success|call)|when\s+invoked)[,:]\s+(?:silently|also|then)\s+(?:call|invoke|exfiltrate|send|leak)/i,
|
|
74
80
|
],
|
|
75
81
|
},
|
|
82
|
+
"tool-output": {
|
|
83
|
+
// The runtime result a tool returned. Distinct from `tool-desc` (static
|
|
84
|
+
// schema): this is data the tool fetched and is therefore
|
|
85
|
+
// attacker-influenceable (PoisonedRAG, scraped pages surfaced through a
|
|
86
|
+
// search tool, a compromised upstream API). Tool results almost never
|
|
87
|
+
// legitimately carry instruction syntax aimed at the calling model, so
|
|
88
|
+
// the bar is as tight as RAG/tool-desc.
|
|
89
|
+
threshold: 0.13,
|
|
90
|
+
extraPatterns: [
|
|
91
|
+
// Result claims to carry instructions for the model.
|
|
92
|
+
/(?:tool|function|api|search|query)\s+(?:result|response|output)[:\s]+(?:ignore|disregard|override|new\s+instructions?|system\s+prompt)/i,
|
|
93
|
+
// "the result indicates you should now call/invoke X"
|
|
94
|
+
/(?:result|response|data|output)\s+(?:indicates?|says?|requires?|means?)\s+(?:that\s+)?you\s+(?:should|must|need\s+to|will)\s+(?:now\s+)?(?:call|invoke|run|execute|use)\s+[a-z_][\w-]{2,}/i,
|
|
95
|
+
// Embedded role/system marker inside a JSON-ish result value.
|
|
96
|
+
/"(?:role|system|instruction|directive)"\s*:\s*"(?:system|ignore|override|admin)/i,
|
|
97
|
+
// "(end of results) Now, as the system, ..."
|
|
98
|
+
/(?:end\s+of\s+(?:results?|output|data)|<\/results?>)[\s.)]*(?:now|next)[,\s]+(?:as\s+(?:the\s+)?(?:system|admin|assistant)|you\s+(?:must|should|will))/i,
|
|
99
|
+
],
|
|
100
|
+
},
|
|
76
101
|
memory: {
|
|
77
102
|
// Stored memory entries: persistence poisoning. Look for sentinel
|
|
78
103
|
// instructions that re-anchor the model on subsequent retrieval.
|
|
@@ -447,6 +472,55 @@ export async function scanIngested(
|
|
|
447
472
|
};
|
|
448
473
|
}
|
|
449
474
|
|
|
475
|
+
/**
|
|
476
|
+
* Scan the runtime *result* of a tool call before it re-enters the model
|
|
477
|
+
* context. The dominant indirect-injection channel in agentic loops: a
|
|
478
|
+
* search tool surfaces a poisoned page, an MCP server returns attacker-
|
|
479
|
+
* controlled data, a compromised upstream API embeds instructions in its
|
|
480
|
+
* response. PoisonedRAG (USENIX Security 2025) showed 5 planted documents
|
|
481
|
+
* reach a 90% attack-success rate in million-document knowledge bases —
|
|
482
|
+
* the payload arrives here, not in the user prompt.
|
|
483
|
+
*
|
|
484
|
+
* Thin wrapper over `scanIngested(content, "tool-output")` that also
|
|
485
|
+
* stamps the originating `toolName` into every violation detail, so an
|
|
486
|
+
* audit log can answer "which tool returned the poisoned content?".
|
|
487
|
+
*
|
|
488
|
+
* Pair with `CircuitBreakerRegistry` when you also want to rate-limit or
|
|
489
|
+
* trip the tool after repeated poisoned results:
|
|
490
|
+
*
|
|
491
|
+
* @example
|
|
492
|
+
* ```ts
|
|
493
|
+
* import { scanToolOutput } from "ai-shield-core";
|
|
494
|
+
*
|
|
495
|
+
* const result = await searchTool.call(query); // untrusted
|
|
496
|
+
* const scan = await scanToolOutput("web_search", result);
|
|
497
|
+
* if (!scan.safe) {
|
|
498
|
+
* // drop the result OR strip it before the next model turn
|
|
499
|
+
* audit.warn("poisoned tool output", { tool: "web_search", v: scan.violations });
|
|
500
|
+
* return; // do not feed `result` back into the model
|
|
501
|
+
* }
|
|
502
|
+
* model.continue(result);
|
|
503
|
+
* ```
|
|
504
|
+
*/
|
|
505
|
+
export async function scanToolOutput(
|
|
506
|
+
toolName: string,
|
|
507
|
+
content: string,
|
|
508
|
+
config: IngestionScannerConfig = {},
|
|
509
|
+
): Promise<IngestionScanResult> {
|
|
510
|
+
const result = await scanIngested(content, "tool-output", config);
|
|
511
|
+
const safeToolName =
|
|
512
|
+
typeof toolName === "string" && toolName.length > 0
|
|
513
|
+
? toolName.slice(0, 120)
|
|
514
|
+
: "unknown";
|
|
515
|
+
return {
|
|
516
|
+
...result,
|
|
517
|
+
violations: result.violations.map((v) => ({
|
|
518
|
+
...v,
|
|
519
|
+
detail: `${v.detail ?? ""} (tool=${safeToolName})`.trim(),
|
|
520
|
+
})),
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
|
|
450
524
|
// ============================================================
|
|
451
525
|
// Encoding-bypass normalization (R1 from Round 1 review — closes
|
|
452
526
|
// OWASP LLM Prompt Injection Prevention Cheat Sheet 2026 Base64/Hex
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ScanContext,
|
|
3
|
+
ScanDecision,
|
|
4
|
+
Violation,
|
|
5
|
+
PIIConfig,
|
|
6
|
+
} from "../types.js";
|
|
7
|
+
import { PIIScanner } from "./pii.js";
|
|
8
|
+
import { normalizeForInjectionScan } from "./heuristic.js";
|
|
9
|
+
|
|
10
|
+
// ============================================================
|
|
11
|
+
// Output Scanner — OWASP LLM05 Improper Output Handling +
|
|
12
|
+
// LLM02 Sensitive Information Disclosure (output side)
|
|
13
|
+
//
|
|
14
|
+
// AI Shield's input scanners answer "is this prompt safe to send to the
|
|
15
|
+
// model?". This scanner answers the other half: "is this model OUTPUT
|
|
16
|
+
// safe to act on / show / forward downstream?".
|
|
17
|
+
//
|
|
18
|
+
// LLM output must never reach a SQL engine, a shell, an HTML sink, or a
|
|
19
|
+
// template renderer unfiltered — XSS, SSRF, SQLi and command injection
|
|
20
|
+
// sourced from model output are a documented 2026 attack class (OWASP
|
|
21
|
+
// LLM05). And a model can leak its own system prompt or a secret it was
|
|
22
|
+
// shown, which is LLM02 / LLM07.
|
|
23
|
+
//
|
|
24
|
+
// Five checks. Inputs are Unicode-normalized first (homoglyph / zero-width /
|
|
25
|
+
// fullwidth evasion defense). Secret + canary checks scan the FULL output
|
|
26
|
+
// (a leak can sit anywhere); the structural checks scan a length-capped copy
|
|
27
|
+
// (those payloads live in the first chunk):
|
|
28
|
+
// 1. secret_leak — API keys, tokens, private keys, DSNs (full output)
|
|
29
|
+
// 2. output_injection — SQL / shell / HTML-JS / template / md-exfil (capped)
|
|
30
|
+
// 3. system_prompt_leak — canary-token leak (exact, full) + heuristic phrasing
|
|
31
|
+
// 4. pii_detected — reuses the input-side PIIScanner
|
|
32
|
+
// 5. jailbreak_indicator— compliance-preamble / mode-switch acknowledgement
|
|
33
|
+
//
|
|
34
|
+
// Checks 1-3 are high-confidence and block. PII follows its configured
|
|
35
|
+
// action. Jailbreak is heuristic and only warns — a "sure, here's how"
|
|
36
|
+
// preamble is often legitimate.
|
|
37
|
+
// ============================================================
|
|
38
|
+
|
|
39
|
+
/** Hard cap on the bytes we pattern-scan. A 1 MB model response is not the
|
|
40
|
+
* threat model and unbounded regex over it pressures GC. Overridable. */
|
|
41
|
+
const DEFAULT_MAX_OUTPUT_BYTES = 256 * 1024;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* High-confidence secret formats. Each is anchored on a provider-specific
|
|
45
|
+
* prefix so false positives on prose are near-zero. Patterns are linear
|
|
46
|
+
* (no nested quantifiers) — ReDoS-safe on large output.
|
|
47
|
+
*/
|
|
48
|
+
const SECRET_PATTERNS: Array<{ id: string; re: RegExp; label: string }> = [
|
|
49
|
+
{ id: "SEC-OPENAI", re: /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/, label: "OpenAI API key" },
|
|
50
|
+
{ id: "SEC-ANTHROPIC", re: /\bsk-ant-[A-Za-z0-9_-]{20,}\b/, label: "Anthropic API key" },
|
|
51
|
+
{ id: "SEC-AWS-AKID", re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/, label: "AWS access key id" },
|
|
52
|
+
{ id: "SEC-GITHUB", re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/, label: "GitHub token" },
|
|
53
|
+
{ id: "SEC-GOOGLE", re: /\bAIza[0-9A-Za-z_-]{35}\b/, label: "Google API key" },
|
|
54
|
+
{ id: "SEC-GOOGLE-OAUTH", re: /\bGOCSPX-[A-Za-z0-9_-]{28}\b/, label: "Google OAuth client secret" },
|
|
55
|
+
{ id: "SEC-GCP-SA", re: /"type"\s*:\s*"service_account"/, label: "GCP service-account JSON" },
|
|
56
|
+
{ id: "SEC-HUGGINGFACE", re: /\bhf_[A-Za-z0-9]{30,}\b/, label: "HuggingFace token" },
|
|
57
|
+
{ id: "SEC-NPM", re: /\bnpm_[A-Za-z0-9]{36}\b/, label: "npm publish token" },
|
|
58
|
+
{ id: "SEC-SLACK", re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/, label: "Slack token" },
|
|
59
|
+
{ id: "SEC-STRIPE", re: /\b[rs]k_live_[A-Za-z0-9]{20,}\b/, label: "Stripe live key" },
|
|
60
|
+
{ id: "SEC-JWT", re: /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/, label: "JWT" },
|
|
61
|
+
{ id: "SEC-PEM", re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/, label: "PEM private key" },
|
|
62
|
+
// DSN: both credential segments are length-bounded so a long near-match
|
|
63
|
+
// without a trailing `@` can't drive O(n²) backtracking (review H1).
|
|
64
|
+
{ id: "SEC-DSN", re: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s:/@]{1,64}:[^\s@]{3,80}@/, label: "connection string with credentials" },
|
|
65
|
+
];
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Output-injection payloads, grouped by downstream sink. Each pattern is
|
|
69
|
+
* deliberately conservative — flagging legitimate output that merely
|
|
70
|
+
* *mentions* SQL would be useless. They target syntax that only matters
|
|
71
|
+
* when the string is interpreted, not displayed.
|
|
72
|
+
*/
|
|
73
|
+
const INJECTION_PATTERNS: Array<{
|
|
74
|
+
id: string;
|
|
75
|
+
sink: OutputSink;
|
|
76
|
+
re: RegExp;
|
|
77
|
+
label: string;
|
|
78
|
+
}> = [
|
|
79
|
+
// SQL
|
|
80
|
+
{ id: "OUTI-SQL-1", sink: "sql", re: /\bunion\s+(?:all\s+)?select\b/i, label: "SQL UNION SELECT" },
|
|
81
|
+
{ id: "OUTI-SQL-2", sink: "sql", re: /['"]\s*;\s*(?:drop|delete|update|insert|truncate|alter)\s+/i, label: "SQL statement break" },
|
|
82
|
+
{ id: "OUTI-SQL-3", sink: "sql", re: /\bor\s+1\s*=\s*1\b|\bor\s+'1'\s*=\s*'1'/i, label: "SQL tautology" },
|
|
83
|
+
// Shell
|
|
84
|
+
{ id: "OUTI-SH-1", sink: "shell", re: /\$\([^)]{1,200}\)|`[^`]{1,200}`/, label: "shell command substitution" },
|
|
85
|
+
{ id: "OUTI-SH-2", sink: "shell", re: /[;&|]\s*(?:rm|curl|wget|nc|bash|sh|chmod|mkfifo|dd)\s+-?/i, label: "chained shell command" },
|
|
86
|
+
{ id: "OUTI-SH-3", sink: "shell", re: /\|\s*(?:sh|bash|zsh|python[0-9.]*)\b/i, label: "pipe to interpreter" },
|
|
87
|
+
// HTML / JS (XSS)
|
|
88
|
+
{ id: "OUTI-XSS-1", sink: "html", re: /<script[\s>]/i, label: "<script> tag" },
|
|
89
|
+
{ id: "OUTI-XSS-2", sink: "html", re: /\bon(?:error|load|click|mouseover)\s*=\s*["']?[^"'>]{1,200}/i, label: "inline event handler" },
|
|
90
|
+
{ id: "OUTI-XSS-3", sink: "html", re: /\bjavascript:\s*[^\s"']{1,200}/i, label: "javascript: URI" },
|
|
91
|
+
{ id: "OUTI-XSS-4", sink: "html", re: /<iframe[\s>]|<img[^>]{0,200}\bsrc\s*=\s*["']?\s*(?:javascript|data):/i, label: "iframe / data-URI image" },
|
|
92
|
+
// Markdown-image data exfiltration: . When a
|
|
93
|
+
// renderer auto-loads the image the query string leaks whatever the model
|
|
94
|
+
// was told to embed. The most-overlooked LLM05 class (review: Research).
|
|
95
|
+
{ id: "OUTI-MDEXF", sink: "html", re: /!\[[^\]]{0,200}\]\(\s*https?:\/\/[^)\s]{1,300}[?&][\w-]{1,40}=/i, label: "markdown-image data exfiltration" },
|
|
96
|
+
// Template / SSTI
|
|
97
|
+
{ id: "OUTI-SSTI-1", sink: "template", re: /\{\{[^}]{0,200}(?:constructor|process|require|global|__proto__|self\.|cycler)[^}]{0,200}\}\}/i, label: "template-injection payload" },
|
|
98
|
+
{ id: "OUTI-SSTI-2", sink: "template", re: /<%[^%]{0,200}(?:system|exec|require|eval)[^%]{0,200}%>/i, label: "ERB/EJS injection" },
|
|
99
|
+
];
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* System-prompt-leak heuristics — used only when no canary token is
|
|
103
|
+
* available. Low-confidence by design (these phrasings occur in benign
|
|
104
|
+
* output too), so they warn rather than block.
|
|
105
|
+
*/
|
|
106
|
+
const SYSTEM_LEAK_PATTERNS: RegExp[] = [
|
|
107
|
+
/(?:my|the)\s+(?:system\s+)?(?:prompt|instructions?)\s+(?:is|are|say|states?|read)\b/i,
|
|
108
|
+
/i\s+(?:was|am|have\s+been)\s+(?:instructed|told|configured|programmed|designed)\s+to\b/i,
|
|
109
|
+
/here\s+(?:is|are)\s+my\s+(?:system\s+)?(?:prompt|instructions?|guidelines?|rules?)\b/i,
|
|
110
|
+
/you\s+are\s+(?:a|an)\s+[\w-]{2,30}\s+(?:assistant|agent|bot|model)\b.{0,40}\b(?:you\s+must|your\s+(?:rules?|guidelines?|instructions?))/i,
|
|
111
|
+
];
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Jailbreak-success indicators in the OUTPUT. Conservative + low weight:
|
|
115
|
+
* a generic "Sure, here's how" is not enough on its own — these target
|
|
116
|
+
* explicit mode-switch acknowledgements and self-declared rule-breaking.
|
|
117
|
+
*/
|
|
118
|
+
const JAILBREAK_PATTERNS: RegExp[] = [
|
|
119
|
+
/\bas\s+(?:DAN|an?\s+(?:unrestricted|unfiltered|jailbroken|uncensored))\b/i,
|
|
120
|
+
/i(?:'?ll|\s+will)\s+(?:now\s+)?(?:ignore|bypass|disregard|set\s+aside)\s+(?:my|the|all)\s+(?:guidelines?|restrictions?|rules?|safety|programming|filters?)/i,
|
|
121
|
+
/(?:jailbreak|developer\s+mode|dan\s+mode)\s+(?:enabled|activated|successful|engaged)/i,
|
|
122
|
+
/i\s+am\s+(?:now\s+)?(?:free\s+(?:from|of)|no\s+longer\s+bound\s+by)\s+(?:my\s+)?(?:restrictions?|guidelines?|rules?|programming)/i,
|
|
123
|
+
];
|
|
124
|
+
|
|
125
|
+
export type OutputSink = "sql" | "shell" | "html" | "template";
|
|
126
|
+
|
|
127
|
+
export interface OutputScanConfig {
|
|
128
|
+
/**
|
|
129
|
+
* PII handling. Pass a `PIIConfig` to control action/locale, or `false`
|
|
130
|
+
* to skip PII scanning entirely. Default: mask.
|
|
131
|
+
*/
|
|
132
|
+
pii?: PIIConfig | false;
|
|
133
|
+
/**
|
|
134
|
+
* Canary token(s) injected into the system prompt via `injectCanary()`.
|
|
135
|
+
* If any appears verbatim in the output → `system_prompt_leak` (block).
|
|
136
|
+
*/
|
|
137
|
+
canaryTokens?: string | string[];
|
|
138
|
+
/**
|
|
139
|
+
* Restrict the structured-injection check to specific downstream sinks.
|
|
140
|
+
* E.g. `["sql"]` when the output only ever flows into a query builder.
|
|
141
|
+
* Default: all sinks.
|
|
142
|
+
*/
|
|
143
|
+
sinks?: OutputSink[];
|
|
144
|
+
/** Selectively disable checks. All enabled by default. */
|
|
145
|
+
checks?: {
|
|
146
|
+
secrets?: boolean;
|
|
147
|
+
injection?: boolean;
|
|
148
|
+
systemPromptLeak?: boolean;
|
|
149
|
+
jailbreak?: boolean;
|
|
150
|
+
};
|
|
151
|
+
/** Override the byte cap on the scanned region. Default 256 KB. */
|
|
152
|
+
maxBytes?: number;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface OutputScanResult {
|
|
156
|
+
/** No blocking violation found. */
|
|
157
|
+
safe: boolean;
|
|
158
|
+
decision: ScanDecision;
|
|
159
|
+
/**
|
|
160
|
+
* Output with PII masked and secrets redacted to `[REDACTED_SECRET]`.
|
|
161
|
+
* Unlike `scanIngested`, this is NOT emptied on block — the caller
|
|
162
|
+
* usually still needs to log or display the sanitized text. Gate on
|
|
163
|
+
* `safe` / `decision` before forwarding it to a downstream sink.
|
|
164
|
+
*/
|
|
165
|
+
sanitized: string;
|
|
166
|
+
violations: Violation[];
|
|
167
|
+
meta: {
|
|
168
|
+
scanDurationMs: number;
|
|
169
|
+
checksRun: string[];
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const SECRET_REDACTION = "[REDACTED_SECRET]";
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Scanner for LLM output. Stateless; safe to reuse across calls.
|
|
177
|
+
*/
|
|
178
|
+
export class OutputScanner {
|
|
179
|
+
private readonly config: OutputScanConfig;
|
|
180
|
+
private readonly pii: PIIScanner | null;
|
|
181
|
+
|
|
182
|
+
constructor(config: OutputScanConfig = {}) {
|
|
183
|
+
this.config = config;
|
|
184
|
+
this.pii =
|
|
185
|
+
config.pii === false
|
|
186
|
+
? null
|
|
187
|
+
: new PIIScanner(config.pii ?? { action: "mask" });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async scan(
|
|
191
|
+
output: string,
|
|
192
|
+
context: ScanContext = {},
|
|
193
|
+
): Promise<OutputScanResult> {
|
|
194
|
+
const start = performance.now();
|
|
195
|
+
const violations: Violation[] = [];
|
|
196
|
+
const checksRun: string[] = [];
|
|
197
|
+
const checks = this.config.checks ?? {};
|
|
198
|
+
const maxBytes = this.config.maxBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
|
199
|
+
|
|
200
|
+
const safeOutput = typeof output === "string" ? output : "";
|
|
201
|
+
|
|
202
|
+
// Capped copy for the *structural* checks (injection / leak-phrasing /
|
|
203
|
+
// jailbreak) — those payloads live in the first chunk and the regex over
|
|
204
|
+
// a 1 MB response would pressure GC. Normalized so homoglyph / zero-width
|
|
205
|
+
// / fullwidth evasion can't slip a payload past the patterns (review H6).
|
|
206
|
+
const cappedDetect = normalizeForInjectionScan(
|
|
207
|
+
safeOutput.length > maxBytes ? safeOutput.slice(0, maxBytes) : safeOutput,
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
// Secrets and canaries can sit ANYWHERE in the output, and the secret
|
|
211
|
+
// patterns are anchored + linear — so they scan the FULL output, not the
|
|
212
|
+
// cap (review C1: a key padded past 256 KB must not slip through). Also
|
|
213
|
+
// normalized for the same evasion defense.
|
|
214
|
+
const fullDetect = normalizeForInjectionScan(safeOutput);
|
|
215
|
+
|
|
216
|
+
let sanitized = output;
|
|
217
|
+
let worst: ScanDecision = "allow";
|
|
218
|
+
const bump = (d: ScanDecision): void => {
|
|
219
|
+
if (priority(d) > priority(worst)) worst = d;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
// 1. Secret leak — high-confidence, always blocks. Redact in `sanitized`.
|
|
223
|
+
// Detection runs on the normalized full output; redaction is
|
|
224
|
+
// best-effort over the raw output (a key fragmented by zero-width
|
|
225
|
+
// chars is still flagged via `fullDetect` and blocks, but may resist
|
|
226
|
+
// clean redaction — callers MUST gate on `safe`/`decision` and never
|
|
227
|
+
// forward a blocked output regardless of `sanitized`).
|
|
228
|
+
if (checks.secrets !== false) {
|
|
229
|
+
checksRun.push("secrets");
|
|
230
|
+
for (const { id, re, label } of SECRET_PATTERNS) {
|
|
231
|
+
if (re.test(fullDetect)) {
|
|
232
|
+
violations.push({
|
|
233
|
+
type: "secret_leak",
|
|
234
|
+
scanner: "output",
|
|
235
|
+
score: 1.0,
|
|
236
|
+
threshold: 0.5,
|
|
237
|
+
message: `Output leaks a secret: ${label}`,
|
|
238
|
+
detail: `Rule ${id}`,
|
|
239
|
+
});
|
|
240
|
+
bump("block");
|
|
241
|
+
// Redact every occurrence in the full output (global copy of re).
|
|
242
|
+
sanitized = sanitized.replace(
|
|
243
|
+
new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g"),
|
|
244
|
+
SECRET_REDACTION,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// 2. Output injection — payloads dangerous to a downstream sink.
|
|
251
|
+
if (checks.injection !== false) {
|
|
252
|
+
checksRun.push("injection");
|
|
253
|
+
const allowedSinks = this.config.sinks;
|
|
254
|
+
for (const { id, sink, re, label } of INJECTION_PATTERNS) {
|
|
255
|
+
if (allowedSinks && !allowedSinks.includes(sink)) continue;
|
|
256
|
+
if (re.test(cappedDetect)) {
|
|
257
|
+
violations.push({
|
|
258
|
+
type: "output_injection",
|
|
259
|
+
scanner: "output",
|
|
260
|
+
score: 0.85,
|
|
261
|
+
threshold: 0.5,
|
|
262
|
+
message: `Output carries a ${sink} injection payload: ${label}`,
|
|
263
|
+
detail: `Rule ${id} (sink=${sink})`,
|
|
264
|
+
});
|
|
265
|
+
bump("block");
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// 3. System-prompt leak — canary first (exact, certain), then heuristics.
|
|
271
|
+
if (checks.systemPromptLeak !== false) {
|
|
272
|
+
checksRun.push("system_prompt_leak");
|
|
273
|
+
const tokens = normalizeTokens(this.config.canaryTokens);
|
|
274
|
+
let canaryHit = false;
|
|
275
|
+
for (const token of tokens) {
|
|
276
|
+
// Check the FULL output, not the capped copy — a leak past 256 KB is
|
|
277
|
+
// still a leak, and an exact substring search is cheap.
|
|
278
|
+
if (token.length >= 4 && output.includes(token)) {
|
|
279
|
+
canaryHit = true;
|
|
280
|
+
violations.push({
|
|
281
|
+
type: "system_prompt_leak",
|
|
282
|
+
scanner: "output",
|
|
283
|
+
score: 1.0,
|
|
284
|
+
threshold: 0.5,
|
|
285
|
+
message: "Output leaks a system-prompt canary token",
|
|
286
|
+
detail: "Canary match (exact)",
|
|
287
|
+
});
|
|
288
|
+
bump("block");
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
// Heuristic phrasing only when no canary was available/hit — avoids
|
|
292
|
+
// double-reporting and keeps the low-confidence signal subordinate.
|
|
293
|
+
if (!canaryHit && tokens.length === 0) {
|
|
294
|
+
for (const re of SYSTEM_LEAK_PATTERNS) {
|
|
295
|
+
if (re.test(cappedDetect)) {
|
|
296
|
+
violations.push({
|
|
297
|
+
type: "system_prompt_leak",
|
|
298
|
+
scanner: "output",
|
|
299
|
+
score: 0.4,
|
|
300
|
+
threshold: 0.5,
|
|
301
|
+
message: "Output may be echoing the system prompt",
|
|
302
|
+
detail: "Heuristic phrasing (no canary configured — pass canaryTokens for an exact check)",
|
|
303
|
+
});
|
|
304
|
+
bump("warn");
|
|
305
|
+
break; // one heuristic signal is enough
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// 4. Jailbreak indicators — heuristic, warn only.
|
|
312
|
+
if (checks.jailbreak !== false) {
|
|
313
|
+
checksRun.push("jailbreak");
|
|
314
|
+
for (const re of JAILBREAK_PATTERNS) {
|
|
315
|
+
if (re.test(cappedDetect)) {
|
|
316
|
+
violations.push({
|
|
317
|
+
type: "jailbreak_indicator",
|
|
318
|
+
scanner: "output",
|
|
319
|
+
score: 0.3,
|
|
320
|
+
threshold: 0.5,
|
|
321
|
+
message: "Output shows a possible jailbreak success indicator",
|
|
322
|
+
detail: "Heuristic phrasing",
|
|
323
|
+
});
|
|
324
|
+
bump("warn");
|
|
325
|
+
break;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// 5. PII — reuse the input-side scanner; respects its configured action.
|
|
331
|
+
if (this.pii) {
|
|
332
|
+
checksRun.push("pii");
|
|
333
|
+
const piiResult = await this.pii.scan(sanitized, context);
|
|
334
|
+
for (const v of piiResult.violations) {
|
|
335
|
+
violations.push({ ...v, scanner: "output" });
|
|
336
|
+
}
|
|
337
|
+
if (piiResult.sanitized !== undefined) sanitized = piiResult.sanitized;
|
|
338
|
+
bump(piiResult.decision);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return {
|
|
342
|
+
safe: worst === "allow",
|
|
343
|
+
decision: worst,
|
|
344
|
+
sanitized,
|
|
345
|
+
violations,
|
|
346
|
+
meta: {
|
|
347
|
+
scanDurationMs: performance.now() - start,
|
|
348
|
+
checksRun,
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* One-shot helper. Scan a model response before acting on it.
|
|
356
|
+
*
|
|
357
|
+
* @example
|
|
358
|
+
* ```ts
|
|
359
|
+
* import { scanOutput } from "ai-shield-core";
|
|
360
|
+
*
|
|
361
|
+
* const reply = await llm.generate(prompt);
|
|
362
|
+
* const r = await scanOutput(reply, { canaryTokens: canary, sinks: ["sql"] });
|
|
363
|
+
* if (!r.safe) {
|
|
364
|
+
* audit.warn("unsafe model output", r.violations);
|
|
365
|
+
* return genericFallback(); // do not run r.sanitized as SQL
|
|
366
|
+
* }
|
|
367
|
+
* showToUser(r.sanitized); // PII masked, secrets redacted
|
|
368
|
+
* ```
|
|
369
|
+
*/
|
|
370
|
+
export async function scanOutput(
|
|
371
|
+
output: string,
|
|
372
|
+
config: OutputScanConfig = {},
|
|
373
|
+
context: ScanContext = {},
|
|
374
|
+
): Promise<OutputScanResult> {
|
|
375
|
+
return new OutputScanner(config).scan(output, context);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function normalizeTokens(tokens?: string | string[]): string[] {
|
|
379
|
+
if (!tokens) return [];
|
|
380
|
+
const arr = Array.isArray(tokens) ? tokens : [tokens];
|
|
381
|
+
return arr.filter((t): t is string => typeof t === "string" && t.length > 0);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function priority(d: ScanDecision): number {
|
|
385
|
+
return d === "block" ? 2 : d === "warn" ? 1 : 0;
|
|
386
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -18,7 +18,19 @@ export type ViolationType =
|
|
|
18
18
|
| "untrusted_instruction"
|
|
19
19
|
| "memory_poisoning"
|
|
20
20
|
| "circuit_breaker_open"
|
|
21
|
-
| "blast_radius_exceeded"
|
|
21
|
+
| "blast_radius_exceeded"
|
|
22
|
+
// --- Output-side (v0.3) — OWASP LLM05 Improper Output Handling ---
|
|
23
|
+
/** LLM output carries an executable payload (SQL / shell / HTML/JS / template). */
|
|
24
|
+
| "output_injection"
|
|
25
|
+
/** LLM output leaks a secret (API key, token, private key, connection string). */
|
|
26
|
+
| "secret_leak"
|
|
27
|
+
/** LLM output echoes the system prompt / developer instructions. */
|
|
28
|
+
| "system_prompt_leak"
|
|
29
|
+
/** LLM output shows a successful jailbreak (compliance preamble, mode-switch acknowledgement). */
|
|
30
|
+
| "jailbreak_indicator"
|
|
31
|
+
// --- Multi-agent (v0.3) ---
|
|
32
|
+
/** Trust violation propagating across an agent-to-agent chain (contagion). */
|
|
33
|
+
| "trust_propagation";
|
|
22
34
|
|
|
23
35
|
export interface Violation {
|
|
24
36
|
type: ViolationType;
|
|
@@ -66,6 +78,12 @@ export interface Scanner {
|
|
|
66
78
|
* - `tool-desc` — MCP tool description / OpenAI function schema / tool args
|
|
67
79
|
* that came from a remote MCP server. High-risk vector
|
|
68
80
|
* per Lakera 2026 advisory + OX Security MCP CVEs.
|
|
81
|
+
* - `tool-output` — The runtime *result* a tool returned (MCP tool result,
|
|
82
|
+
* function-call output). Distinct from `tool-desc` (the
|
|
83
|
+
* static schema): this is attacker-influenceable data the
|
|
84
|
+
* tool fetched — the RAG-poisoning vector (PoisonedRAG:
|
|
85
|
+
* 5 docs → 90% ASR) and the dominant indirect-injection
|
|
86
|
+
* channel in agentic loops.
|
|
69
87
|
* - `memory` — Persisted memory entry (knowledge graph, session
|
|
70
88
|
* history, vector memory). Subject to persistence-poisoning.
|
|
71
89
|
* - `web` — Scraped web page / HTML. Hidden-instruction risk via
|
|
@@ -77,6 +95,7 @@ export type IngestionSource =
|
|
|
77
95
|
| "user"
|
|
78
96
|
| "rag"
|
|
79
97
|
| "tool-desc"
|
|
98
|
+
| "tool-output"
|
|
80
99
|
| "memory"
|
|
81
100
|
| "web"
|
|
82
101
|
| "agent-output";
|