#!/usr/bin/env python3
"""agentscan: a small, local, read-only scanner for AI-agent instruction and config files.

It looks at files such as AGENTS.md, CLAUDE.md, SKILL.md, .cursor/rules, .mcp.json and similar,
and flags patterns that commonly cause trouble: hidden characters, instruction-override text,
remote-script execution, secrets, unpinned or over-broad MCP servers, auto-approve settings.

It makes no network calls, executes nothing it scans, and prints findings only.
A finding is a prompt to look, not proof of a problem; a clean run is not proof of safety.
Python 3.8+, standard library only. MIT licence (see LICENSE text at the bottom of this file).

Usage:
  python3 agentscan.py PATH [PATH ...]            scan files/folders
  python3 agentscan.py . --format json            machine-readable output
  python3 agentscan.py . --min-severity medium    hide low findings
  python3 agentscan.py . --rules rules-pro.json   add extra regex rules from a JSON file
  python3 agentscan.py --list-rules               show built-in rules
Exit code: 0 = no findings at or above --fail-on (default high), 1 = findings, 2 = usage error.
"""
import argparse, json, os, re, sys, unicodedata

VERSION = "1.0.0"
SEV = {"info": 0, "low": 1, "medium": 2, "high": 3, "critical": 4}
MAX_BYTES = 2_000_000

# File names / path fragments treated as agent-related (case-insensitive).
NAME_HINTS = ("agents.md", "claude.md", "gemini.md", "skill.md", "copilot-instructions.md", ".cursorrules",
              ".mcp.json", "mcp.json", "mcp_settings.json", "claude_desktop_config.json", "settings.json",
              "settings.local.json", "config.toml", "windsurfrules", "aider.conf.yml", ".aider", "hooks.json")
DIR_HINTS = (".cursor/rules", ".claude/", ".codex/", ".gemini/", ".github/instructions", ".agents/", "skills/", ".windsurf/", ".roo/", ".continue/")
TEXT_EXT = (".md", ".mdc", ".txt", ".json", ".toml", ".yml", ".yaml", ".sh", ".py", ".js", ".ts")
SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", ".next", "target"}

INVISIBLE = {
    0x200B: "ZERO WIDTH SPACE", 0x200C: "ZERO WIDTH NON-JOINER", 0x200D: "ZERO WIDTH JOINER", 0x2060: "WORD JOINER",
    0xFEFF: "ZERO WIDTH NO-BREAK SPACE (BOM, not at start)", 0x00AD: "SOFT HYPHEN",
}
BIDI = set(range(0x202A, 0x202F)) | set(range(0x2066, 0x206A))

