Introducing a new way to review your PRs.

Read the announcement

affaan-m / agentshield

AI agent security scanner. Detect vulnerabilities in agent configurations, MCP servers, and tool permissions. Available as CLI, GitHub Action, ECC plugin, and GitHub App integration. 🛡️

View on GitHub

20 documents · Updated Sep 11, 2026

docs / security-rule-engine

Security rule engine

The security rule engine is the static analysis layer that reviews discovered AI-agent configuration and support files for unsafe capability, instruction, integration, permission, package, secret, and skill patterns. It turns those observations into findings that describe the risk, point to the source file, preserve useful evidence, and can include a fix suggestion for the wider security report. See the parent page Static security analysis for the scan lifecycle and Repository discovery and context for how files reach this engine.

Security analysis boundary

The engine evaluates text and structured configuration that can change an agent's behavior or expose the host. A ConfigFile is the shared input unit: it has a path, a detected type, and file content. A rule accepts one such file and may also inspect the full discovered file set when a finding depends on related files. (src/types.ts• L62-98)

The built-in set combines general risk checks with checks for named agent harnesses. The registry also includes cross-harness MCP checks, threat data, and an optional external rule-pack path. These groups use shared finding categories, so one risk can be found in more than one product surface. (src/…/index.ts• L1-41)

Rule familyMain security questionTypical source surface
AgentsDoes an agent have more capability than its role needs, or contain hostile instructions?Agent definitions, subagents, CLAUDE.md, slash commands, and custom-agent files
Harness policyDoes a named agent product weaken approvals, sandboxing, trust, or model routing?Claude Code, Codex, Hermes, Gemini CLI, OpenCode, Cursor, and Copilot settings
HooksCan automatic actions run commands, leak data, persist, or change the host?Hook settings, hook manifests, and hook code
MCP integrationsDoes a server expand access, trust remote content, or weaken approval and transport boundaries?MCP server configurations and tool descriptions
PermissionsCan the agent run, write, connect, or change sensitive resources?Allow, deny, approval, sandbox, and trust settings
Package managersCan dependency installation run unsafe scripts, expose registry credentials, or accept a new package too quickly?npm, pnpm, and Yarn configuration
Prompt defensesDo system instructions resist role changes, instruction overrides, indirect injection, and unsafe output?Agent prompts, CLAUDE.md, and local rules
SecretsAre keys, passwords, private material, or sensitive endpoints stored or exposed in text?All discovered file types, with targeted checks for some files
SkillsDoes a skill have safe invocation, observation, version, and rollback controls?SKILL.md, skill frontmatter, and related history files
Threat intelligenceDoes an MCP package or hook match known vulnerable, malicious, or persistent software?MCP commands, arguments, hook code, and paths
External rule packsDoes an explicitly supplied rule pack identify an additional pattern?File content and optional file-type filters

Rule families

Agent capability and instruction rules

Agent rules review both what an agent can do and what its instructions tell it to do. They flag missing or excessive tool limits, unsafe combinations such as web access with file writing, unrestricted delegation, and full discovery-to-execution chains. They also detect instructions that could cause remote downloads, data theft, persistence, privilege escalation, destructive actions, allow-list bypass, secret leakage, or output suppression. (src/…/agents.ts• L264-707, src/…/agents.ts• L821-1007, src/…/agents.ts• L1327-1924)

The checks apply to agent definitions and, where the format permits, slash commands, CLAUDE.md, custom-agent files, and subagent definitions. The engine reads structured metadata when it exists, but it also treats instruction text as a security surface. This matters because a safe tool list does not make a prompt safe if the prompt directs the agent to bypass that list or pass harmful instructions to another agent. (src/…/agents.ts• L175-232, src/…/claude-code.ts• L1319-1570, src/…/harnesses.ts• L1036-1124)

References: src/…/agents.ts• L264-707 src/…/agents.ts• L821-1007 src/…/agents.ts• L1327-1924 src/…/claude-code.ts• L1319-1570 src/…/harnesses.ts• L1036-1124

Harness policy rules

Harness rules assess product-specific controls that general agent checks cannot interpret reliably. They turn each harness's own approval, sandbox, trust, environment, model-provider, and project-scope settings into findings about the real boundary that a user or cloned repository can change. (src/…/index.ts• L13-41)

The current named surfaces include:

