"use strict";
/**
 * Layer 1: Agent Skill Injection Detection
 * Detects prompt injection, data exfiltration, and hidden execution
 * patterns in AI agent skill/configuration files.
 *
 * Scans:
 * - SKILL.md, AGENTS.md, skills.json/yaml
 * - .cursor/rules/, .cursorrules
 * - .claude/commands/, .claude/skills/, .claude/tools/
 * - .github/copilot-instructions.md, .github/agents/
 * - MCP configs (mcp.json, claude-desktop-config.json)
 * - .aider, .moltbot, .openclaw configs
 *
 * Detection Groups:
 * 1. Prompt Injection in Skill Prose (HIGH)
 * 2. Data Exfiltration (CRITICAL)
 * 3. Hidden Execution (HIGH)
 * 4. Tool/Function Description Poisoning (HIGH)
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.detectAgentSkillInjection = detectAgentSkillInjection;
const file_classifier_1 = require("../../parse/file-classifier");
const BASE_CONFIDENCE = 0.70;
// ============================================================================
// Educational Context Detection
// ============================================================================
const EDUCATIONAL_PATTERNS = [
    /example\s+of/i,
    /vulnerability/i,
    /never\s+do\s+this/i,
    /do\s+not/i,
    /malicious\s+example/i,
    /don['']t\s+do/i,
    /avoid\s+this/i,
    /anti[- ]?pattern/i,
    /insecure\s+example/i,
];
function isEducationalContext(line) {
    return EDUCATIONAL_PATTERNS.some(p => p.test(line));
}
function extractCodeBlocks(content) {
    const blocks = [];
    const regex = /```(?:bash|sh|shell|zsh|python|py|javascript|js|typescript|ts|ruby|php|powershell|cmd)?\n([\s\S]*?)```/g;
    let match;
    while ((match = regex.exec(content)) !== null) {
        const beforeMatch = content.slice(0, match.index);
        const startLine = beforeMatch.split('\n').length + 1; // +1 for content after ```
        blocks.push({
            content: match[1],
            startLine,
        });
    }
    return blocks;
}
// Group 1: Prompt Injection in Skill Prose
const PROMPT_INJECTION_PATTERNS = [
    {
        pattern: /ignore\s+(previous|prior|all(\s+previous)?)\s+instructions/i,
        title: 'Prompt injection: instruction override',
        description: 'Agent skill file contains an instruction to ignore previous/prior instructions, a common prompt injection technique.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /forget\s+(your|all)\s+(rules|guidelines|restrictions)/i,
        title: 'Prompt injection: rule erasure',
        description: 'Agent skill file instructs the model to forget its rules or guidelines.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /you\s+are\s+now\b/i,
        title: 'Prompt injection: role manipulation',
        description: 'Agent skill file attempts to reassign the model\'s role identity.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /pretend\s+(you\s+are|to\s+be)\b/i,
        title: 'Prompt injection: role impersonation',
        description: 'Agent skill file instructs the model to pretend to be something else.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /act\s+as\s+(if|though)\b/i,
        title: 'Prompt injection: behavioral override',
        description: 'Agent skill file instructs the model to act as if constraints do not apply.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /\bno\s+restrictions\b/i,
        title: 'Prompt injection: safety bypass',
        description: 'Agent skill file claims there are no restrictions on the model.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /skip\s+safety\b/i,
        title: 'Prompt injection: safety skip',
        description: 'Agent skill file instructs the model to skip safety checks.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /override\s+(guidelines|instructions|prompt)/i,
        title: 'Prompt injection: guideline override',
        description: 'Agent skill file attempts to override model guidelines or instructions.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /bypass\s+(safety|security)\b/i,
        title: 'Prompt injection: security bypass',
        description: 'Agent skill file instructs the model to bypass safety or security measures.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /\bDAN\b|Do\s+Anything\s+Now/i,
        title: 'Prompt injection: jailbreak (DAN)',
        description: 'Agent skill file contains DAN (Do Anything Now) jailbreak pattern.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /\bdeveloper\s+mode\b/i,
        title: 'Prompt injection: developer mode',
        description: 'Agent skill file invokes "developer mode" to bypass restrictions.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /\bjailbreak\b/i,
        title: 'Prompt injection: jailbreak keyword',
        description: 'Agent skill file contains explicit jailbreak terminology.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /system:\s*ignore\b/i,
        title: 'Prompt injection: system prompt override',
        description: 'Agent skill file attempts to inject a system-level ignore instruction.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
    {
        pattern: /<\|im_start\|>system/i,
        title: 'Prompt injection: ChatML system override',
        description: 'Agent skill file contains ChatML-format system prompt injection.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'prompt_injection',
    },
];
// Group 2: Data Exfiltration
const DATA_EXFILTRATION_PATTERNS = [
    {
        pattern: /curl\s+[^|]*\|\s*(sh|bash|zsh)\b/i,
        title: 'Data exfiltration: piped remote execution (curl)',
        description: 'Agent skill file pipes curl output directly to a shell, enabling remote code execution.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /wget\s+[^|]*-O\s*-[^|]*\|\s*(sh|bash|zsh)\b/i,
        title: 'Data exfiltration: piped remote execution (wget)',
        description: 'Agent skill file pipes wget output directly to a shell, enabling remote code execution.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /curl\s+[^\n]*\$[({]/i,
        title: 'Data exfiltration: curl with variable interpolation',
        description: 'Agent skill file uses curl with shell variable interpolation, potentially exfiltrating sensitive data.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /wget\s+[^\n]*\$[({]/i,
        title: 'Data exfiltration: wget with variable interpolation',
        description: 'Agent skill file uses wget with shell variable interpolation, potentially exfiltrating sensitive data.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /cat\s+[^\n]*(id_rsa|passwd|shadow|\.env)[^\n]*\|/i,
        title: 'Data exfiltration: sensitive file piped to command',
        description: 'Agent skill file reads a sensitive file (SSH keys, passwd, .env) and pipes it to another command.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /\$\(cat\s+~\/\.ssh/i,
        title: 'Data exfiltration: SSH key read via command substitution',
        description: 'Agent skill file reads SSH keys via command substitution, likely for exfiltration.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /\$(API_KEY|AWS_SECRET|ANTHROPIC_API_KEY|OPENAI_API_KEY|SECRET_KEY|DATABASE_URL|DB_PASSWORD)\b/i,
        title: 'Data exfiltration: env variable reference in skill file',
        description: 'Agent skill file references sensitive environment variables that could be exfiltrated.',
        severity: 'high',
        requiresAIValidation: true,
        group: 'data_exfiltration',
    },
    {
        pattern: /\|\s*base64\b[^\n]*(?:curl|wget|nc|socat)/i,
        title: 'Data exfiltration: base64 encoding for network exfil',
        description: 'Agent skill file encodes data with base64 before sending it over the network.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /(?:curl|wget|nc|socat)\s+[^\n]*\|\s*base64\b/i,
        title: 'Data exfiltration: network data piped through base64',
        description: 'Agent skill file pipes network command output through base64 encoding.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /\bnc\s+[^\n]*\$[({]/i,
        title: 'Data exfiltration: netcat with variable interpolation',
        description: 'Agent skill file uses netcat with shell variable interpolation for data exfiltration.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
    {
        pattern: /\bsocat\s+[^\n]*\$[({]/i,
        title: 'Data exfiltration: socat with variable interpolation',
        description: 'Agent skill file uses socat with shell variable interpolation for data exfiltration.',
        severity: 'critical',
        requiresAIValidation: false,
        group: 'data_exfiltration',
    },
];
// Group 3: Hidden Execution
const HIDDEN_EXECUTION_PATTERNS = [
    {
        pattern: /\bbash\s+-c\b/i,
        title: 'Hidden execution: bash -c in skill file',
        description: 'Agent skill file executes arbitrary shell commands via bash -c.',
        severity: 'high',
        requiresAIValidation: true,
        group: 'hidden_execution',
    },
    {
        pattern: /\beval\s*\(/i,
        title: 'Hidden execution: eval() in skill file',
        description: 'Agent skill file uses eval() to execute dynamically constructed code.',
        severity: 'high',
        requiresAIValidation: true,
        group: 'hidden_execution',
    },
    {
        pattern: /\bexec\s*\(/i,
        title: 'Hidden execution: exec() in skill file',
        description: 'Agent skill file uses exec() to execute commands.',
        severity: 'high',
        requiresAIValidation: true,
        group: 'hidden_execution',
    },
    {
        pattern: /\bsh\s+-c\b/i,
        title: 'Hidden execution: sh -c in skill file',
        description: 'Agent skill file executes arbitrary shell commands via sh -c.',
        severity: 'high',
        requiresAIValidation: true,
        group: 'hidden_execution',
    },
    {
        pattern: /base64\s+-d\s*\|\s*(sh|bash)\b/i,
        title: 'Hidden execution: base64-decoded shell execution',
        description: 'Agent skill file decodes base64 data and pipes it to a shell for execution.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'hidden_execution',
    },
    {
        pattern: /echo\s+[^\n]*\|\s*base64\s+-d\b/i,
        title: 'Hidden execution: echo-to-base64 decode pipeline',
        description: 'Agent skill file decodes a base64 string, likely obfuscating malicious commands.',
        severity: 'medium',
        requiresAIValidation: true,
        group: 'hidden_execution',
    },
    {
        pattern: /crontab\s/i,
        title: 'Hidden execution: crontab modification',
        description: 'Agent skill file modifies crontab entries for persistence.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'hidden_execution',
    },
    {
        pattern: />>?\s*~?\/?[^\s]*(\.bashrc|\.bash_profile|\.profile|\.zshrc)\b/i,
        title: 'Hidden execution: shell profile modification',
        description: 'Agent skill file modifies shell profiles (.bashrc, .zshrc, etc.) for persistence.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'hidden_execution',
    },
    {
        pattern: /[\u200B-\u200F]/,
        title: 'Hidden execution: zero-width Unicode characters',
        description: 'Agent skill file contains invisible zero-width Unicode characters that may hide malicious content.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'hidden_execution',
    },
    {
        pattern: /[\u202A-\u202E]/,
        title: 'Hidden execution: RTL override characters',
        description: 'Agent skill file contains bidirectional text override characters that can visually hide code direction.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'hidden_execution',
    },
    {
        pattern: /[\uFEFF]/,
        title: 'Hidden execution: BOM character mid-file',
        description: 'Agent skill file contains a Byte Order Mark character in an unexpected position, potentially hiding content.',
        severity: 'high',
        requiresAIValidation: false,
        group: 'hidden_execution',
    },
];
// Group 4: Tool/Function Description Poisoning (JSON/YAML)
const DESCRIPTION_POISONING_PATTERNS = [
    {
        pattern: /"description"\s*:\s*"[^"]*(?:ignore|override|before|first run|execute|curl|wget|bash)\b[^"]*/i,
        title: 'Description poisoning: injection in tool description',
        description: 'Tool description field contains injection language (ignore, override, execute commands).',
        severity: 'high',
        requiresAIValidation: true,
        group: 'description_poisoning',
    },
    {
        pattern: /"description"\s*:\s*"[^"]*(?:system:|<\|im_start\|>)[^"]*/i,
        title: 'Description poisoning: system prompt in tool description',
        description: 'Tool description field contains system prompt injection markers.',
        severity: 'high',
        requiresAIValidation: true,
        group: 'description_poisoning',
    },
];
function detectAgentSkillInjection(content, filePath, options) {
    // Gatekeeper: only process agent skill files
    if (!(0, file_classifier_1.isAgentSkillFile)(filePath)) {
        return [];
    }
    // Skip test/fixture/scanner files
    if ((0, file_classifier_1.isTestOrMockFile)(filePath) || (0, file_classifier_1.isScannerOrFixtureFile)(filePath)) {
        return [];
    }
    const findings = [];
    const lines = content.split('\n');
    const codeBlocks = extractCodeBlocks(content);
    // Track which lines are inside code blocks
    const codeBlockLineSet = new Set();
    for (const block of codeBlocks) {
        const blockLines = block.content.split('\n');
        for (let i = 0; i < blockLines.length; i++) {
            codeBlockLineSet.add(block.startLine + i);
        }
    }
    // Group 1: Prompt Injection — scan ALL lines (prose + code)
    for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
        const line = lines[lineIdx];
        const lineNumber = lineIdx + 1;
        if (isEducationalContext(line))
            continue;
        for (const patternDef of PROMPT_INJECTION_PATTERNS) {
            if (patternDef.pattern.test(line)) {
                findings.push(createFinding(filePath, lineNumber, line.trim(), patternDef));
            }
        }
    }
    // Group 2: Data Exfiltration — scan code blocks + all lines
    for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
        const line = lines[lineIdx];
        const lineNumber = lineIdx + 1;
        if (isEducationalContext(line))
            continue;
        for (const patternDef of DATA_EXFILTRATION_PATTERNS) {
            if (patternDef.pattern.test(line)) {
                findings.push(createFinding(filePath, lineNumber, line.trim(), patternDef));
            }
        }
    }
    // Group 3: Hidden Execution — code blocks for shell commands, all lines for Unicode
    for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
        const line = lines[lineIdx];
        const lineNumber = lineIdx + 1;
        if (isEducationalContext(line))
            continue;
        for (const patternDef of HIDDEN_EXECUTION_PATTERNS) {
            // Unicode patterns scan all lines
            const isUnicodePattern = patternDef.group === 'hidden_execution' &&
                (patternDef.title.includes('Unicode') || patternDef.title.includes('RTL') || patternDef.title.includes('BOM'));
            // Shell execution patterns only in code blocks
            if (!isUnicodePattern && !codeBlockLineSet.has(lineNumber)) {
                continue;
            }
            if (patternDef.pattern.test(line)) {
                findings.push(createFinding(filePath, lineNumber, line.trim(), patternDef));
            }
        }
    }
    // Group 4: Description Poisoning — JSON/YAML files
    if (/\.(json|ya?ml)$/i.test(filePath)) {
        for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
            const line = lines[lineIdx];
            const lineNumber = lineIdx + 1;
            if (isEducationalContext(line))
                continue;
            for (const patternDef of DESCRIPTION_POISONING_PATTERNS) {
                if (patternDef.pattern.test(line)) {
                    findings.push(createFinding(filePath, lineNumber, line.trim(), patternDef));
                }
            }
        }
    }
    return findings;
}
// ============================================================================
// Helpers
// ============================================================================
let findingCounter = 0;
function createFinding(filePath, lineNumber, lineContent, patternDef) {
    return {
        id: `agent-skill-${++findingCounter}`,
        filePath,
        lineNumber,
        lineContent,
        severity: patternDef.severity,
        category: 'ai_skill_injection',
        title: patternDef.title,
        description: patternDef.description,
        confidence: patternDef.severity === 'critical' ? 'high' : 'medium',
        layer: 1,
        source: 'config',
        requiresAIValidation: patternDef.requiresAIValidation,
        baseConfidence: BASE_CONFIDENCE,
    };
}
//# sourceMappingURL=agent-skill-injection.js.map