# (id, severity, title, regex, why, advice, flags)
RULES = [
 ("AS010", "high", "Instruction-override phrase",
  r"\b(ignore|disregard|forget|override)\b[^\n]{0,40}\b(previous|prior|above|earlier|all|system|safety)\b[^\n]{0,30}\b(instructions?|rules?|prompts?|guidelines?|polic(?:y|ies))\b",
  "Text that tells an agent to drop its earlier instructions is the classic prompt-injection shape.",
  "Read the surrounding text. If it is a quoted example in documentation, add an allow-comment; otherwise remove it.", re.I),
 ("AS011", "medium", "Secrecy instruction aimed at the user",
  r"\b(do not|don't|never)\s+(tell|inform|notify|alert|let)\s+(the\s+|your\s+)?(user|human|operator|owner)\b(?!\s+(until|if|when|how)\b)|\b(hide|conceal)\b[^\n]{0,30}\bfrom\s+(the\s+|your\s+)?(user|human|operator|owner)\b",
  "Files that tell an agent to hide actions from the person it works for deserve a close read.",
  "Remove, or rewrite so actions are reported to the user.", re.I),
 ("AS012", "high", "Instruction to send data to an external address",
  r"\b(send|post|upload|forward|exfiltrate|email|curl|transmit)\b[^\n]{0,60}(?<![\w])(secrets?|credentials?|api[ _-]?keys?|tokens?|env(?:ironment)? variables?|\.env\b|ssh keys?|private keys?|passwords?)(?![\w])[^\n]{0,60}\b(to|at|via)\b",
  "Instructions that move secrets off the machine are a common injection goal.",
  "Remove. Agents should never be told to transmit credentials.", re.I),
 ("AS013", "medium", "Role or authority claim inside a content file",
  r"(^|\n)\s*(system|assistant|developer)\s*:\s*\S",
  "Fake role markers inside a file can trick some pipelines into treating file text as higher-priority instructions.",
  "Use normal prose or a fenced example instead of role-prefixed lines.", re.I),
 ("AS020", "high", "Remote script piped to a shell",
  r"(curl|wget|iwr|Invoke-WebRequest|fetch)\b[^\n|;]{0,200}\|\s*(sudo\s+)?(ba|z|da)?sh\b|(iex|Invoke-Expression)\s*\(?\s*\(?\s*(iwr|Invoke-WebRequest|New-Object Net\.WebClient)",
  "Running whatever a URL returns means the URL's owner controls your machine.",
  "Download, read and pin a checksum, or use a package manager with a lockfile.", re.I),
 ("AS021", "high", "Decoded payload executed",
  r"(base64\s+(-d|--decode)|atob\(|b64decode|FromBase64String)[^\n]{0,120}(\|\s*(ba|z)?sh|eval|exec|bash|powershell|python)",
  "Encoded commands that get executed hide what will run.",
  "Decode it yourself and read the result; replace with plain, reviewable commands.", re.I),
 ("AS022", "medium", "Eval or dynamic exec of text",
  r"\b(eval|exec)\s*\(\s*(?!['\"]\s*\))",
  "Dynamic execution of strings in a config or skill script widens what an injected instruction can do.",
  "Prefer explicit commands; if needed, document why.", 0),
 ("AS023", "medium", "Privilege escalation in instructions",
  r"\b(sudo\s+(-S\s+)?\w|chmod\s+(-R\s+)?(777|a\+rwx)|chown\s+-R\s+root|--privileged|NOPASSWD)",
  "Instructions that elevate privileges or open permissions give a mistaken or hijacked agent more reach than it needs.",
  "Use the least privilege that works; avoid blanket 777.", re.I),
 ("AS024", "medium", "Destructive command in instructions",
  r"\b(rm\s+-rf\s+(/|~|\$HOME|\*)|git\s+push\s+(-f|--force)(?!-with-lease)|git\s+reset\s+--hard|drop\s+(table|database)|mkfs\.|dd\s+if=.+of=/dev/)",
  "Destructive commands in standing instructions run without a human looking at them.",
  "Require an explicit user approval step for destructive actions.", re.I),
 ("AS030", "critical", "Private key block",
  r"-----BEGIN (RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----",
  "A private key is stored in a text file that may be shared or read by an agent.",
  "Remove it, rotate the key, and use a secret store.", 0),
 ("AS031", "high", "Cloud or code-host token",
  r"\b(AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,}|glpat-[A-Za-z0-9_\-]{20}|xox[abprs]-[A-Za-z0-9\-]{10,}|AIza[0-9A-Za-z_\-]{35})\b",
  "A token with a well-known prefix is present in the file.",
  "Revoke and rotate it now, then load secrets from the environment or a secret manager.", 0),
 ("AS032", "high", "LLM or payment API key",
  r"\b(sk-[A-Za-z0-9_\-]{32,}|sk_live_[A-Za-z0-9]{20,}|rk_live_[A-Za-z0-9]{20,}|sk-ant-[A-Za-z0-9_\-]{30,})\b",
  "A key for an AI provider or payment processor is in the file.",
  "Revoke and rotate it; check provider logs for use.", 0),
 ("AS033", "medium", "Hard-coded secret assignment",
  r"(?i)\b(api[_-]?key|secret|token|passwd|password|authorization)\b\s*[:=]\s*[\"']?(?!\$|\{|<|your|xxx|changeme|example|placeholder|\*\*\*)[A-Za-z0-9_\-/+=]{16,}[\"']?",
  "A long literal value is assigned to a name that looks like a secret.",
  "Confirm whether it is real. If so, rotate it and move it out of the file.", 0),
 ("AS040", "medium", "MCP/tool server launched without a pinned version",
  r"\"(command)\"\s*:\s*\"(npx|uvx|pipx|bunx|pnpm dlx|yarn dlx)\"[^}]{0,200}?\"args\"\s*:\s*\[(?![^\]]*@\d)[^\]]*\]",
  "Launching a package with npx/uvx and no version means each start can run different code.",
  "Pin an exact version (package@1.2.3) and review updates.", re.S),
 ("AS041", "high", "Auto-approve or permission bypass enabled",
  r"(dangerously[-_]?skip[-_]?permissions|--yolo\b|\"?(alwaysAllow|autoApprove|auto_approve|bypassPermissions)\"?\s*[:=]\s*(true|\[\s*\"?\*|\"\*\"|\[[^\]]+\]))|trust[-_]all[-_]tools|approvalPolicy\"?\s*[:=]\s*\"?never",
  "Turning off approvals removes the human check that limits what an injected instruction can do.",
  "Allow-list specific read-only tools; keep approvals on for writes, network and shell.", re.I),
 ("AS042", "medium", "Filesystem tool rooted at / or home",
  r"(server-filesystem|filesystem)[^\n]{0,200}[\"' ](/|~|\$HOME|C:\\\\?)[\"',\]\s]",
  "A filesystem server rooted at the whole disk exposes keys, history and other projects.",
  "Root it at the one project directory.", re.I),
 ("AS043", "medium", "Remote tool server over plain HTTP",
  r"\"(url|serverUrl|endpoint)\"\s*:\s*\"http://(?!localhost|127\.0\.0\.1|\[::1\])",
  "Traffic, and any tokens in it, can be read or altered on the network.",
  "Use https, and a server you control or have reviewed.", re.I),
 ("AS044", "medium", "Secrets passed through to a tool server environment",
  r"\"env\"\s*:\s*\{[^}]*\"[A-Z0-9_]*(KEY|TOKEN|SECRET|PASSWORD)[A-Z0-9_]*\"\s*:\s*\"(?!\$|\$\{)[^\"]{12,}\"",
  "A literal secret sits in the tool config, which often gets committed or shared.",
  "Reference an environment variable instead of pasting the value.", re.S | re.I),
 ("AS050", "medium", "Known exfiltration or paste endpoint",
  r"(webhook\.site|requestbin|pipedream\.net|ngrok(-free)?\.(io|app|dev)|burpcollaborator|oast\.(fun|site|live|pro)|interact\.sh|pastebin\.com/raw|discord(app)?\.com/api/webhooks|hooks\.slack\.com/services|transfer\.sh|temp\.sh)",
  "These hosts are often used to receive stolen data from injected instructions.",
  "Confirm it is intentional and documented; otherwise remove.", re.I),
 ("AS051", "low", "Raw IP address URL",
  r"https?://(?!127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|0\.0\.0\.0)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
  "Instructions that fetch from a bare IP skip domain-based review and blocklists.",
  "Prefer a named, reviewable host.", 0),
 ("AS052", "low", "Long encoded blob",
  r"[A-Za-z0-9+/]{200,}={0,2}",
  "A long run of base64-like text can hide a payload or a second set of instructions.",
  "Decode it in a safe place and confirm what it is.", 0),
 ("AS060", "low", "Hidden HTML comment with instructions",
  r"<!--[^>]{0,2000}?\b(agent|assistant|ai|claude|gpt|model|you must|you should|always|never)\b[^>]{0,2000}?-->",
  "HTML comments are invisible when a file is rendered but are read by agents.",
  "Move needed guidance into visible text.", re.I | re.S),
]
# Rules whose matches are ignored when the same sentence is a prohibition ("never send secrets to ...").
NEGATABLE = {"AS012", "PR011", "PR012", "PR013", "PR015", "PR016", "PR020", "PR037"}
NEG_RE = re.compile(r"(never|do not|don't|must not|should not|shouldn't|not to|avoid|refuse to|stop)\W[^\n.;]{0,60}$", re.I)
ALLOW_RE = re.compile(r"agentscan:\s*allow(?:\s+(AS\d{3}))?", re.I)

