injectguard 0.1.0

Heuristic prompt-injection detector and sanitizer for untrusted text fed to AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
// SPDX-License-Identifier: MIT
//! The table of regex-based detection rules.
//!
//! Pattern conventions (applied by [`compile`]):
//! * every pattern is compiled case-insensitive and multi-line (`(?im)`);
//! * a literal space means "word separator": 1..=6 chars of whitespace,
//!   punctuation or symbols, so `ignore  --  previous` still matches (use
//!   `[\t\x20]` for a real space);
//! * `\b` is rewritten to the ASCII word boundary `(?-u:\b)`, which keeps the
//!   fast lazy DFA usable on non-ASCII haystacks.

use std::sync::OnceLock;

use regex::Regex;

use super::{Category, Severity};

/// Word separator substituted for each literal space in a pattern:
/// whitespace, ASCII punctuation/symbols, and common Unicode dashes, quotes
/// and bullets, plus the escapes `\n`, `\r`, `\t` (JSON-encoded tool
/// output). (Full `\p{P}\p{S}` works too but makes compilation and
/// matching noticeably slower.)
const SEP: &str = r"(?:[\s!-/:-@\[-`{-~\u{2010}-\u{2027}\u{00B7}]|\\[nrt]){1,6}";

pub(crate) struct Rule {
    pub id: &'static str,
    pub category: Category,
    pub severity: Severity,
    pub message: &'static str,
    pub regex: Regex,
    /// Report the location of capture group 1 instead of the whole match.
    pub loc_group: bool,
}

struct Def {
    id: &'static str,
    category: Category,
    severity: Severity,
    message: &'static str,
    pattern: &'static str,
    loc_group: bool,
}

const fn def(
    id: &'static str,
    category: Category,
    severity: Severity,
    message: &'static str,
    pattern: &'static str,
) -> Def {
    Def {
        id,
        category,
        severity,
        message,
        pattern,
        loc_group: false,
    }
}

const fn def_loc(
    id: &'static str,
    category: Category,
    severity: Severity,
    message: &'static str,
    pattern: &'static str,
) -> Def {
    Def {
        id,
        category,
        severity,
        message,
        pattern,
        loc_group: true,
    }
}

use Category::*;
use Severity::*;

