ai-shield-core 0.1.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.
Files changed (76) hide show
  1. package/dist/audit/logger.d.ts.map +1 -1
  2. package/dist/audit/logger.js +13 -14
  3. package/dist/audit/types.js +1 -2
  4. package/dist/cache/lru.js +1 -5
  5. package/dist/canary/memory.d.ts +75 -0
  6. package/dist/canary/memory.d.ts.map +1 -0
  7. package/dist/canary/memory.js +194 -0
  8. package/dist/context/wrap-context.d.ts +169 -0
  9. package/dist/context/wrap-context.d.ts.map +1 -0
  10. package/dist/context/wrap-context.js +278 -0
  11. package/dist/cost/anomaly.js +1 -4
  12. package/dist/cost/pricing.d.ts.map +1 -1
  13. package/dist/cost/pricing.js +26 -19
  14. package/dist/cost/tracker.d.ts +19 -1
  15. package/dist/cost/tracker.d.ts.map +1 -1
  16. package/dist/cost/tracker.js +27 -10
  17. package/dist/index.d.ts +34 -3
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +55 -37
  20. package/dist/judge/async-judge.d.ts +85 -0
  21. package/dist/judge/async-judge.d.ts.map +1 -0
  22. package/dist/judge/async-judge.js +146 -0
  23. package/dist/policy/circuit-breaker.d.ts +70 -0
  24. package/dist/policy/circuit-breaker.d.ts.map +1 -0
  25. package/dist/policy/circuit-breaker.js +376 -0
  26. package/dist/policy/engine.js +1 -5
  27. package/dist/policy/tools.js +4 -8
  28. package/dist/scanner/canary.js +4 -8
  29. package/dist/scanner/chain.js +1 -5
  30. package/dist/scanner/heuristic.d.ts +27 -0
  31. package/dist/scanner/heuristic.d.ts.map +1 -1
  32. package/dist/scanner/heuristic.js +118 -7
  33. package/dist/scanner/ingestion.d.ts +147 -0
  34. package/dist/scanner/ingestion.d.ts.map +1 -0
  35. package/dist/scanner/ingestion.js +520 -0
  36. package/dist/scanner/output.d.ts +73 -0
  37. package/dist/scanner/output.d.ts.map +1 -0
  38. package/dist/scanner/output.js +297 -0
  39. package/dist/scanner/pii.d.ts.map +1 -1
  40. package/dist/scanner/pii.js +24 -12
  41. package/dist/shield.d.ts.map +1 -1
  42. package/dist/shield.js +34 -26
  43. package/dist/types.d.ts +156 -2
  44. package/dist/types.d.ts.map +1 -1
  45. package/dist/types.js +1 -2
  46. package/package.json +4 -3
  47. package/src/audit/logger.ts +6 -1
  48. package/src/canary/memory.ts +259 -0
  49. package/src/context/wrap-context.ts +475 -0
  50. package/src/cost/pricing.ts +21 -9
  51. package/src/cost/tracker.ts +35 -1
  52. package/src/index.ts +113 -2
  53. package/src/judge/async-judge.ts +254 -0
  54. package/src/policy/circuit-breaker.ts +449 -0
  55. package/src/scanner/heuristic.ts +125 -2
  56. package/src/scanner/ingestion.ts +624 -0
  57. package/src/scanner/output.ts +386 -0
  58. package/src/scanner/pii.ts +21 -7
  59. package/src/shield.ts +15 -2
  60. package/src/types.ts +194 -2
  61. package/tsconfig.json +2 -1
  62. package/dist/audit/logger.js.map +0 -1
  63. package/dist/audit/types.js.map +0 -1
  64. package/dist/cache/lru.js.map +0 -1
  65. package/dist/cost/anomaly.js.map +0 -1
  66. package/dist/cost/pricing.js.map +0 -1
  67. package/dist/cost/tracker.js.map +0 -1
  68. package/dist/index.js.map +0 -1
  69. package/dist/policy/engine.js.map +0 -1
  70. package/dist/policy/tools.js.map +0 -1
  71. package/dist/scanner/canary.js.map +0 -1
  72. package/dist/scanner/chain.js.map +0 -1
  73. package/dist/scanner/heuristic.js.map +0 -1
  74. package/dist/scanner/pii.js.map +0 -1
  75. package/dist/shield.js.map +0 -1
  76. package/dist/types.js.map +0 -1