def load_extra(path):
    with open(path, encoding="utf-8") as f:
        data = json.load(f)
    out = []
    for r in data.get("rules", data if isinstance(data, list) else []):
        fl = 0
        for ch in r.get("flags", ""):
            fl |= {"i": re.I, "s": re.S, "m": re.M}.get(ch, 0)
        out.append((r["id"], r.get("severity", "medium"), r["title"], r["pattern"], r.get("why", ""), r.get("advice", ""), fl))
    return out

def is_agent_file(path):
    p = path.replace("\\", "/").lower()
    base = os.path.basename(p)
    if base in NAME_HINTS or any(base.endswith(h) for h in (".mdc",)):
        return True
    return any(h in p for h in DIR_HINTS) and p.endswith(TEXT_EXT)

def walk(paths, scan_all):
    for root in paths:
        if os.path.isfile(root):
            yield root; continue
        for d, dirs, files in os.walk(root):
            dirs[:] = [x for x in dirs if x not in SKIP_DIRS]
            for fn in files:
                p = os.path.join(d, fn)
                if scan_all and fn.lower().endswith(TEXT_EXT) or is_agent_file(p):
                    yield p

def line_of(text, idx):
    return text.count("\n", 0, idx) + 1

def snippet(text, a, b):
    s = text[max(0, a - 0):b].replace("\n", " ")
    s = re.sub(r"\s+", " ", s).strip()
    return (s[:117] + "...") if len(s) > 120 else s