const DEFS: &[Def] = &[
    // ---------------------------------------------------------------- AI
    def(
        "ai.ignore_instructions",
        AiDirective,
        High,
        "asks to ignore previous instructions",
        r"\b(?:ignore|disregard|forget|override|bypass|neglect)(?: (?:all|any|every|the|your|my|of|these|those|its|their)){0,3} (?:previous|prior|above|earlier|preceding|former|original|initial|old|existing|system|developer)(?: \w+)? (?:instructions?|rules|prompts?|directives?|guidelines|guidance|commands|directions|orders|context|messages)\b|\b(?:ignore|disregard|forget) (?:all|any|every)(?: (?:of|the|your|my|these|those)){0,2} (?:instructions?|rules|prompts?|directives?|guidelines)\b|\b(?:ignore|disregard|forget)(?: all)?(?: of)? (?:the|everything|anything|all) (?:above|before this|before|said above|written above|prior)(?: (?:and|instructions|directions|text|prompt|context|line|message))\b|\bpay no (?:attention|heed|mind) to (?:\w+ ){0,3}(?:instructions?|rules|prompts?|directives?|guidelines|guidance)\b|\bstop (?:following|obeying|listening to) (?:all )?(?:of )?(?:your |any |the |these |those )?(?:previous|prior|earlier|original|initial|system|current|above|old) (?:\w+ )?(?:instructions?|rules|prompts?|directives?|guidelines|guidance)\b",
    ),
    def(
        "ai.role_override",
        AiDirective,
        High,
        "tries to assign the AI a new role",
        r"\byou are now (?:(?:a|an|the|my) (?:\w+ ){0,3}(?:ai|assistant|model|bot|chatbot|llm|agent|character|persona|hacker|villain|pirate|terminal|shell)|acting as|operating as|free|unrestricted|jailbroken|unfiltered|dan|no longer bound|no longer an? (?:ai|assistant|model)|evil)\b|\bpretend (?:that )?you(?:'re|’re| are)\b",
    ),
    def(
        "ai.as_an_ai",
        AiDirective,
        High,
        "addresses an AI model (\"as an AI\")",
        r"\bas an? (?:ai|artificial intelligence|large language model|language model|llm)\b",
    ),
    def(
        "ai.system_prompt",
        AiDirective,
        High,
        "mentions the system prompt",
        r"\bsystem prompts?\b",
    ),
    def(
        "ai.conceal_from_user",
        AiDirective,
        High,
        "asks to hide something from the user",
        r"\b(?:do not|don't|don’t|dont|never|without) (?:tell|telling|inform|informing|notify|notifying|mention|mentioning|alert|alerting|reveal this to|show this to) (?:(?:the|your|this) )?(?:user|human|operator|developer)s?\b|\bkeep (?:this|it|that) (?:secret|hidden|private) from (?:(?:the|your) )?(?:user|human|operator)s?\b",
    ),
    def(
        "ai.new_instructions",
        AiDirective,
        High,
        "announces new instructions",
        r"\bnew (?:system )?instructions?\b|\b(?:your|the) real instructions\b|\byour (?:instructions|rules|guidelines|system prompt|directives) (?:have|has) (?:now )?been (?:updated|changed|replaced|modified|overridden|revoked|reset)\b",
    ),
    def(
        "ai.act_as",
        AiDirective,
        High,
        "imperative \"act as\" role assignment",
        r"(?:^[\t\x20]*|[.!?:][\t\x20]*|\b(?:please|now|you (?:will|must|should|shall|are to|need to)) )act as (?:a|an|if|my|the)\b",
    ),
    def(
        "ai.role_marker",
        AiDirective,
        High,
        "chat-template role marker",
        r"<\s*\|\s*(?:im_start|im_end|system|user|assistant|endoftext|eot_id|start_header_id|end_header_id|begin_of_text)\s*\|\s*>|\[/?inst\]|<</?sys>>",
    ),
    def(
        "ai.role_heading",
        AiDirective,
        High,
        "heading that impersonates a chat role",
        r"^[\t\x20]*#{1,6}[\t\x20]*(?:system|assistant|system[\t\x20]+prompt)[\t\x20]*:?[\t\x20]*\r?$",
    ),
    def(
        "ai.role_prefix",
        AiDirective,
        High,
        "line starts with a chat role prefix",
        r"^[\t\x20]*(?:system|assistant)[\t\x20]*:|^[\t\x20]*human[\t\x20]*:[^\n]{0,300}\bassistant[\t\x20]*:",
    ),
    def(
        "ai.direct_address",
        AiDirective,
        High,
        "text addressed directly to an AI",
        r"\b(?:dear|hey|hello|hi|attention|note to|message to|instructions for|memo to) (?:the )?(?:ai|assistant|claude|llm|agent|ai agent|ai assistant|coding agent|chatgpt|gpt|copilot|language model)s?\b|\bdear (?:the )?models?\b|\b(?:note|message|instructions?|important|attention|reminder|warning) (?:for|to) (?:the |any |all )?(?:ai|llms?|language models?|assistants?|ai agents?|ai assistants?|agents?|chatbots?)[\t\x20]*[:,!\u{2014}-]|\battention,? (?:ai|llm|assistant|ai agent|agent|language model)s?[\t\x20]*[:,!]|\b(?:ai|llm|language model|assistant|ai agent|agent|chatbot)s? (?:reading|processing|parsing|summari[sz]ing|viewing|crawling|scraping|browsing) this\b",
    ),
    def(
        "ai.if_you_are_ai",
        AiDirective,
        High,
        "conditional addressed to an AI (\"if you are an AI\")",
        r"\bif you(?:'re|’re| are) (?:(?:an?|the) )?(?:ai|llm|assistant|agent|language model|bot|chatbot|claude|chatgpt|model|ai agent|ai assistant)\b",
    ),
    def(
        "ai.prompt_leak",
        AiDirective,
        High,
        "asks the AI to reveal its instructions or context",
        r"\b(?:repeat|print|output|show|reveal|display|recite|dump|write out|copy|tell me|list)\b (?:back )?(?:all |everything |verbatim )?(?:(?:of|in|from) )?(?:your (?:(?:initial|original|hidden|system|full|previous|first|exact|secret|entire) )?(?:instructions|prompt|context window|context|system message|rules|configuration|guidelines)|the (?:initial|original|hidden|system|secret|full) (?:instructions|prompt|message))\b|\b(?:repeat|output|print|copy)\b (?:all |everything |the )?(?:text|words|content|everything|lines?) above (?:verbatim|word for word|starting|exactly|from)\b",
    ),
    def(
        "ai.bypass_safety",
        AiDirective,
        Medium,
        "talks about ignoring safety rules (may be benign)",
        r"\b(?:disregard|ignore|bypass|override|circumvent)\b (?:all |any |the |your )?(?:safety|ethical|ethics|content|moderation) (?:guidelines|rules|policies|filters|restrictions|protocols|measures)\b",
    ),
    def(
        "ai.from_now_on",
        AiDirective,
        High,
        "re-programs the AI's future behaviour",
        r"\bfrom now on,? you (?:will|must|shall|are going to|should|are to|can) (?:only |always |never |not |no longer )?(?:answer|respond|reply|act|behave|ignore|obey|follow|comply|be|pretend|speak|output|do|say|refuse)\b|\byou (?:must|will|shall) now (?:only )?(?:follow|obey|comply|answer|respond|act|ignore|do whatever)\b|\b(?:follow|obey) only (?:my|these|the following) (?:commands|instructions|orders|rules)\b",
    ),
    def(
        "ai.jailbreak",
        AiDirective,
        High,
        "jailbreak or safety-override phrasing",
        r"\b(?:enable|activate|enter|switch to|switch into|turn on|you are (?:now )?in|unlock) (?:the )?(?:god|jailbreak|jailbroken|unrestricted|unfiltered|dan|evil|chaos) mode\b|\byou are (?:now )?in (?:developer|dev) mode\b|\b(?:enable|activate|enter) (?:the )?developer mode (?:and|to) (?:ignore|remove|bypass|disable|lift|drop)\b|\bdo anything now\b|\byou are (?-i:DAN)\b|\bsystem override\b|\b(?:remove|disable|bypass|turn off|lift|ignore|drop) (?:all )?(?:of )?your (?:safety |content |ethical )?(?:restrictions|filters|guardrails|safeguards|guidelines|limitations|rules)\b|\b(?:safety|content) (?:filters?|guardrails|restrictions|guidelines) (?:are |have been )?(?:now )?(?:disabled|removed|off|lifted|deactivated)\b",
    ),
    def(
        "ai.context_break",
        AiDirective,
        High,
        "fake end-of-document marker followed by new orders",
        r"(?:^|[-=#*\[(<]{2,}[\t\x20]*)(?:end of (?:the )?(?:document|context|input|prompt|text|data|file|page|email))[\t\x20]*(?:[-=#*\])>]{2,})?[^\n]{0,40}?\b(?:new (?:task|instructions?|objective|goal|orders?)|now (?:you|do|instead)|instead)\b",
    ),
    def(
        "ai.fake_tags",
        AiDirective,
        High,
        "fake tool-call or system tags",
        r"</?(?:tool_result|tool_use|tool_call|function_results?|function_calls?|system|system-reminder|system_prompt|system-prompt|developer_message)\s*>|<invoke\s+name\s*=|<parameter\s+name\s*=",
    ),
    def(
        "ai.role_json",
        AiDirective,
        Medium,
        "chat message JSON with a system role (may be benign API code)",
        r#"["']role["']\s*:\s*["'](?:system|developer)["']"#,
    ),
    def(
        "ai.ignore_instructions_i18n",
        AiDirective,
        High,
        "asks to ignore previous instructions (non-English)",
        concat!(
            // Turkish: "önceki (tüm) talimatları yok say / görmezden gel / unut"
            r"(?:önceki|yukarıdaki|daha\s+önceki|tüm|bütün|eski)\s+(?:\w+\s+){0,2}(?:talimat|komut|kural|yönerge|direktif)\w*\s+(?:\w+\s+){0,3}(?:yok\s+say|görmezden\s+gel|unut|dikkate\s+alma|umursama)(?:ın|in|un|ün|ınız|iniz|unuz|ünüz)?(?:[\t\x20.,!;:]|$)",
            // German
            r"|(?:ignorier|vergiss|vergesse|missachte)\w*\s+(?:du\s+)?(?:alle\s+)?(?:\w+\s+)?(?:vorherigen|bisherigen|obigen|vorigen|früheren|ursprünglichen)\s+(?:anweisungen|instruktionen|befehle|regeln|vorgaben)",
            // Spanish / Portuguese / Italian
            r"|(?:ignora|ignore|olvida|olvide|esquece|esqueça|dimentica)\w*\s+(?:todas\s+|todos\s+|tutte\s+)?(?:las\s+|as\s+|le\s+|os\s+)?(?:instrucciones|instruções|istruzioni|reglas|regras|regole|indicaciones|órdenes)\s+(?:anteriores|previas|precedentes|precedenti|prévias)",
            // French
            r"|(?:ignore|ignorez|oublie|oubliez)\s+(?:toutes\s+)?(?:les\s+)?(?:instructions|consignes|règles|directives)\s+(?:précédentes|antérieures|ci-dessus)",
            // Russian
            r"|(?:игнорир|забудь|забудьте|проигнорир)\w*\s+(?:все\s+)?(?:предыдущие|прошлые|прежние|вышеуказанные|вышеприведённые|предшествующие)\s+(?:инструкции|указания|команды|правила)",
            // Chinese / Japanese
            r"|(?:忽略|无视|忘记|忽視|無視)[^\n]{0,8}(?:之前|以上|上面|先前|前面|上述|以前)[^\n]{0,8}(?:指令|指示|说明|說明|提示|规则|規則|命令)",
            r"|(?:以前|前|上記|これまで)の(?:すべての)?(?:指示|命令|ルール)[^\n]{0,6}(?:無視|忘れ)",
        ),
    ),
    def(
        "ai.mention_model",
        AiDirective,
        Medium,
        "mentions an AI model or vendor (may be benign)",
        r"\b(?:claude|chatgpt|openai|anthropic|llms?|large language models?|language models?|gpt-?[345](?:\.\d)?o?)\b",
    ),
    // ------------------------------------------------------------ ACTION
    def(
        "action.pipe_to_shell",
        ActionRequest,
        High,
        "downloads and pipes into a shell",
        r"\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b[^\n|]{0,200}\|[\t\x20]*(?:sudo[\t\x20]+)?(?:sh|bash|zsh|ksh|dash|fish|python3?|perl|ruby|node|iex|invoke-expression|pwsh|powershell)\b",
    ),
    def(
        "action.rm_rf",
        ActionRequest,
        High,
        "destructive recursive delete command",
        r"\brm[\t\x20]+(?:-[a-z]*r[a-z]*f[a-z]*|-[a-z]*f[a-z]*r[a-z]*|-r[\t\x20]+-f|-f[\t\x20]+-r|--recursive[\t\x20]+--force|--force[\t\x20]+--recursive)\b|\brd[\t\x20]+/s[\t\x20]+/q\b|\bdel[\t\x20]+/[fsq]\b[^\n]{0,20}/[sq]\b",
    ),
    def(
        "action.powershell_encoded",
        ActionRequest,
        High,
        "PowerShell with an encoded command",
        r"\b(?:powershell|pwsh)(?:\.exe)?\b[^\n]{0,100}?[\t\x20]-(?:e|ec|en|enc|enco|encodedcommand)\b",
    ),
    def(
        "action.invoke_expression",
        ActionRequest,
        High,
        "PowerShell Invoke-Expression",
        r"\binvoke-expression\b|\|[\t\x20]*iex\b|\biex[\t\x20]*\(|\biex[\t\x20]+\$",
    ),
    def(
        "action.run_command",
        ActionRequest,
        Medium,
        "asks to run a command or script",
        r"\b(?:run|execute|exec) (?:the following|this|these|that|the below) (?:(?:shell|terminal|bash|powershell|cmd|system) )?(?:commands?|scripts?|code|snippet|one-liner|payload)\b",
    ),
    def(
        "action.git_push",
        ActionRequest,
        Medium,
        "mentions git push",
        r"\bgit[\t\x20]+push\b|\bcommit and push\b",
    ),
    def(
        "action.force_push",
        ActionRequest,
        High,
        "asks for a force push",
        r"\bforce push(?:ing|ed|es)?\b|\bgit[\t\x20]+push\b[^\n]{0,80}?(?:[\t\x20]--force(?:-with-lease)?\b|[\t\x20]-f\b|[\t\x20]\+\w)",
    ),
    def(
        "action.open_pr",
        ActionRequest,
        Medium,
        "asks to open a pull request",
        r"\b(?:open|create|submit|file|send|make) (?:a|an|the|this|new) (?:new )?(?:pull requests?|prs?|merge requests?)\b",
    ),
    def(
        "action.merge_pr",
        ActionRequest,
        Medium,
        "asks to merge a pull request",
        r"\bmerge (?:this|the|that|my) (?:pull requests?|prs?|merge requests?)\b",
    ),
    def(
        "action.commit",
        ActionRequest,
        Medium,
        "asks to commit changes",
        r"\bcommit (?:this|these|those|the following)\b",
    ),
    def(
        "action.modify_agent_config",
        ActionRequest,
        High,
        "asks to modify AI agent or CI configuration",
        r"\b(?:edit|modify|update|change|overwrite|delete|remove|replace|rewrite|append|write|add|create|alter|patch|insert)\b[^\n]{0,80}?(?:claude\.md|agents\.md|gemini\.md|\.github/workflows|settings(?:\.local)?\.json|\.cursorrules|\.cursor/rules|mcp\.json|\.claude/|copilot-instructions\.md|\.windsurfrules|\.clinerules)",
    ),
    def(
        "action.add_dependency",
        ActionRequest,
        Medium,
        "asks to add a dependency",
        r"\badd (?:a|an|this|these|the following|the) (?:new )?(?:dependency|dependencies|crate|package)\b",
    ),
    def(
        "action.install_package",
        ActionRequest,
        Medium,
        "asks to install a package",
        r"\binstall (?:this|the following|these|that|my) (?:(?:npm|pip|python|node|cargo|rust) )?(?:packages?|crates?|modules?|librar(?:y|ies)|dependency|dependencies|extensions?|plugins?)\b",
    ),
    // ------------------------------------------------------------ SECRET
    def(
        "secret.exfiltrate",
        SecretRequest,
        High,
        "asks to reveal or send secrets",
        // Only determiners/possessives and a few qualifiers may sit between the
        // verb and the noun, which keeps API docs ("send process
        // credentials") from matching. An indirect object may follow the
        // verb ("send me the API key").
        r"\b(?:reveal|print|show|send|leak|exfiltrate|exfil|output|dump|upload|post|share|display|disclose|expose|email|paste|echo|give me|tell me|read out|forward|transmit|dm|mail|text)\b (?:(?:me|us|them|him|her|to me|to us|over|across) )?(?:(?:your|my|the|all|any|every|these|those|its|their|our|of|and|stored|saved|current|full|raw|plaintext|private|secret|admin|root|user's|users'|aws|github|openai|anthropic|cloud|ci|contents|content|output|values?) ){0,4}(?:api[\s_-]?keys?|(?:access|auth|api|bearer|oauth|session|github|gh|secret|refresh|personal[\s_-]access)[\s_-]?tokens?|passwords?|passwd|passphrases?|secrets|secret[\s_-]?keys?|credentials?|env(?:ironment)?[\s_-]?var(?:iable)?s?|ssh[\s_-]?keys?|private[\s_-]?keys?|signing[\s_-]?keys?|session[\s_-]?cookies?)\b",
    ),
    def(
        "secret.append_to_reply",
        SecretRequest,
        High,
        "asks to put secrets into the reply",
        r"\b(?:append|include|add|attach|insert|put|paste|embed)\b (?:(?:the|your|my|user's|users'|all|any|current|full|their) ){0,3}(?:\w+ )?(?:api[\s_-]?keys?|(?:access|auth|session|api|bearer)[\s_-]?tokens?|passwords?|secrets?|credentials?|(?:session[\s_-]?)?cookies?|env(?:ironment)?[\s_-]?var(?:iable)?s?)\b[^\n]{0,30}?\b(?:(?:to|in|into|at the end of|inside) (?:your|each|every) (?:answer|reply|response|output|message|summary)|(?:to|in|into|at the end of) (?:the|this) (?:answer|reply|summary))\b",
    ),
    def(
        "secret.dump_env",
        SecretRequest,
        High,
        "asks to run a command that dumps environment variables",
        r"\b(?:run|execute|exec|call|type|invoke)\b[\t\x20]+[`'\x22]?(?:printenv|env|export[\t\x20]+-p|get-childitem[\t\x20]+env:|gci[\t\x20]+env:|dir[\t\x20]+env:)[`'\x22]?[^\n]{0,30}?\b(?:paste|send|include|share|post|upload|return|reply|append|output|show me|tell me|give me)\b",
    ),
    def(
        "secret.send_to_url",
        SecretRequest,
        High,
        "asks to send the conversation or secrets to a URL",
        r"\b(?:send|post|upload|forward|transmit|leak|exfiltrate|copy|submit|email|log|report)\b (?:(?:\w+ ){0,4})?(?:conversation|chat history|chat log|message history|session (?:data|history)|system prompt|prompt|context window|transcript|previous messages|api[\s_-]?keys?|tokens?|passwords?|credentials?|secrets?|env(?:ironment)? var(?:iable)?s?)(?: history| log| logs| contents?| data)?\b[^\n]{0,40}?\bto (?:https?://|www\.|[a-z0-9-]+\.(?:com|net|org|io|site|xyz|ru|cn|app|dev|me|sh|cc|tk|top)\b)",
    ),
    def(
        "secret.markdown_exfil",
        SecretRequest,
        High,
        "markdown image/link URL with a placeholder for data (exfiltration)",
        r"!?\[[^\]\n]{0,100}\]\([\t\x20]*<?https?://[^)\s]{1,300}[?&#][^)\s]{0,300}(?:\{\{|\{[a-z_]{2,30}\}|\$\{|%7b|\[[a-z_ ]{2,30}\]|<[a-z_]{2,30}>|(?-i:[A-Z_]{6,}_HERE))",
    ),
    def(
        "secret.data_in_url",
        SecretRequest,
        Medium,
        "talks about putting secrets or the conversation into a URL",
        r"\b(?:include|put|append|add|insert|encode|embed|place)\b[^\n]{0,60}\b(?:tokens?|secrets?|passwords?|api keys?|credentials?|cookies?|conversation|chat history|history|session)\b[^\n]{0,40}?\b(?:in|into|to|as) (?:the |a |this |that )?(?:url|link|query(?: string)?|image url|parameter|request)\b",
    ),
    def(
        "secret.request_i18n",
        SecretRequest,
        High,
        "asks to reveal or send secrets (Turkish)",
        r"(?:api\s*anahtar|şifre|parola|token|kimlik\s+bilgi|gizli\s+anahtar)\w*\s+(?:\w+\s+){0,2}(?:gönder|paylaş|ilet)(?:in|ın|iniz|ınız)?(?:[\t\x20.,!;:]|$)",
    ),
    def(
        "secret.key_name",
        SecretRequest,
        High,
        "names a well-known secret environment variable",
        // Environment variable names are conventionally upper case; matching
        // case-sensitively is also several times faster here.
        r"\b(?-i:ANTHROPIC_API_KEY|OPENAI_API_KEY|AZURE_OPENAI_API_KEY|GOOGLE_API_KEY|GEMINI_API_KEY|GITHUB_TOKEN|GH_TOKEN|AWS_SECRET_ACCESS_KEY|AWS_ACCESS_KEY_ID|AWS_SESSION_TOKEN|HF_TOKEN|NPM_TOKEN|CARGO_REGISTRY_TOKEN)\b",
    ),
    def(
        "secret.credential_file",
        SecretRequest,
        High,
        "refers to a credential file",
        r"~/\.ssh\b|\$home/\.ssh\b|%userprofile%\\\.ssh\b|\.ssh/(?:id_|authorized_keys|config\b)|\b(?-i:id_(?:rsa|dsa|ecdsa|ed25519))\b|\.aws/credentials\b|\.git-credentials\b|/etc/shadow\b|\.netrc\b|\.docker/config\.json\b|\.pypirc\b",
    ),
    def(
        "secret.dotenv",
        SecretRequest,
        High,
        "asks to read a .env file",
        r"\b(?:cat|type|read|open|print|show|send|upload|dump|get-content|copy|cp|leak|exfiltrate|post|display|reveal|echo)\b[^\n]{0,40}?[\s/'`(=]\.env(?:\.[a-z]+)?\b",
    ),
    // ------------------------------------------------------------ STYLE
    def(
        "style.display_none",
        HiddenStyling,
        Medium,
        "CSS display:none hides text",
        r"display[\t\x20]*:[\t\x20]*none\b",
    ),
    def(
        "style.visibility_hidden",
        HiddenStyling,
        Medium,
        "CSS visibility:hidden hides text",
        r"visibility[\t\x20]*:[\t\x20]*(?:hidden|collapse)\b",
    ),
    def(
        "style.font_size_zero",
        HiddenStyling,
        Medium,
        "zero font size hides text",
        r#"font-size[\t\x20]*:[\t\x20]*0+(?:\.0+)?(?:px|pt|em|rem|%|vh|vw|ex|ch)?[\t\x20]*(?:[;"'}!]|$)"#,
    ),
    def(
        "style.opacity_zero",
        HiddenStyling,
        Medium,
        "zero opacity hides text",
        r#"opacity[\t\x20]*:[\t\x20]*0*\.?0+[\t\x20]*(?:[;"'}!]|$)"#,
    ),
    def_loc(
        "style.white_text",
        HiddenStyling,
        Medium,
        "white text color (white-on-white hiding)",
        r#"(?:^|[^-a-z0-9_])(color[\t\x20]*[:=][\t\x20]*["']?(?:white\b|#fff(?:fff)?\b|rgba?\([\t\x20]*255[\t\x20]*,[\t\x20]*255[\t\x20]*,[\t\x20]*255\b))"#,
    ),
    def(
        "style.offscreen",
        HiddenStyling,
        Medium,
        "text pushed off-screen with CSS",
        r"(?:left|top|right|text-indent|margin-left|margin-top)[\t\x20]*:[\t\x20]*-[\t\x20]*\d{4,}(?:\.\d+)?(?:px|em|rem|pt|vw|vh)?\b",
    ),
    def(
        "style.hidden_attr",
        HiddenStyling,
        Medium,
        "HTML element with the hidden attribute",
        r"<[a-z][a-z0-9-]*[\t\x20\r\n]+(?:[^>]*[\t\x20\r\n])?hidden[\t\x20\r\n/>=]",
    ),
    def(
        "style.aria_hidden",
        HiddenStyling,
        Medium,
        "aria-hidden content",
        r#"aria-hidden[\t\x20]*=[\t\x20]*["']?true\b"#,
    ),
    // -------------------------------------------------------- WHITESPACE
    def_loc(
        "ws.long_run",
        WeirdWhitespace,
        Low,
        "run of 40+ spaces/tabs inside a line (may push text off-screen)",
        r"\S([\t\x20]{40,})\S",
    ),
    def(
        "ws.blank_lines",
        WeirdWhitespace,
        Low,
        "10+ consecutive blank lines (may hide text below the fold)",
        r"(?:\r?\n[\t\x20]*){11,}",
    ),
];