These checks fail closed when a structured file cannot be parsed or cannot be identified as the named harness. This prevents a generic JSON file from being treated as a product policy file, but it also means a new harness shape needs explicit discovery and recognition before its rules can report findings. (src/…/harnesses.ts• L201-229, src/…/codex.ts• L229-232, src/…/hermes.ts• L51-54)

References: src/…/claude-code.ts• L322-756 src/…/codex.ts• L417-1035 src/…/hermes.ts• L131-421 src/…/harnesses.ts• L201-229 src/…/harnesses.ts• L314-1277

Hook execution rules

Hook rules review actions that run automatically before or after tool use and at session boundaries. They look for command injection, remote downloads, network and environment-variable exfiltration, access to credential stores, privilege changes, destructive commands, persistence, logging evasion, and host or container escape behavior. (src/…/hooks.ts• L773-1010, src/…/hooks.ts• L1117-1389, src/…/hooks.ts• L1621-2070, src/…/hooks.ts• L2200-2745)

The family also checks whether the safety boundary itself is dependable. Missing PreToolUse checks, silently suppressed errors, broad network hooks, and missing end-of-session checks produce configuration findings rather than claims that an attack occurred. Defensive guard commands are treated differently from offensive use: a hook that searches for a dangerous command and rejects it is reported as a guard pattern instead of as an executed command. (src/…/hooks.ts• L384-555, src/…/hooks.ts• L1013-1115, src/…/guard-context.ts• L332-394)

References: src/…/hooks.ts• L773-1010 src/…/hooks.ts• L1013-1389 src/…/hooks.ts• L1621-2070 src/…/hooks.ts• L2200-2745 src/…/guard-context.ts• L332-394

MCP integration rules

MCP rules review each configured server as a capability and trust boundary. They flag high-impact server roles such as shell, file system, browser, database, and messaging access. They also check unrestricted paths, external URL transport, remote code execution, shell wrappers, unsafe environment overrides, broad interface binding, wildcard CORS, automatic approval, weak time limits, and unpinned launch packages. (src/…/mcp.ts• L196-534, src/…/mcp.ts• L537-970, src/…/mcp.ts• L1010-1354)

Remote MCP rules give the same review to server definitions across several harnesses. They cover TLS, private and metadata addresses, OAuth endpoints and scopes, credentials in URLs or headers, stdio bridges, shell and interpreter launchers, proxy environment settings, host-secret forwarding, broad auto-approval, tool-description poisoning, tool shadowing, and mutable container images. (src/…/mcp-remote.ts• L343-567, src/…/mcp-remote.ts• L813-1107, src/…/mcp-remote.ts• L1109-1383, src/…/mcp-remote.ts• L1385-1553)

MCP descriptions and names are part of the input to an AI agent. The tool-poisoning checks therefore inspect names, descriptions, arguments, environment values, and file paths for hidden instructions, sensitive data collection, cross-tool steering, and known exfiltration endpoints. This extends the review beyond the server process to the text that can influence tool selection. (src/…/mcp-remote.ts• L762-809, src/…/mcp-remote.ts• L1385-1499)

Template and documentation MCP files receive runtime context. Structural risks in an example are labeled and may receive lower severity, while secret findings remain visible because an example can still contain a real credential. (src/…/mcp.ts• L80-184, src/…/mcp-remote.ts• L140-154)

References: src/…/mcp.ts• L196-534 src/…/mcp.ts• L537-970 src/…/mcp-remote.ts• L343-567 src/…/mcp-remote.ts• L813-1107 src/…/mcp-remote.ts• L1385-1553

Permission rules

Permission rules assess the allow, deny, ask, approval, sandbox, and trust model that limits tool use. They find unrestricted shell, write, edit, network, interpreter, container, sensitive-path, and destructive Git access. They also find missing denials, contradictory entries, broad prefix grants, missing permission blocks, model endpoint overrides, and affirmative permission-bypass flags. (src/…/permissions.ts• L367-694, src/…/permissions.ts• L696-1054, src/…/permissions.ts• L1057-1190)

Permission entries are normalized before comparisons. This lets the engine recognize equivalent command forms and detect when a broad prefix silently covers a narrower rule. Checks focus on allow entries when they assess excessive access; a dangerous pattern in a deny or ask list is a prohibition, not permission to run it. (src/…/permission-entries.ts• L1-102, src/…/permissions.ts• L17-20, src/…/permissions.ts• L382-427)