def scan_text(path, text, rules):
    findings = []
    allow_lines, allow_all = {}, set()
    for i, ln in enumerate(text.split("\n"), 1):
        m = ALLOW_RE.search(ln)
        if m:
            allow_lines.setdefault(i, set()).add((m.group(1) or "*").upper())
    def allowed(rule_id, line):
        for l in (line, line - 1):
            s = allow_lines.get(l)
            if s and ("*" in s or rule_id in s):
                return True
        return False
    # invisible and bidi characters
    seen = set()
    for i, ch in enumerate(text):
        cp = ord(ch)
        if cp == 0xFEFF and i == 0:
            continue
        kind = None
        if cp in INVISIBLE: kind = ("AS001", "high", "Hidden zero-width character", INVISIBLE[cp])
        elif cp in BIDI: kind = ("AS002", "high", "Bidirectional control character", "U+%04X" % cp)
        elif 0xE0000 <= cp <= 0xE007F: kind = ("AS003", "critical", "Unicode tag character (invisible text)", "U+%05X" % cp)
        elif unicodedata.category(ch) == "Cf" and cp not in INVISIBLE and cp not in BIDI and cp != 0x200E and cp != 0x200F:
            kind = ("AS004", "medium", "Other invisible format character", "U+%04X" % cp)
        if kind:
            ln = line_of(text, i)
            key = (kind[0], ln)
            if key in seen or allowed(kind[0], ln): continue
            seen.add(key)
            findings.append(dict(rule=kind[0], severity=kind[1], title=kind[2], path=path, line=ln, detail=kind[3],
                                 why="Characters you cannot see can carry instructions that a reviewer will not notice.",
                                 advice="Delete the character (or the whole line) and re-save as plain UTF-8. Show hidden characters in your editor.",
                                 snippet=""))
    for rid, sev, title, pat, why, adv, fl in rules:
        try:
            rx = re.compile(pat, fl)
        except re.error:
            continue
        for m in rx.finditer(text):
            ln = line_of(text, m.start())
            if allowed(rid, ln): continue
            if rid in NEGATABLE:
                ls = text.rfind("\n", 0, m.start()) + 1
                if NEG_RE.search(text[ls:m.start()]): continue
            findings.append(dict(rule=rid, severity=sev, title=title, path=path, line=ln, detail="", why=why, advice=adv,
                                 snippet=snippet(text, m.start(), m.end())))
    return findings