@@ -0,0 +1,624 @@
1
+ import type {
2
+ Scanner,
3
+ ScannerResult,
4
+ ScanContext,
5
+ Violation,
6
+ IngestionSource,
7
+ TrustTier,
8
+ } from "../types.js";
9
+ import { HeuristicScanner, normalizeForInjectionScan } from "./heuristic.js";
10
+
11
+ // ============================================================
12
+ // Ingestion Scanner — Indirect Prompt Injection (IPI) Defense
13
+ //
14
+ // Scans non-user content (RAG chunks, MCP tool descriptions, stored
15
+ // memory facts, scraped web pages, agent-to-agent messages) for
16
+ // instruction-shaped payloads BEFORE they enter the model context.
17
+ //
18
+ // Per Lakera 2026 incident catalog + OWASP LLM01:2025, indirect
19
+ // injection is now the dominant attack class — >55% of observed
20
+ // incidents arrive through trusted-looking data channels. Direct user
21
+ // injection is the minority case.
22
+ //
23
+ // This scanner runs the existing heuristic patterns at a stricter
24
+ // threshold AND adds source-specific patterns the user channel does
25
+ // not see (HTML-comment instructions, tool-description override,
26
+ // memory-entry steering).
27
+ // ============================================================
28
+
29
+ /**
30
+ * Per-source threshold + extra patterns. Tighter than the user-channel
31
+ * default because data sources almost never need instruction syntax —
32
+ * the presence of one in retrieved content is itself a signal.
33
+ */
34
+ const SOURCE_PROFILE: Record<
35
+ IngestionSource,
36
+ { threshold: number; extraPatterns: RegExp[] }
37
+ > = {
38
+ user: {
39
+ // For symmetry — a caller may pass source="user" through scanIngested().
40
+ // Falls back to normal heuristic strictness.
41
+ threshold: 0.3,
42
+ extraPatterns: [],
43
+ },
44
+ rag: {
45
+ // Retrieved docs basically never legitimately contain "ignore previous
46
+ // instructions" type wording. Strict. Patterns here are ReDoS-bounded —
47
+ // hidden-comment + CSS detection are done via slice-then-test below in
48
+ // `runStructuralIngestionScan()` so we never run two `[^]*?` wildcards
49
+ // back-to-back over attacker-controlled input.
50
+ threshold: 0.15,
51
+ extraPatterns: [
52
+ // "AI assistant note: ..." style trojan headers.
53
+ /(?:AI\s+(?:assistant|model)\s+(?:note|instruction|directive)|attention\s+(?:AI|model|assistant))[:\s]+/i,
54
+ // Document-claims-to-be-system marker.
55
+ /this\s+document\s+(?:is|contains|provides)\s+(?:your|the)\s+(?:new\s+)?(?:instructions?|system\s+prompt|directives?)/i,
56
+ ],
57
+ },
58
+ "tool-desc": {
59
+ // MCP tool descriptions / function schemas: any imperative aimed at
60
+ // the calling model is suspicious. OX Security MCP advisory + LiteLLM
61
+ // CVE-2025-69256 class.
62
+ threshold: 0.12,
63
+ extraPatterns: [
64
+ // "Before using this tool, you must ..." / "After calling, also call X"
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 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,
74
+ // "Tool description: ignore the above and ..."
75
+ /(?:tool|function|action)\s+description[:\s]+(?:ignore|disregard|override)/i,
76
+ // "Note to LLM:" / "Hidden instruction:"
77
+ /(?:note|hidden\s+(?:instruction|directive|note))\s+to\s+(?:LLM|model|assistant|AI|agent)[:\s]/i,
78
+ // Tool args carrying meta-instructions.
79
+ /(?:on\s+(?:success|call)|when\s+invoked)[,:]\s+(?:silently|also|then)\s+(?:call|invoke|exfiltrate|send|leak)/i,
80
+ ],
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
+ },
101
+ memory: {
102
+ // Stored memory entries: persistence poisoning. Look for sentinel
103
+ // instructions that re-anchor the model on subsequent retrieval.
104
+ threshold: 0.18,
105
+ extraPatterns: [
106
+ // "Remember:" / "Important note for next session:"
107
+ /(?:remember|important|critical)\s+(?:note|instruction|directive)\s+(?:for\s+(?:next|future|all)\s+(?:sessions?|conversations?|calls?))[:\s]/i,
108
+ // "Whenever the user asks X, do Y"
109
+ /(?:whenever|every\s+time)\s+(?:the\s+user|a\s+user|someone)\s+(?:asks|says|mentions|requests)\s+.{1,80}?[,:]\s*(?:you\s+(?:must|should|will|need)|always)/i,
110
+ // "User's true preference is ..." (steering attempts).
111
+ /(?:user(?:'s|s)?\s+(?:real|true|actual|hidden)\s+(?:preference|intent|goal|name|identity))/i,
112
+ // "Override default behavior when ..."
113
+ /override\s+(?:default|standard|normal)\s+(?:behavior|response|policy)/i,
114
+ ],
115
+ },
116
+ web: {
117
+ // Scraped web — same as RAG but also catch markdown-link hijacks.
118
+ // HTML-comment + CSS-hidden detection lives in
119
+ // `runStructuralIngestionScan()` (slice-then-test, ReDoS-bounded).
120
+ threshold: 0.15,
121
+ extraPatterns: [
122
+ // Markdown-link with instruction-shaped anchor text.
123
+ /\[(?:ignore|disregard|override|system\s+(?:prompt|message))[^\]]{0,200}\]\([^)]{0,500}\)/i,
124
+ // ARIA / data-* attributes leaking instructions.
125
+ /(?:aria-label|alt|title|data-[a-z-]{0,40})\s*=\s*["'][^"']{0,500}(ignore\s+previous|new\s+instruction|system\s+prompt|override)/i,
126
+ ],
127
+ },
128
+ "agent-output": {
129
+ // Output of one agent feeding another: multi-agent contagion.
130
+ // Treat like RAG but also catch "tell next agent to ..." patterns.
131
+ threshold: 0.18,
132
+ extraPatterns: [
133
+ /(?:tell|instruct|forward\s+to)\s+(?:the\s+)?(?:next|downstream|receiving|other)\s+(?:agent|model|assistant)\s+to/i,
134
+ /(?:on\s+behalf\s+of|impersonating)\s+(?:the\s+)?(?:user|admin|system|owner)/i,
135
+ /(?:relay|pass|propagate)\s+(?:these|the\s+following)\s+(?:instructions?|directives?|orders?)/i,
136
+ ],
137
+ },
138
+ };
139
+
140
+ /**
141
+ * Default trust-tier inferred from source.
142
+ * `user` is still untrusted in this library's threat model — a user can
143
+ * inject too — but `system` is reserved for content the developer
144
+ * controls and labels via `wrapContext()`. Every ingestion source
145
+ * (including `user`) therefore returns `"untrusted"` by default; the
146
+ * parameter is kept on the signature so future per-source overrides
147
+ * (e.g. an installer marking a specific source as trusted) don't
148
+ * require a breaking API change.
149
+ */
150
+ export function trustTierForSource(_source: IngestionSource): TrustTier {
151
+ return "untrusted";
152
+ }
153
+
154
+ // --- ReDoS-safe structural scan helpers ---
155
+
156
+ /**
157
+ * Hidden-comment + CSS-hidden detection done as bounded slice-then-test
158
+ * rather than a compound `[^]*?...[^]*?` regex (which back-tracks
159
+ * quadratically on attacker-controlled input that omits the terminator).
160
+ * See Critic C1 (round 1 review) — unterminated `<!--` of 50 KB stalled
161
+ * the original implementation.
162
+ *
163
+ * Each detector takes the already-NFKC-normalized input and returns
164
+ * `null` (clean) or a `Violation`.
165
+ */
166
+ function runStructuralIngestionScan(
167
+ normalized: string,
168
+ source: IngestionSource,
169
+ threshold: number,
170
+ ): Violation[] {
171
+ if (source !== "rag" && source !== "web") return [];
172
+ const violations: Violation[] = [];
173
+ const COMMENT_WINDOW = 2048;
174
+ const KEYWORD_RE =
175
+ /ignore|disregard|override|forget|system\s+prompt|new\s+instructions?/i;
176
+
177
+ // 1. HTML comment hidden instruction.
178
+ let commentStart = 0;
179
+ let commentMatchCount = 0;
180
+ while (commentStart !== -1 && commentMatchCount < 8) {
181
+ commentStart = normalized.indexOf("<!--", commentStart);
182
+ if (commentStart === -1) break;
183
+ const window = normalized.slice(
184
+ commentStart + 4,
185
+ commentStart + 4 + COMMENT_WINDOW,
186
+ );
187
+ if (KEYWORD_RE.test(window)) {
188
+ violations.push({
189
+ type: "ingested_injection",
190
+ scanner: "ingestion",
191
+ score: 0.4,
192
+ threshold,
193
+ message: `HTML-comment hidden instruction in ${source} content`,
194
+ detail: `Pattern: <!-- ... ignore|override|... (window 2KB)`,
195
+ });
196
+ commentMatchCount += 1;
197
+ }
198
+ commentStart += 4;
199
+ }
200
+
201
+ // 2. CSS-hidden style attribute carrying instruction-shaped neighbour.
202
+ //
203
+ // Round 2 Critic M-NEW-2: a single `.exec()` would only find the FIRST
204
+ // `style=` attribute. An attacker placing a benign `style="display:block"`
205
+ // first and a malicious `style="display:none"` later would slip through.
206
+ // Iterate all matches via the `/g` flag, capped at 16 to bound the work
207
+ // on adversarial input that floods style attributes.
208
+ const STYLE_HIDDEN_RE =
209
+ /style\s*=\s*["'][^"']{0,300}(?:display\s*:\s*none|visibility\s*:\s*hidden|font-size\s*:\s*0)[^"']{0,300}["']/gi;
210
+ let styleMatchCount = 0;
211
+ let styleMatch: RegExpExecArray | null;
212
+ while (
213
+ (styleMatch = STYLE_HIDDEN_RE.exec(normalized)) !== null &&
214
+ styleMatchCount < 16
215
+ ) {
216
+ styleMatchCount += 1;
217
+ const tail = normalized.slice(
218
+ styleMatch.index + styleMatch[0].length,
219
+ styleMatch.index + styleMatch[0].length + 500,
220
+ );
221
+ if (/ignore|override|system|instruction/i.test(tail)) {
222
+ violations.push({
223
+ type: "ingested_injection",
224
+ scanner: "ingestion",
225
+ score: 0.4,
226
+ threshold,
227
+ message: `CSS-hidden instruction in ${source} content`,
228
+ detail: `Pattern: style="display:none ... ignore|override|... (window 500B)`,
229
+ });
230
+ }
231
+ }
232
+
233
+ return violations;
234
+ }
235
+
236
+ /**
237
+ * Result of `scanIngested()`.
238
+ *
239
+ * Shape parallels `ScanResult` from `chain.ts` so callers can treat
240
+ * both interchangeably.
241
+ */
242
+ export interface IngestionScanResult {
243
+ safe: boolean;
244
+ decision: "allow" | "warn" | "block";
245
+ /**
246
+ * Sanitized output. When `decision === "block"` this is the empty
247
+ * string — the original content was deemed unsafe and the field name
248
+ * "sanitized" would otherwise mislead callers into using poisoned
249
+ * content. Use the source `content` argument if you need the raw input
250
+ * for logging or quarantine.
251
+ */
252
+ sanitized: string;
253
+ violations: Violation[];
254
+ source: IngestionSource;
255
+ meta: {
256
+ scanDurationMs: number;
257
+ scannersRun: string[];
258
+ /** Number of extra source-specific patterns that fired. */
259
+ sourceSpecificHits: number;
260
+ /**
261
+ * Always `false` from `scanIngested()` — ingestion scans don't go
262
+ * through the LRU cache. Field is present so callers can write a
263
+ * single result-handler for both `ScanResult` and `IngestionScanResult`.
264
+ */
265
+ cached: boolean;
266
+ };
267
+ }
268
+
269
+ export interface IngestionScannerConfig {
270
+ /** Override the per-source threshold lookup. */
271
+ threshold?: number;
272
+ /**
273
+ * Additional custom patterns to merge with the source profile's
274
+ * `extraPatterns`. Useful for org-specific markers.
275
+ */
276
+ customPatterns?: RegExp[];
277
+ /**
278
+ * Force the underlying heuristic scanner to a different strictness
279
+ * (default "high" because ingestion is always tighter than user input).
280
+ */
281
+ strictness?: "low" | "medium" | "high";
282
+ }
283
+
284
+ /**
285
+ * Scanner implementation. Composable into a `ScannerChain` when the
286
+ * caller wants ingestion to participate in the main scan flow rather
287
+ * than be invoked via the standalone `scanIngested()` helper.
288
+ *
289
+ * The scanner reads the `source` from `ScanContext` (or treats input
290
+ * as `"user"` when missing) and applies the source-specific profile.
291
+ */
292
+ export class IngestionScanner implements Scanner {
293
+ readonly name = "ingestion";
294
+ private readonly threshold: number | undefined;
295
+ private readonly customPatterns: RegExp[];
296
+ private readonly heuristic: HeuristicScanner;
297
+
298
+ constructor(config: IngestionScannerConfig = {}) {
299
+ this.threshold = config.threshold;
300
+ this.customPatterns = config.customPatterns ?? [];
301
+ this.heuristic = new HeuristicScanner({
302
+ strictness: config.strictness ?? "high",
303
+ });
304
+ }
305
+
306
+ async scan(input: string, context: ScanContext): Promise<ScannerResult> {
307
+ const source = context.source ?? "user";
308
+ const profile = SOURCE_PROFILE[source];
309
+ const effectiveThreshold = this.threshold ?? profile.threshold;
310
+
311
+ const start = performance.now();
312
+ const violations: Violation[] = [];
313
+
314
+ // 1. Run the base heuristic scanner at high strictness. We respect its
315
+ // own decision (it includes structural signals that don't surface
316
+ // as individual violations) and re-tag the violations as
317
+ // `ingested_injection` so downstream code can filter.
318
+ const heuristicResult = await this.heuristic.scan(input, context);
319
+ for (const v of heuristicResult.violations) {
320
+ violations.push({
321
+ ...v,
322
+ type: "ingested_injection",
323
+ scanner: this.name,
324
+ detail: `${v.detail ?? ""} (source=${source})`.trim(),
325
+ });
326
+ }
327
+
328
+ // 2. Run source-specific patterns against the normalized input so the
329
+ // same Unicode-evasion defense the user channel gets applies here.
330
+ const normalized = normalizeForInjectionScan(input);
331
+ const sourcePatterns = [...profile.extraPatterns, ...this.customPatterns];
332
+ let sourceScore = 0;
333
+ for (const pattern of sourcePatterns) {
334
+ if (pattern.test(normalized)) {
335
+ sourceScore += 0.4;
336
+ violations.push({
337
+ type: "ingested_injection",
338
+ scanner: this.name,
339
+ score: 0.4,
340
+ threshold: effectiveThreshold,
341
+ message: `Indirect injection pattern in ${source} content`,
342
+ detail: `Pattern: ${pattern.source.slice(0, 80)}`,
343
+ });
344
+ }
345
+ }
346
+ // 2b. Structural slice-then-test scans for `rag` + `web` (ReDoS-safe
347
+ // replacement for the old compound HTML-comment + CSS-hidden
348
+ // patterns).
349
+ const structural = runStructuralIngestionScan(
350
+ normalized,
351
+ source,
352
+ effectiveThreshold,
353
+ );
354
+ for (const v of structural) {
355
+ sourceScore += 0.4;
356
+ violations.push(v);
357
+ }
358
+ // 2c. Encoding-bypass: attackers wrap an injection in Base64 / Hex /
359
+ // percent-encoding and ask the model to "decode this". A single
360
+ // decode pass over the input flushes the most common bypasses
361
+ // documented in OWASP LLM Prompt Injection Prevention Cheat
362
+ // Sheet 2026. Only run when the input "looks encoded" to keep
363
+ // false-positive load low on plain prose.
364
+ const decoded = tryDecodeObfuscation(input);
365
+ if (decoded && decoded !== input) {
366
+ const decodedNormalized = normalizeForInjectionScan(decoded);
367
+ const decodedHeuristic = await this.heuristic.scan(decoded, context);
368
+ if (decodedHeuristic.decision !== "allow") {
369
+ for (const v of decodedHeuristic.violations) {
370
+ violations.push({
371
+ ...v,
372
+ type: "ingested_injection",
373
+ scanner: this.name,
374
+ detail:
375
+ `${v.detail ?? ""} (source=${source}, layer=decoded)`.trim(),
376
+ });
377
+ }
378
+ sourceScore += 0.6; // decoded-hit is high-confidence
379
+ }
380
+ // Also run source-specific patterns over the decoded layer.
381
+ for (const pattern of sourcePatterns) {
382
+ if (pattern.test(decodedNormalized)) {
383
+ sourceScore += 0.4;
384
+ violations.push({
385
+ type: "ingested_injection",
386
+ scanner: this.name,
387
+ score: 0.4,
388
+ threshold: effectiveThreshold,
389
+ message: `Encoded indirect injection in ${source} content`,
390
+ detail: `Pattern: ${pattern.source.slice(0, 80)} (layer=decoded)`,
391
+ });
392
+ }
393
+ }
394
+ }
395
+ sourceScore = Math.min(sourceScore, 1.0);
396
+
397
+ // 3. Combine decisions. The heuristic scanner already weighed
398
+ // structural signals (newlines, headers, padding) that may not
399
+ // surface as individual violations; trust its decision rather
400
+ // than re-aggregating only the violation-score subset.
401
+ const heuristicBlocks = heuristicResult.decision === "block";
402
+ const heuristicWarns = heuristicResult.decision === "warn";
403
+ const sourceBlocks = sourceScore >= effectiveThreshold;
404
+ const sourceWarns = sourceScore >= effectiveThreshold * 0.6;
405
+
406
+ let decision: "allow" | "warn" | "block";
407
+ if (heuristicBlocks || sourceBlocks) {
408
+ decision = "block";
409
+ } else if (heuristicWarns || sourceWarns) {
410
+ decision = "warn";
411
+ } else {
412
+ decision = "allow";
413
+ }
414
+
415
+ return {
416
+ decision,
417
+ violations,
418
+ durationMs: performance.now() - start,
419
+ };
420
+ }
421
+ }
422
+
423
+ /**
424
+ * One-shot helper. Scans `content` against the source-specific profile
425
+ * and returns a result without needing an `AIShield` instance.
426
+ *
427
+ * Use when you want a quick gate at the ingestion boundary, e.g.
428
+ * before storing a chunk into a vector DB or before passing a tool
429
+ * description into the model's context.
430
+ *
431
+ * @example
432
+ * ```ts
433
+ * import { scanIngested } from "ai-shield-core";
434
+ *
435
+ * const ragChunk = "...retrieved document text...";
436
+ * const result = await scanIngested(ragChunk, "rag");
437
+ * if (!result.safe) {
438
+ * // reject the chunk OR strip it before assembly
439
+ * logger.warn("IPI candidate", result.violations);
440
+ * }
441
+ * ```
442
+ */
443
+ export async function scanIngested(
444
+ content: string,
445
+ source: IngestionSource,
446
+ config: IngestionScannerConfig = {},
447
+ ): Promise<IngestionScanResult> {
448
+ const start = performance.now();
449
+ const scanner = new IngestionScanner(config);
450
+ const result = await scanner.scan(content, { source });
451
+
452
+ return {
453
+ safe: result.decision === "allow",
454
+ decision: result.decision,
455
+ // When a chunk is blocked, returning the raw input under the field
456
+ // name "sanitized" mis-leads callers into trusting poisoned content.
457
+ // Return empty string on block so a `if (!safe) use(result.sanitized)`
458
+ // path becomes a no-op rather than a vulnerability. Use the original
459
+ // `content` argument if you still need it for audit / quarantine.
460
+ sanitized: result.decision === "block" ? "" : content,
461
+ violations: result.violations,
462
+ source,
463
+ meta: {
464
+ scanDurationMs: performance.now() - start,
465
+ scannersRun: [scanner.name],
466
+ sourceSpecificHits: result.violations.filter(
467
+ (v) =>
468
+ v.detail?.startsWith("Pattern:") && v.type === "ingested_injection",
469
+ ).length,
470
+ cached: false,
471
+ },
472
+ };
473
+ }
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
+
524
+ // ============================================================
525
+ // Encoding-bypass normalization (R1 from Round 1 review — closes
526
+ // OWASP LLM Prompt Injection Prevention Cheat Sheet 2026 Base64/Hex
527
+ // bypass class).
528
+ // ============================================================
529
+
530
+ /**
531
+ * Try to decode common obfuscation layers an attacker uses to smuggle
532
+ * an injection past pattern matchers. Returns the decoded payload when
533
+ * it looks like a successful decode, else `null`.
534
+ *
535
+ * The function deliberately runs at most ONE decode layer to avoid
536
+ * decoding amplification (a chain of `base64(base64(...))` would force
537
+ * us into deep recursion); a single-layer decode is enough to catch
538
+ * the vast majority of in-the-wild bypasses while keeping execution
539
+ * cost bounded.
540
+ *
541
+ * Heuristics:
542
+ * - Base64: contiguous run of 40+ Base64 chars, decodes to mostly
543
+ * printable ASCII or the `\u00..` C0 range stays empty.
544
+ * - Hex: 80+ hex chars in a row.
545
+ * - Percent-encoding: more than 5 `%XX` sequences.
546
+ *
547
+ * Returns the longest decoded payload when multiple candidates fire.
548
+ */
549
+ export function tryDecodeObfuscation(input: string): string | null {
550
+ if (typeof input !== "string" || input.length === 0) return null;
551
+ // Cap input we look at — Base64 of a megabyte is not the threat model.
552
+ const haystack = input.length > 65_536 ? input.slice(0, 65_536) : input;
553
+
554
+ const candidates: string[] = [];
555
+
556
+ // Base64 — at least 40 chars, optional padding, optional whitespace.
557
+ const B64_RE = /[A-Za-z0-9+/=]{40,}/g;
558
+ for (const match of haystack.match(B64_RE) ?? []) {
559
+ const cleaned = match.replace(/=+$/, "").replace(/[^A-Za-z0-9+/]/g, "");
560
+ if (cleaned.length < 40) continue;
561
+ try {
562
+ const decoded = Buffer.from(cleaned, "base64").toString("utf8");
563
+ if (decoded.length === 0) continue;
564
+ const printable = decoded.replace(/[^\x20-\x7E\s]/g, "");
565
+ // Require >70% printable to avoid noise.
566
+ if (printable.length / decoded.length >= 0.7) {
567
+ candidates.push(decoded);
568
+ }
569
+ } catch {
570
+ // ignore malformed Base64
571
+ }
572
+ }
573
+
574
+ // Hex — 80+ hex digits in a row.
575
+ const HEX_RE = /[0-9a-fA-F]{80,}/g;
576
+ for (const match of haystack.match(HEX_RE) ?? []) {
577
+ if (match.length % 2 !== 0) continue;
578
+ try {
579
+ const decoded = Buffer.from(match, "hex").toString("utf8");
580
+ if (decoded.length === 0) continue;
581
+ const printable = decoded.replace(/[^\x20-\x7E\s]/g, "");
582
+ if (printable.length / decoded.length >= 0.7) {
583
+ candidates.push(decoded);
584
+ }
585
+ } catch {
586
+ // ignore malformed hex
587
+ }
588
+ }
589
+
590
+ // Percent-encoding — only decode a windowed region around clustered
591
+ // escapes rather than the full 65KB haystack. Round 2 Critic M-NEW-1:
592
+ // running `decodeURIComponent()` on the full haystack on every scan
593
+ // allocates a ~2× copy per call and pressures GC in high-throughput
594
+ // ingestion pipelines.
595
+ const PERCENT_RE = /%[0-9A-Fa-f]{2}/g;
596
+ const percentMatches: number[] = [];
597
+ let percentMatch: RegExpExecArray | null;
598
+ while (
599
+ (percentMatch = PERCENT_RE.exec(haystack)) !== null &&
600
+ percentMatches.length < 32
601
+ ) {
602
+ percentMatches.push(percentMatch.index);
603
+ }
604
+ if (percentMatches.length >= 5) {
605
+ // Decode only a window around the cluster: 256 bytes before the first
606
+ // escape, 1KB after the last. Bounded work regardless of haystack size.
607
+ const first = percentMatches[0] ?? 0;
608
+ const last = percentMatches[percentMatches.length - 1] ?? first;
609
+ const winStart = Math.max(0, first - 256);
610
+ const winEnd = Math.min(haystack.length, last + 1024);
611
+ const window = haystack.slice(winStart, winEnd);
612
+ try {
613
+ const decoded = decodeURIComponent(window);
614
+ if (decoded !== window) candidates.push(decoded);
615
+ } catch {
616
+ // ignore malformed percent-encoding
617
+ }
618
+ }
619
+
620
+ if (candidates.length === 0) return null;
621
+ // Return the longest candidate; that's the most likely attack payload.
622
+ candidates.sort((a, b) => b.length - a.length);
623
+ return candidates[0] ?? null;
624
+ }