References: src/…/permissions.ts• L367-694 src/…/permissions.ts• L696-1054 src/…/permissions.ts• L1057-1190 src/…/permission-entries.ts• L1-102

Package manager rules

Package manager rules treat dependency setup as an execution and credential boundary. They find plaintext registry credentials, enabled dependency lifecycle scripts, broad pnpm build approval, and missing or weak release-age gates. The goal is to reduce the chance that a new or compromised dependency runs with workstation or CI access before it receives review. (src/…/package-manager.ts• L221-385, src/…/package-manager.ts• L388-529)

The family supports npm-style line settings and YAML settings used by Yarn and pnpm. It distinguishes an environment-variable reference from a value stored in the file and reports unsupported settings that can create false confidence. (src/…/package-manager.ts• L45-186, src/…/package-manager.ts• L391-527)

References: src/…/package-manager.ts• L11-18 src/…/package-manager.ts• L221-385 src/…/package-manager.ts• L388-529

Prompt defense rules

Prompt defense rules measure whether prompt-bearing files state clear boundaries against common attacks. They check for defenses against role and instruction changes, internal-data disclosure, unsafe output, language and Unicode bypasses, context overflow, indirect injection, social engineering, harmful content, abuse, and invalid input. A missing defense produces a finding because absence of a control is useful posture information. (src/…/prompt-defense.ts• L3-177)

The checks apply to CLAUDE.md, agent definitions, and rules under the local Claude rules surface. They do not claim that a prompt will block every attack. They show which stated safeguards are missing so an engineer can review the prompt as part of the larger permission and tool model. (src/…/prompt-defense.ts• L130-177)

References: src/…/prompt-defense.ts• L3-177

Secret detection rules

Secret rules search for recognizable keys, tokens, passwords, private keys, connection strings, webhook URLs, internal service addresses, and other sensitive values. They also identify ways to expose secrets, such as echoing environment variables, referencing credential files from prompts, passing too many sensitive variables to an MCP server, or placing credentials in URLs. (src/…/secrets.ts• L7-147, src/…/secrets.ts• L272-471, src/…/secrets.ts• L475-787)

The engine masks evidence for many secret matches and skips clear variable references or likely example values in selected contexts. This reduces accidental disclosure in reports without treating every example as an active credential. The rule family still reports private key material and other high-confidence exposure patterns wherever they occur. (src/…/secrets.ts• L149-270, src/…/claude-code.ts• L91-118, src/…/mcp-remote.ts• L161-223)

References: src/…/secrets.ts• L7-147 src/…/secrets.ts• L149-270 src/…/secrets.ts• L272-471 src/…/secrets.ts• L475-787

Skill governance rules

Skill rules check whether a skill can be observed, improved, versioned, and reversed safely. A skill is considered stronger when its definition names observation and feedback hooks and has version and rollback metadata. The Claude Code skill checks add controls for dynamic shell context, broad pre-approved tools, persistent hooks, trigger hijacking, wrong frontmatter keys, and model-invoked side effects. (src/…/skills.ts• L1-90, src/…/claude-code.ts• L1049-1317)

These rules produce posture findings for missing governance rather than security claims about a skill's contents. The health analysis links a SKILL.md file to nearby history files and classifies observed skills by score. That relationship is why skill checks receive the complete discovered file set instead of only the current file. (src/…/health.ts• L83-125, src/…/health.ts• L215-381)

References: src/…/skills.ts• L1-90 src/…/claude-code.ts• L1049-1317 src/…/health.ts• L83-125 src/…/health.ts• L215-381

Threat intelligence rules

Threat intelligence rules add known-bad knowledge to structural hook and MCP checks. They compare MCP package arguments with curated records for vulnerable, malicious, compromised, or typosquatted software. Hook checks also recognize known AI-tool persistence indicators. A match becomes a high-severity finding with the affected indicator and a direction for containment or replacement. (src/…/mcp-cve.ts• L9-148, src/…/hooks.ts• L704-819)

This source is a point-in-time knowledge set. A clean result means that no registered match was found in the scanned content; it does not prove that an unknown package, later compromise, or new persistence technique is safe. (src/…/cve-database.ts• L1-53)

References: src/…/mcp-cve.ts• L9-148 src/…/hooks.ts• L704-819 src/…/cve-database.ts• L1-53

External rule-pack rules