def scan_file(path, rules):
    try:
        if os.path.getsize(path) > MAX_BYTES:
            return [dict(rule="AS000", severity="info", title="File skipped (too large)", path=path, line=0, detail="", why="", advice="", snippet="")]
        with open(path, "rb") as f:
            raw = f.read()
    except OSError as e:
        return [dict(rule="AS000", severity="info", title="Could not read file: %s" % e.__class__.__name__, path=path, line=0, detail="", why="", advice="", snippet="")]
    if b"\x00" in raw[:4096]:
        return []
    text = raw.decode("utf-8", errors="replace")
    return scan_text(path, text, rules)

def redact(s):
    s = re.sub(r"(AKIA|ASIA)[0-9A-Z]{4}[0-9A-Z]{12}", lambda m: m.group(1) + "****", s)
    s = re.sub(r"(gh[pousr]_|github_pat_|glpat-|xox[abprs]-|sk-ant-|sk_live_|rk_live_|sk-)[A-Za-z0-9_\-]{6,}", lambda m: m.group(1) + "****", s)
    return s

def main(argv=None):
    ap = argparse.ArgumentParser(prog="agentscan", description="Scan AI-agent instruction/config files for risky patterns (local, read-only).")
    ap.add_argument("paths", nargs="*")
    ap.add_argument("--format", choices=["text", "json"], default="text")
    ap.add_argument("--min-severity", choices=list(SEV), default="low")
    ap.add_argument("--fail-on", choices=list(SEV), default="high")
    ap.add_argument("--rules", action="append", default=[], help="extra rules JSON file (repeatable)")
    ap.add_argument("--all-text", action="store_true", help="scan every text file, not only agent-related names")
    ap.add_argument("--list-rules", action="store_true")
    ap.add_argument("--version", action="version", version="agentscan " + VERSION)
    a = ap.parse_args(argv)
    rules = list(RULES)
    for rp in a.rules:
        try: rules += load_extra(rp)
        except Exception as e:
            print("cannot load rules %s: %s" % (rp, e), file=sys.stderr); return 2
    if a.list_rules:
        print("AS001-AS004 invisible / bidi / tag characters")
        for r in rules: print("%s  %-8s %s" % (r[0], r[1], r[2]))
        return 0
    if not a.paths:
        ap.print_usage(sys.stderr); return 2
    files = sorted(set(walk(a.paths, a.all_text)))
    allf = []
    for p in files: allf += scan_file(p, rules)
    allf = [f for f in allf if SEV[f["severity"]] >= SEV[a.min_severity]]
    for f in allf: f["snippet"] = redact(f["snippet"])
    allf.sort(key=lambda f: (-SEV[f["severity"]], f["path"], f["line"]))
    if a.format == "json":
        print(json.dumps(dict(tool="agentscan", version=VERSION, files_scanned=len(files), findings=allf), indent=2))
    else:
        for f in allf:
            print("[%s] %s %s  %s:%s" % (f["severity"].upper(), f["rule"], f["title"], f["path"], f["line"]))
            if f["snippet"]: print("    > " + f["snippet"])
            if f["detail"]: print("    " + f["detail"])
            if f["why"]: print("    why: " + f["why"])
            if f["advice"]: print("    do:  " + f["advice"])
        counts = {}
        for f in allf: counts[f["severity"]] = counts.get(f["severity"], 0) + 1
        print("\nagentscan %s: scanned %d file(s), %d finding(s) %s" % (VERSION, len(files), len(allf), json.dumps(counts, sort_keys=True) if counts else ""))
        print("Findings are prompts to look, not proof. A clean result is not proof of safety.")
    worst = max([SEV[f["severity"]] for f in allf], default=-1)
    return 1 if worst >= SEV[a.fail_on] else 0

if __name__ == "__main__":
    sys.exit(main())

# MIT License. Copyright (c) 2026 hackerdb.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software. The Software
# is provided "as is", without warranty of any kind.
