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,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: ![x](http://evil/log?data=…). 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
+ }
@@ -24,10 +24,13 @@ interface PIIPattern {
24
24
 
25
25
  // --- German & International PII Patterns ---
26
26
  const PII_PATTERNS: PIIPattern[] = [
27
- // IBAN: DE + 2 check digits + 18 digits (with optional spaces/dashes)
27
+ // IBAN: 2-letter ISO + 2 check digits + 11..30 alphanumerics (with optional spaces/dashes).
28
+ // Covers all 80+ IBAN countries: NO (15), BE (16), DE (22), FR (27), MT (31), SC (31).
29
+ // The validator runs mod-97 over the cleaned value and rejects anything that isn't a real IBAN.
30
+ // Pattern is linear (no nested quantifiers) — ReDoS-safe.
28
31
  {
29
32
  type: "iban",
30
- pattern: /\b[A-Z]{2}\s?\d{2}\s?\d{4}\s?\d{4}\s?\d{4}\s?\d{4}\s?\d{2,4}\b/g,
33
+ pattern: /\b[A-Z]{2}\d{2}[ -]?[A-Z0-9](?:[A-Z0-9 -]{9,36}[A-Z0-9])?\b/g,
31
34
  validator: validateIBAN,
32
35
  baseConfidence: 0.95,
33
36
  },
@@ -62,11 +65,16 @@ const PII_PATTERNS: PIIPattern[] = [
62
65
  baseConfidence: 0.95,
63
66
  },
64
67
 
65
- // Phone: German formats (+49, 0xxx) and international
68
+ // Phone: German formats (+49, 0xxx) and international.
69
+ // Previous pattern had nested optional quantifiers (`\s?[\s\-/]?` plus two
70
+ // `[\s\-/]?\d{0,5}` tails) which risks catastrophic backtracking on
71
+ // malformed inputs. Restructured so every separator group requires at least
72
+ // one char when present and the trailing digits group is a true non-optional
73
+ // extension (or absent entirely).
66
74
  {
67
75
  type: "phone",
68
76
  pattern:
69
- /(?<!\d)(?:\+\d{1,3}|00\d{1,3}|0)\s?[\s\-/]?\(?\d{2,5}\)?[\s\-/]?\d{3,8}[\s\-/]?\d{0,5}\b/g,
77
+ /(?<!\d)(?:\+\d{1,3}|00\d{1,3}|0)[\s\-/]?\(?\d{2,5}\)?[\s\-/]?\d{3,8}(?:[\s\-/]\d{1,5})?\b/g,
70
78
  validator: validatePhone,
71
79
  baseConfidence: 0.80,
72
80
  },
@@ -161,11 +169,17 @@ function maskValue(type: PIIType, value: string): string {
161
169
  return value[0] + "***@" + value.substring(atIdx + 1);
162
170
  }
163
171
  case "phone":
172
+ // Need room for 4-prefix + **** + 2-suffix without overlap.
173
+ if (value.length < 7) return "[PHONE]";
164
174
  return value.substring(0, 4) + "****" + value.substring(value.length - 2);
165
175
  case "iban":
166
- return value.substring(0, 4) + " **** **** ****";
167
- case "credit_card":
168
- return "**** **** **** " + value.replace(/\D/g, "").substring(12);
176
+ // Keep country code + check digits, mask rest. Works for any IBAN length.
177
+ return value.length >= 4 ? value.substring(0, 4) + " **** **** ****" : "[IBAN]";
178
+ case "credit_card": {
179
+ const digits = value.replace(/\D/g, "");
180
+ if (digits.length < 13) return "[CREDIT_CARD]";
181
+ return "**** **** **** " + digits.substring(digits.length - 4);
182
+ }
169
183
  default:
170
184
  return `[${type.toUpperCase()}]`;
171
185
  }
package/src/shield.ts CHANGED
@@ -48,6 +48,16 @@ export class AIShield {
48
48
 
49
49
  /** Scan input text — the main API */
50
50
  async scan(input: string, context: ScanContext = {}): Promise<ScanResult> {
51
+ // Input-length guard — without this a user-supplied multi-MB prompt would
52
+ // trigger every regex scan on the full buffer, which is O(n) best-case
53
+ // but pathological under ReDoS-prone patterns. 256 KB handles every
54
+ // real chat/tool input we care about with plenty of headroom; override
55
+ // via AI_SHIELD_MAX_INPUT_BYTES when needed.
56
+ const maxInputBytes = Number(process.env.AI_SHIELD_MAX_INPUT_BYTES ?? 262_144);
57
+ if (input.length > maxInputBytes) {
58
+ input = input.slice(0, maxInputBytes);
59
+ }
60
+
51
61
  // Apply preset if not set in context
52
62
  if (!context.preset) {
53
63
  context.preset = this.config.preset ?? "public_website";
@@ -70,8 +80,11 @@ export class AIShield {
70
80
  this.scanCache.set(cacheKey, result);
71
81
  }
72
82
 
73
- // Log to audit if enabled
74
- if (this.auditLogger) {
83
+ // Log to audit if enabled — but never double-log the same input when
84
+ // a downstream caller re-scans cached content (result.meta.cached is set
85
+ // by the cache hit path above; here it is always false but we guard to
86
+ // be explicit and so subclasses extending scan() stay safe).
87
+ if (this.auditLogger && !result.meta.cached) {
75
88
  void this.auditLogger.log(input, result, context);
76
89
  }
77
90