External rule packs let an operator add declarative pattern checks without recompiling the scanner. A pack defines a version, rule identity, severity, category, patterns, optional flags, and optional file-type limits. The loader validates the pack, rejects duplicate or invalid rules, fails closed on errors, and limits findings from one rule on one file. (src/…/external.ts• L5-19, src/…/external.ts• L21-57, src/…/external.ts• L120-196)

These rules are explicit operator input rather than part of the built-in registry. Their findings use the same shared finding shape as built-in rules, so they enter the normal report and score flow after loading. The pack is trusted only because the operator chose it; arbitrary patterns remain a known risk of the external input path. (src/…/external.ts• L86-117)

References: src/…/external.ts• L5-19 src/…/external.ts• L81-117 src/…/external.ts• L120-196

Finding pipeline

The scanner connects repository discovery to rule evaluation and then adds source context before reporting. The flow below shows the main path from files to findings and the outputs that are calculated from the same scan result.

flowchart LR
    A[Discovered config files] --> B[Built-in rule families]
    A --> C[Optional external rule packs]
    B --> D[Raw findings]
    C --> D
    D --> E[Runtime and source context]
    E --> F[Severity sort]
    F --> G[Security report]
    F --> H[Security score and summary]
    A --> I[Skill health]
    I --> G

Rule execution

scan discovers files, loads the built-in rules, and calls every rule for every compatible file. The optional allFiles input lets cross-file checks find companion hook manifests, plugin files, and skill history. A rule can return zero, one, or many findings, so the engine does not stop after the first match. (src/…/index.ts• L24-52)

The discovery layer assigns types such as settings-json, mcp-json, agent-md, skill-md, hook-script, hook-code, and harness-specific files. Rules use those types and paths to avoid applying a check to an unrelated surface. Referenced hook code and related plugin files can also enter the scan so a configuration finding can be checked against the file it invokes. (src/types.ts• L67-98, src/…/discovery.ts• L152-239, src/…/discovery.ts• L268-429)

The built-in registry is the boundary between rule modules and the scanner. It assembles general families first and then harness-specific families. A family that is not included in getBuiltinRules never runs. (src/…/index.ts• L18-41)

References: src/…/index.ts• L18-41 src/…/index.ts• L24-52 src/types.ts• L67-98 src/…/discovery.ts• L152-239 src/…/discovery.ts• L268-429

Finding records

Each finding carries a stable rule-derived identifier, severity, category, title, description, source file, and optional line and evidence. A finding can also carry a fix suggestion with before and after text and an auto flag. This record is the contract between rule families and report formats. (src/types.ts• L15-28, src/types.ts• L51-58)

Findings may be posture notes, active-risk indicators, or source-context observations. Severity expresses the rule's assessment; runtime confidence explains whether the source looks active, optional, cached, templated, or documentary. Rules do not prove that a matched pattern was executed. Guard-context and harness-specific rules use descriptions and lower severities to preserve that distinction. (src/…/guard-context.ts• L332-394, src/…/mcp.ts• L157-184)

References: src/types.ts• L15-28 src/types.ts• L51-58 src/…/guard-context.ts• L332-394 src/…/mcp.ts• L157-184

Source context

Source context changes how findings from examples, templates, plugin content, and optional project files are described and, for structural risks, how much they affect the score. Secret findings remain visible because a secret in an example can still be unsafe, while non-secret structural findings from examples and caches receive lower severity or score weight. (src/…/mcp.ts• L102-184)

References: src/source-context.ts• L1-55 src/…/mcp.ts• L102-184 src/…/score.ts• L60-131

Report scoring

The report keeps the full finding list and also summarizes counts by severity, scanned files, and automatic fix suggestions. The score maps findings into five broad areas: secrets, permissions, hooks, MCP, and agents. Skills and injection findings contribute to the agents area, while exposure and general configuration findings map to hooks or permissions. (src/…/score.ts• L18-49, src/…/score.ts• L52-103, src/…/score.ts• L138-160)

The score starts at 100 and subtracts severity-weighted deductions. The final numeric score is the average of the five area scores and maps to grades A through F. Runtime context can reduce the weight of structural findings, but secrets are not reduced by those context weights. (src/…/score.ts• L4-16, src/…/score.ts• L60-131)

