ai-shield-core 0.2.0 → 0.4.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 +62 -7
- 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 +66 -5
- package/dist/scanner/heuristic.d.ts.map +1 -1
- package/dist/scanner/heuristic.js +382 -11
- 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 +327 -0
- package/dist/types.d.ts +18 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +7 -3
- package/src/context/wrap-context.ts +171 -0
- package/src/cost/pricing.ts +15 -7
- package/src/index.ts +91 -6
- package/src/judge/async-judge.ts +254 -0
- package/src/scanner/heuristic.ts +399 -11
- package/src/scanner/ingestion.ts +76 -2
- package/src/scanner/output.ts +418 -0
- package/src/types.ts +20 -1
|
@@ -0,0 +1,418 @@
|
|
|
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. Detection runs on the
|
|
223
|
+
// normalized full output (so a key fragmented by zero-width / homoglyph
|
|
224
|
+
// chars is still flagged), and redaction MUST guarantee the live secret
|
|
225
|
+
// never survives in `sanitized` — not just best-effort.
|
|
226
|
+
if (checks.secrets !== false) {
|
|
227
|
+
checksRun.push("secrets");
|
|
228
|
+
const matchedSecretREs: RegExp[] = [];
|
|
229
|
+
for (const { id, re, label } of SECRET_PATTERNS) {
|
|
230
|
+
if (re.test(fullDetect)) {
|
|
231
|
+
violations.push({
|
|
232
|
+
type: "secret_leak",
|
|
233
|
+
scanner: "output",
|
|
234
|
+
score: 1.0,
|
|
235
|
+
threshold: 0.5,
|
|
236
|
+
message: `Output leaks a secret: ${label}`,
|
|
237
|
+
detail: `Rule ${id}`,
|
|
238
|
+
});
|
|
239
|
+
bump("block");
|
|
240
|
+
matchedSecretREs.push(re);
|
|
241
|
+
// First pass: redact every occurrence in the raw output. This is the
|
|
242
|
+
// clean case and preserves the surrounding formatting.
|
|
243
|
+
sanitized = sanitized.replace(globalCopy(re), SECRET_REDACTION);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// Scrub-on-block guarantee: detection saw the secret in the NORMALIZED
|
|
247
|
+
// text, but the raw `.replace()` above can miss a key that was split by
|
|
248
|
+
// invisible chars ("sk-ant-...<ZWSP>...") — the raw form doesn't match
|
|
249
|
+
// the anchored pattern, so the live key would survive in `sanitized`.
|
|
250
|
+
// If any matched pattern still hits the normalized sanitized output, the
|
|
251
|
+
// evasion-split key got through: strip the zero-width chars (they are
|
|
252
|
+
// invisible, so this never alters how benign text reads) so the key
|
|
253
|
+
// collapses, then redact again. The result: `sanitized` is free of the
|
|
254
|
+
// live secret regardless of the evasion used.
|
|
255
|
+
if (matchedSecretREs.length > 0) {
|
|
256
|
+
const stillLeaks = (): boolean =>
|
|
257
|
+
matchedSecretREs.some((re) =>
|
|
258
|
+
re.test(normalizeForInjectionScan(sanitized)),
|
|
259
|
+
);
|
|
260
|
+
if (stillLeaks()) {
|
|
261
|
+
sanitized = stripZeroWidth(sanitized);
|
|
262
|
+
for (const re of matchedSecretREs) {
|
|
263
|
+
sanitized = sanitized.replace(globalCopy(re), SECRET_REDACTION);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// 2. Output injection — payloads dangerous to a downstream sink.
|
|
270
|
+
if (checks.injection !== false) {
|
|
271
|
+
checksRun.push("injection");
|
|
272
|
+
const allowedSinks = this.config.sinks;
|
|
273
|
+
for (const { id, sink, re, label } of INJECTION_PATTERNS) {
|
|
274
|
+
if (allowedSinks && !allowedSinks.includes(sink)) continue;
|
|
275
|
+
if (re.test(cappedDetect)) {
|
|
276
|
+
violations.push({
|
|
277
|
+
type: "output_injection",
|
|
278
|
+
scanner: "output",
|
|
279
|
+
score: 0.85,
|
|
280
|
+
threshold: 0.5,
|
|
281
|
+
message: `Output carries a ${sink} injection payload: ${label}`,
|
|
282
|
+
detail: `Rule ${id} (sink=${sink})`,
|
|
283
|
+
});
|
|
284
|
+
bump("block");
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// 3. System-prompt leak — canary first (exact, certain), then heuristics.
|
|
290
|
+
if (checks.systemPromptLeak !== false) {
|
|
291
|
+
checksRun.push("system_prompt_leak");
|
|
292
|
+
const tokens = normalizeTokens(this.config.canaryTokens);
|
|
293
|
+
let canaryHit = false;
|
|
294
|
+
for (const token of tokens) {
|
|
295
|
+
// Check the FULL output, not the capped copy — a leak past 256 KB is
|
|
296
|
+
// still a leak, and an exact substring search is cheap.
|
|
297
|
+
if (token.length >= 4 && output.includes(token)) {
|
|
298
|
+
canaryHit = true;
|
|
299
|
+
violations.push({
|
|
300
|
+
type: "system_prompt_leak",
|
|
301
|
+
scanner: "output",
|
|
302
|
+
score: 1.0,
|
|
303
|
+
threshold: 0.5,
|
|
304
|
+
message: "Output leaks a system-prompt canary token",
|
|
305
|
+
detail: "Canary match (exact)",
|
|
306
|
+
});
|
|
307
|
+
bump("block");
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// Heuristic phrasing only when no canary was available/hit — avoids
|
|
311
|
+
// double-reporting and keeps the low-confidence signal subordinate.
|
|
312
|
+
if (!canaryHit && tokens.length === 0) {
|
|
313
|
+
for (const re of SYSTEM_LEAK_PATTERNS) {
|
|
314
|
+
if (re.test(cappedDetect)) {
|
|
315
|
+
violations.push({
|
|
316
|
+
type: "system_prompt_leak",
|
|
317
|
+
scanner: "output",
|
|
318
|
+
score: 0.4,
|
|
319
|
+
threshold: 0.5,
|
|
320
|
+
message: "Output may be echoing the system prompt",
|
|
321
|
+
detail: "Heuristic phrasing (no canary configured — pass canaryTokens for an exact check)",
|
|
322
|
+
});
|
|
323
|
+
bump("warn");
|
|
324
|
+
break; // one heuristic signal is enough
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// 4. Jailbreak indicators — heuristic, warn only.
|
|
331
|
+
if (checks.jailbreak !== false) {
|
|
332
|
+
checksRun.push("jailbreak");
|
|
333
|
+
for (const re of JAILBREAK_PATTERNS) {
|
|
334
|
+
if (re.test(cappedDetect)) {
|
|
335
|
+
violations.push({
|
|
336
|
+
type: "jailbreak_indicator",
|
|
337
|
+
scanner: "output",
|
|
338
|
+
score: 0.3,
|
|
339
|
+
threshold: 0.5,
|
|
340
|
+
message: "Output shows a possible jailbreak success indicator",
|
|
341
|
+
detail: "Heuristic phrasing",
|
|
342
|
+
});
|
|
343
|
+
bump("warn");
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// 5. PII — reuse the input-side scanner; respects its configured action.
|
|
350
|
+
if (this.pii) {
|
|
351
|
+
checksRun.push("pii");
|
|
352
|
+
const piiResult = await this.pii.scan(sanitized, context);
|
|
353
|
+
for (const v of piiResult.violations) {
|
|
354
|
+
violations.push({ ...v, scanner: "output" });
|
|
355
|
+
}
|
|
356
|
+
if (piiResult.sanitized !== undefined) sanitized = piiResult.sanitized;
|
|
357
|
+
bump(piiResult.decision);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
safe: worst === "allow",
|
|
362
|
+
decision: worst,
|
|
363
|
+
sanitized,
|
|
364
|
+
violations,
|
|
365
|
+
meta: {
|
|
366
|
+
scanDurationMs: performance.now() - start,
|
|
367
|
+
checksRun,
|
|
368
|
+
},
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* One-shot helper. Scan a model response before acting on it.
|
|
375
|
+
*
|
|
376
|
+
* @example
|
|
377
|
+
* ```ts
|
|
378
|
+
* import { scanOutput } from "ai-shield-core";
|
|
379
|
+
*
|
|
380
|
+
* const reply = await llm.generate(prompt);
|
|
381
|
+
* const r = await scanOutput(reply, { canaryTokens: canary, sinks: ["sql"] });
|
|
382
|
+
* if (!r.safe) {
|
|
383
|
+
* audit.warn("unsafe model output", r.violations);
|
|
384
|
+
* return genericFallback(); // do not run r.sanitized as SQL
|
|
385
|
+
* }
|
|
386
|
+
* showToUser(r.sanitized); // PII masked, secrets redacted
|
|
387
|
+
* ```
|
|
388
|
+
*/
|
|
389
|
+
export async function scanOutput(
|
|
390
|
+
output: string,
|
|
391
|
+
config: OutputScanConfig = {},
|
|
392
|
+
context: ScanContext = {},
|
|
393
|
+
): Promise<OutputScanResult> {
|
|
394
|
+
return new OutputScanner(config).scan(output, context);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function normalizeTokens(tokens?: string | string[]): string[] {
|
|
398
|
+
if (!tokens) return [];
|
|
399
|
+
const arr = Array.isArray(tokens) ? tokens : [tokens];
|
|
400
|
+
return arr.filter((t): t is string => typeof t === "string" && t.length > 0);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function priority(d: ScanDecision): number {
|
|
404
|
+
return d === "block" ? 2 : d === "warn" ? 1 : 0;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** Return a global-flagged copy of `re` (idempotent if already global). */
|
|
408
|
+
function globalCopy(re: RegExp): RegExp {
|
|
409
|
+
return new RegExp(re.source, re.flags.includes("g") ? re.flags : re.flags + "g");
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Zero-width / BOM chars (U+200B..U+200D, U+2060, U+FEFF) used to fragment a
|
|
413
|
+
// secret across a pattern boundary. Stripping them is safe in `sanitized`
|
|
414
|
+
// because they render as nothing — benign visible text is unaffected.
|
|
415
|
+
const OUTPUT_ZERO_WIDTH_RE = /[\u200B-\u200D\u2060\uFEFF]/g;
|
|
416
|
+
function stripZeroWidth(s: string): string {
|
|
417
|
+
return s.replace(OUTPUT_ZERO_WIDTH_RE, "");
|
|
418
|
+
}
|
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";
|