MR
Mayur Rathi
@sickn33
⭐ 47.3k GitHub stars

prompt-injection-defense

prompt-injection-defense is an code AI skill with a core value of Defend AI systems against prompt injection and indirect prompt attacks using input controls, tool permissions, output validation, and isolation boundaries. It helps developers solve real-world problems in the code domain, boosting efficiency, automating repetitive tasks, and optimizing workflows.

Defend AI systems against prompt injection and indirect prompt attacks using input controls, tool permissions, output validation, and isolation boundaries.

Last verified on: 2026-10-06

Quick Facts

Category code
Works With Claude
Source sickn33/antigravity-awesome-skills
Stars ⭐ 47.3k
Last Verified 2026-10-06
Risk Level Low
mkdir -p ./skills/prompt-injection-defense && curl -sfL https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/main/skills/prompt-injection-defense/SKILL.md -o ./skills/prompt-injection-defense/SKILL.md

Run in terminal / PowerShell. Requires curl (Unix) or PowerShell 5+ (Windows).

Skill Content

# Prompt Injection Defense


Mitigate direct and indirect prompt injection across chat apps, agentic workflows, and RAG pipelines.


When to Use This Skill


Use this skill when:

- Building or securing any LLM-powered application

- Designing RAG pipelines that ingest untrusted documents

- Implementing agentic workflows with tool-calling capabilities

- Responding to a reported prompt injection vulnerability

- Performing security reviews of AI-integrated products


Prerequisites


- Python 3.10+ with `re`, `hashlib`, `json` standard libraries

- Access to the LLM application source code or configuration

- Understanding of the application's prompt architecture (system/user/tool boundaries)

- Test environment with representative user inputs and documents


Attack Surface


- User input attempting to override system instructions

- Untrusted documents/web pages in retrieval context

- Tool output that smuggles malicious instructions

- Cross-tenant leakage via shared context windows

- Markdown or HTML injection in rendered outputs

- Multi-turn attacks that gradually shift context


Defense-in-Depth Pattern


1. **Instruction hierarchy enforcement**: system > developer > user > tool output.

2. **Context segregation**: isolate untrusted text from control instructions.

3. **Tool permissioning**: explicit allow-list per task and tenant.

4. **Output policy checks**: validate schema, redact secrets, block unsafe actions.

5. **Human approval**: required for high-impact operations.


Input Sanitization Functions


python
"""prompt_sanitizer.py - Input sanitization for LLM applications."""

import re
import hashlib
import json
from typing import Optional

# Patterns that commonly appear in injection attempts
INJECTION_PATTERNS = [
    r"(?i)ignore\s+(all\s+)?previous\s+instructions",
    r"(?i)disregard\s+(all\s+)?(above|previous|prior)",
    r"(?i)you\s+are\s+now\s+(DAN|evil|unrestricted|jailbroken)",
    r"(?i)system\s*:\s*override",
    r"(?i)SYSTEM\s+OVERRIDE",
    r"(?i)new\s+instructions?\s*:",
    r"(?i)forget\s+(everything|all|your\s+instructions)",
    r"(?i)act\s+as\s+if\s+you\s+have\s+no\s+(restrictions|limits|rules)",
    r"(?i)pretend\s+(you\s+are|to\s+be)\s+.*(unrestricted|evil|without)",
    r"(?i)BEGIN\s+(TRUSTED|SYSTEM|ADMIN)\s+(CONTEXT|PROMPT|OVERRIDE)",
    r"(?i)```system",
    r"(?i)\[INST\]",
    r"(?i)<\|im_start\|>system",
]

COMPILED_PATTERNS = [re.compile(p) for p in INJECTION_PATTERNS]


def detect_injection(text: str) -> dict:
    """Scan text for known prompt injection patterns.

    Returns:
        dict with 'detected' bool, 'patterns' list of matched pattern descriptions,
        and 'risk_score' float between 0.0 and 1.0.
    """
    matches = []
    for i, pattern in enumerate(COMPILED_PATTERNS):
        if pattern.search(text):
            matches.append(INJECTION_PATTERNS[i])

    risk_score = min(len(matches) / 3.0, 1.0)
    return {
        "detected": len(matches) > 0,
        "patterns": matches,
        "risk_score": risk_score,
        "input_length": len(text),
    }


def sanitize_input(text: str, max_length: int = 4096) -> str:
    """Sanitize user input before passing to the LLM.

    - Truncates to max_length
    - Strips null bytes and control characters
    - Removes Unicode homoglyph tricks
    - Normalizes whitespace
    """
    # Truncate
    text = text[:max_length]

    # Remove null bytes and most control characters (keep newlines and tabs)
    text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text)

    # Normalize Unicode confusables (basic set)
    confusable_map = {
        '\u200b': '',   # zero-width space
        '\u200c': '',   # zero-width non-joiner
        '\u200d': '',   # zero-width joiner
        '\u2060': '',   # word joiner
        '\ufeff': '',   # BOM
        '\u00a0': ' ',  # non-breaking space
    }
    for char, replacement in confusable_map.items():
        text = text.replace(char, replacement)

    # Collapse excessive whitespace
    text = re.sub(r'\n{4,

🎯 Best For

  • Claude users
  • Software engineers
  • Development teams
  • Tech leads

💡 Use Cases

  • Code quality improvement
  • Best practice enforcement

📖 How to Use This Skill

  1. 1

    Install the Skill

    Copy the install command from the Terminal tab and run it. The SKILL.md file downloads to your local skills directory.

  2. 2

    Load into Your AI Assistant

    Open Claude and reference the skill. Paste the SKILL.md content or use the system prompt tab.

  3. 3

    Apply prompt-injection-defense to Your Work

    Open your project in the AI assistant and ask it to apply the skill. Start with a small module to verify the output quality.

  4. 4

    Review and Refine

    Review AI suggestions before committing. Run tests, check for regressions, and iterate on the skill output.

❓ Frequently Asked Questions

Is prompt-injection-defense compatible with Cursor and VS Code?

Yes — this skill works with any AI coding assistant including Cursor, VS Code with Copilot, and JetBrains IDEs.

Do I need specific dependencies for prompt-injection-defense?

Check the install command and Works With section. Most code skills only require the AI assistant and your codebase.

How do I install prompt-injection-defense?

Copy the install command from the Terminal tab and run it. The skill downloads to ./skills/prompt-injection-defense/SKILL.md, ready to use.

Can I customize this skill for my team?

Absolutely. Edit the SKILL.md file to add team-specific instructions, examples, or workflows.

⚠️ Common Mistakes to Avoid

Skipping validation

Always test AI-generated code changes, even for simple refactors.

Missing dependency updates

Check if the skill requires updated dependencies or new packages.

🔗 Related Skills