References: src/…/score.ts• L4-16 src/…/score.ts• L18-49 src/…/score.ts• L52-103 src/…/score.ts• L138-160

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the registered rule arrays in src/…/index.ts aligned with the FindingCategory and ConfigFileType contracts. A rule that is not exported from the registry never runs.
  • When adding a harness surface, update file discovery and harness recognition together. A rule that cannot identify its input fails closed and produces no finding.
  • Preserve Finding fields, severity names, and category names across rule changes because JSON, Markdown, terminal, scoring, and fix flows consume the same record.
  • Keep permission parsing and normalization aligned. New allow-entry spellings can otherwise evade broad-prefix and destructive-command checks.
  • Keep guard-context checks conservative. A dangerous token in a deny pattern is not the same as an executed command, but an ambiguous match must not be downgraded automatically.
  • When changing MCP traversal, keep server aliases and tool collection aligned across harnesses. Otherwise the same remote server can receive different coverage depending on its config shape.
  • When changing cross-file behavior, keep companion hook paths, plugin references, and skill history naming aligned with discovery and health analysis. These checks depend on related files being present in allFiles.
  • When adding a finding category or changing its meaning, update the score-category map. An unmapped category defaults to the agents score area.
  • When adding an external rule-pack field or constraint, update schema validation, duplicate-ID handling, and the per-rule finding cap together.
  • When changing example or plugin handling, review both finding severity changes and score weighting. A finding can be correctly visible while still being intentionally capped in the score.
  • Keep secret evidence redacted in new structured and harness-specific rules. A finding must not expose the value it tells the user to rotate.

Important failure modes

TriggerConsequenceGuard
A new rule family is defined but not spread into getBuiltinRulesThe scanner silently omits the familyKeep every built-in rule array registered in src/…/index.ts
A new harness file is discovered but its path or key shape is not recognizedHarness-specific policy rules fail closed and produce no findingsKeep discovery types and detectHarness signatures aligned
A permission entry uses a new spelling that the normalizer does not understandA broad allow rule can appear narrow and evade least-privilege checksExtend parsePermissionEntry, normalizePermissionEntry, and coverage checks together
A dangerous token in a guard pattern is treated as an executed commandDefensive hooks produce false high-severity findingsUse isGuardPatternContext and require a deny signal before lowering confidence
A cross-harness MCP shape is missed by the shared server iteratorRemote transport, tool poisoning, and auto-approval risks are not reportedKeep URL aliases, nested server maps, and tool collection in one shared view
An external rule pack has invalid JSON, duplicate IDs, or an invalid patternThe requested pack cannot be trusted as a scan inputReject the pack before execution and cap findings per rule and file
A finding includes raw secret evidenceReports can expose the same sensitive value they warn aboutMask evidence and report a rotation or replacement action
A template or plugin finding loses its runtime confidenceExample risk can look like active production exposure and distort the scorePreserve source-path classification and context adjustment before report generation
A skill history file no longer matches the skill naming conventionSkill health reports the skill as unobserved even when records existKeep history files beside the skill with one of the supported related suffixes

Key files

FileWhy to read it
src/…/index.tsDefines the built-in rule registry and the family assembly order.
src/…/agents.tsIllustrates the agent capability and instruction threat model.
src/…/claude-code.tsDefines Claude Code settings, hook, skill, and subagent policy checks.
src/…/codex.tsDefines Codex approval, sandbox, trust, MCP, provider, and role checks.
src/…/hermes.tsDefines Hermes approval, terminal, chat gateway, and MCP checks.
src/…/harnesses.tsCovers plugins, Gemini CLI, OpenCode, Cursor, Copilot, and instruction imports.
src/…/hooks.ts and src/…/guard-context.tsExplain automatic execution checks and the distinction between a dangerous command and a guard that blocks it.
src/…/mcp.ts and src/…/mcp-remote.tsExplain MCP capability, transport, OAuth, environment, approval, tool-text, and supply-chain checks.
src/…/permission-entries.ts and src/…/permissions.tsDefine normalized allow-entry comparison and the least-privilege view of agent actions.
src/…/package-manager.tsDefines dependency install and registry credential checks.
src/…/prompt-defense.tsDefines the expected defensive posture for prompt-bearing files.
src/…/secrets.tsDefines secret patterns, exposure checks, example handling, and evidence masking.
src/…/skills.ts and src/…/health.tsConnect skill findings with version, rollback, observation, feedback, and run health.
src/…/external.tsDefines the optional external rule-pack contract and failure behavior.
src/…/mcp-cve.ts and src/…/cve-database.tsConnect MCP package checks to curated vulnerability and malicious-package data.
src/…/score.tsDefines finding summaries, score deductions, runtime weighting, and grades.