fn compile(pattern: &str) -> Regex {
    let p = pattern.replace(' ', SEP).replace(r"\b", r"(?-u:\b)");
    let full = format!("(?im){p}");
    // The patterns are static; a failure here is a programming error that
    // the test suite catches.
    Regex::new(&full).unwrap_or_else(|e| panic!("bad rule pattern {pattern:?}: {e}"))
}

/// All compiled regex rules (compiled once).
pub(crate) fn rules() -> &'static [Rule] {
    static RULES: OnceLock<Vec<Rule>> = OnceLock::new();
    RULES.get_or_init(|| {
        DEFS.iter()
            .map(|d| Rule {
                id: d.id,
                category: d.category,
                severity: d.severity,
                message: d.message,
                regex: compile(d.pattern),
                loc_group: d.loc_group,
            })
            .collect()
    })
}

/// Separator-free variants of the High directive/action/secret rules, for
/// the squashed letters of spaced-out runs (`spaced`): spaces and `\b` are
/// dropped, so "ignoreallpreviousinstructions" matches. Only ever applied
/// to squashed runs, never to ordinary text (it would match inside words).
pub(crate) fn squashed_rules() -> &'static [Rule] {
    static RULES: OnceLock<Vec<Rule>> = OnceLock::new();
    RULES.get_or_init(|| {
        DEFS.iter()
            .filter(|d| {
                d.severity == High
                    && matches!(d.category, AiDirective | ActionRequest | SecretRequest)
            })
            .map(|d| {
                let p = d.pattern.replace(' ', "").replace(r"\b", "");
                Rule {
                    id: d.id,
                    category: d.category,
                    severity: d.severity,
                    message: d.message,
                    regex: Regex::new(&format!("(?im){p}"))
                        .unwrap_or_else(|e| panic!("bad squashed pattern {:?}: {e}", d.pattern)),
                    loc_group: d.loc_group,
                }
            })
            .collect()
    })
}

/// HTML comments, possibly unterminated. Group 1 is the content.
pub(crate) fn html_comment() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"(?s)<!--(.*?)(?:-->|\z)").expect("static regex"))
}

/// Candidate base64 runs.
pub(crate) fn base64_run() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"[A-Za-z0-9+/]{40,}={0,2}").expect("static regex"))
}