ezco 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ezco/__init__.py +0 -0
- ezco/__main__.py +5 -0
- ezco/cli.py +186 -0
- ezco/clone.py +205 -0
- ezco/data/popular_npm.json +5002 -0
- ezco/data/popular_pypi.json +5002 -0
- ezco/data/revoke_guide.json +62 -0
- ezco/deep.py +67 -0
- ezco/gate.py +161 -0
- ezco/hook.py +158 -0
- ezco/leaks.py +107 -0
- ezco/mcp_check.py +172 -0
- ezco/packages.py +201 -0
- ezco-0.1.0.dist-info/METADATA +177 -0
- ezco-0.1.0.dist-info/RECORD +19 -0
- ezco-0.1.0.dist-info/WHEEL +5 -0
- ezco-0.1.0.dist-info/entry_points.txt +2 -0
- ezco-0.1.0.dist-info/licenses/LICENSE +21 -0
- ezco-0.1.0.dist-info/top_level.txt +1 -0
ezco/__init__.py
ADDED
|
File without changes
|
ezco/__main__.py
ADDED
ezco/cli.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Command line: `ezco scan <files or folders>`, `ezco install`, `ezco uninstall`.
|
|
2
|
+
`ezco hook` is what git runs before each commit."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ezco import clone, deep, gate, hook, leaks, mcp_check, packages
|
|
11
|
+
|
|
12
|
+
ENV_FILE = re.compile(r"^\.env(\.(?!example$|sample$|template$)[\w.-]+)?$") # .env, .env.local; not .env.example
|
|
13
|
+
SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "env", "__pycache__", "dist", "build", ".next"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def is_dependency_file(path):
|
|
17
|
+
name = Path(path).name
|
|
18
|
+
return name in ("package.json", "pyproject.toml") or (name.startswith("requirements") and name.endswith(".txt"))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def dependencies_in(path, text):
|
|
22
|
+
"""Return (name, ecosystem) pairs from a dependency file, or [] for other files."""
|
|
23
|
+
name = Path(path).name
|
|
24
|
+
if not is_dependency_file(path):
|
|
25
|
+
return []
|
|
26
|
+
text = text.lstrip("\ufeff") # PowerShell 5.1 and Notepad add a BOM; it broke the first name and all of JSON
|
|
27
|
+
if name.endswith(".txt"):
|
|
28
|
+
return [(n, "pypi") for n in packages.parse_requirements(text)]
|
|
29
|
+
try:
|
|
30
|
+
if name == "pyproject.toml":
|
|
31
|
+
return [(n, "pypi") for n in packages.parse_pyproject(text)]
|
|
32
|
+
return [(n, "npm") for n in packages.parse_package_json(text)]
|
|
33
|
+
except (ValueError, AttributeError):
|
|
34
|
+
return [] # empty or broken file: pip/npm itself will complain about that
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def text_checks(lines, path, full_text):
|
|
38
|
+
return leaks.scan_lines(lines, path) + mcp_check.scan_lines(lines, path, full_text)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def walk(paths, ignore):
|
|
42
|
+
"""Yield every file under the given files/folders, skipping junk folders and .ezcoignore."""
|
|
43
|
+
for p in paths:
|
|
44
|
+
if os.path.isdir(p):
|
|
45
|
+
# a folder you name yourself is always scanned, even if .ezcoignore lists it
|
|
46
|
+
rules = [] if hook.is_ignored(os.path.join(p, "x"), ignore) else ignore
|
|
47
|
+
for root, dirs, files in os.walk(p):
|
|
48
|
+
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
|
|
49
|
+
for f in files:
|
|
50
|
+
full = os.path.relpath(os.path.join(root, f))
|
|
51
|
+
if not hook.is_ignored(full, rules):
|
|
52
|
+
yield full
|
|
53
|
+
else:
|
|
54
|
+
yield p # a file you name yourself is always scanned
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def scan(paths):
|
|
58
|
+
"""Check whole files on disk. Returns (findings, deps, text for --deep)."""
|
|
59
|
+
findings, deps, review = [], [], []
|
|
60
|
+
for path in walk(paths, hook.ignore_patterns()):
|
|
61
|
+
try:
|
|
62
|
+
text = Path(path).read_text(encoding="utf-8")
|
|
63
|
+
except (UnicodeDecodeError, OSError):
|
|
64
|
+
continue # binary or unreadable file
|
|
65
|
+
findings += text_checks(list(enumerate(text.splitlines(), start=1)), path, text) # list: both checks read it
|
|
66
|
+
deps += dependencies_in(path, text)
|
|
67
|
+
if mcp_check.is_mcp_config(path):
|
|
68
|
+
config_findings, config_deps = mcp_check.check_config(path, text)
|
|
69
|
+
findings += config_findings
|
|
70
|
+
deps += config_deps
|
|
71
|
+
review.append(f"### {path}\n{text}")
|
|
72
|
+
return findings, deps, "\n".join(review)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def staged():
|
|
76
|
+
"""Check only what this commit adds. Returns (findings, deps, text for --deep)."""
|
|
77
|
+
ignore = hook.ignore_patterns()
|
|
78
|
+
findings, deps, review = [], [], []
|
|
79
|
+
for path, lines in hook.added_lines().items():
|
|
80
|
+
if hook.is_ignored(path, ignore):
|
|
81
|
+
continue
|
|
82
|
+
findings += text_checks(lines, path, hook.staged_text(path))
|
|
83
|
+
review.append(f"### {path}\n" + "\n".join(f"{n}: {t}" for n, t in lines))
|
|
84
|
+
for path in hook.staged_files():
|
|
85
|
+
if hook.is_ignored(path, ignore):
|
|
86
|
+
continue
|
|
87
|
+
if ENV_FILE.match(Path(path).name):
|
|
88
|
+
findings.append({"severity": "WARN", "where": path,
|
|
89
|
+
"reason": ".env files hold secrets and shouldn't be committed. Add .env to "
|
|
90
|
+
f".gitignore and run: git rm --cached \"{path}\""})
|
|
91
|
+
if is_dependency_file(path): # only packages this commit ADDS, so old ones aren't re-checked
|
|
92
|
+
old = set(dependencies_in(path, hook.head_text(path)))
|
|
93
|
+
deps += [d for d in dependencies_in(path, hook.staged_text(path)) if d not in old]
|
|
94
|
+
if mcp_check.is_mcp_config(path):
|
|
95
|
+
config_findings, config_deps = mcp_check.check_config(path, hook.staged_text(path))
|
|
96
|
+
findings += config_findings
|
|
97
|
+
deps += config_deps
|
|
98
|
+
return findings, deps, "\n".join(review)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def print_report(findings, notes, in_hook):
|
|
102
|
+
if not findings:
|
|
103
|
+
print("ezco: all clear")
|
|
104
|
+
for f in findings:
|
|
105
|
+
print(f"[{f['severity']}] {f['where']}: {f['reason']}")
|
|
106
|
+
if "fix" in f:
|
|
107
|
+
if f["fix"]["url"]:
|
|
108
|
+
print(f" revoke at: {f['fix']['url']}")
|
|
109
|
+
print(f" {f['fix']['steps']}")
|
|
110
|
+
for note in notes:
|
|
111
|
+
print(f"note: {note}")
|
|
112
|
+
blocks = sum(f["severity"] == "BLOCK" for f in findings)
|
|
113
|
+
if blocks:
|
|
114
|
+
print(f"\n{len(findings)} problem(s), {blocks} blocking")
|
|
115
|
+
elif findings:
|
|
116
|
+
print(f"\n{len(findings)} warning(s), nothing blocking" + (" - commit allowed" if in_hook else ""))
|
|
117
|
+
if blocks and in_hook:
|
|
118
|
+
print("Commit blocked. Fix the BLOCK items above, or if one is a false alarm:\n"
|
|
119
|
+
" - add '# ezco:ignore' to that line, or add the path to .ezcoignore\n"
|
|
120
|
+
" - skip the check once: git commit --no-verify")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def main(argv=None):
|
|
124
|
+
sys.stdout.reconfigure(errors="backslashreplace") # odd filenames must never crash the report
|
|
125
|
+
parser = argparse.ArgumentParser(prog="ezco", description="Security guard for AI-written commits")
|
|
126
|
+
# metavar + no help= on `hook`/`agent-hook`: git and Claude Code run those, people don't, so --help hides them
|
|
127
|
+
sub = parser.add_subparsers(dest="command", required=True, metavar="{scan,install,uninstall,clone,guard}")
|
|
128
|
+
scan_cmd = sub.add_parser("scan", help="scan files or folders now")
|
|
129
|
+
scan_cmd.add_argument("paths", nargs="*", default=["."])
|
|
130
|
+
scan_cmd.add_argument("--deep", action="store_true", help="also ask an LLM (needs GROQ_API_KEY)")
|
|
131
|
+
hook_cmd = sub.add_parser("hook") # what git runs before each commit
|
|
132
|
+
hook_cmd.add_argument("--deep", action="store_true")
|
|
133
|
+
install_cmd = sub.add_parser("install", help="turn on the check for every commit in this repo")
|
|
134
|
+
install_cmd.add_argument("--force", action="store_true", help="replace an existing pre-commit hook")
|
|
135
|
+
install_cmd.add_argument("--agent", nargs="?", const="claude", choices=[*gate.HARNESSES, "all"],
|
|
136
|
+
help="also check an AI agent's package installs before they run "
|
|
137
|
+
"(claude by default; codex, gemini or all)")
|
|
138
|
+
sub.add_parser("uninstall", help="remove every ezco hook from this repo")
|
|
139
|
+
agent_cmd = sub.add_parser("agent-hook") # what the agent runs before each shell command
|
|
140
|
+
agent_cmd.add_argument("--for", dest="harness", choices=list(gate.HARNESSES), default="claude")
|
|
141
|
+
deep_help = "also ask an LLM; its hits quarantine too (needs GROQ_API_KEY)"
|
|
142
|
+
clone_cmd = sub.add_parser("clone", help="git clone, then quarantine dangerous AI-agent files before you open it")
|
|
143
|
+
clone_cmd.add_argument("url")
|
|
144
|
+
clone_cmd.add_argument("folder", nargs="?")
|
|
145
|
+
clone_cmd.add_argument("--deep", action="store_true", help=deep_help)
|
|
146
|
+
guard_cmd = sub.add_parser("guard", help="check a folder's AI-agent files (CLAUDE.md, .cursorrules, hooks...)")
|
|
147
|
+
guard_cmd.add_argument("folder", nargs="?", default=".")
|
|
148
|
+
guard_cmd.add_argument("--no-quarantine", action="store_true", help="only report, don't rename files")
|
|
149
|
+
guard_cmd.add_argument("--deep", action="store_true", help=deep_help)
|
|
150
|
+
args = parser.parse_args(argv)
|
|
151
|
+
|
|
152
|
+
if args.command == "agent-hook":
|
|
153
|
+
return gate.agent_hook(harness=args.harness)
|
|
154
|
+
if args.command == "clone":
|
|
155
|
+
return clone.clone(args.url, args.folder, use_deep=args.deep)
|
|
156
|
+
if args.command == "guard":
|
|
157
|
+
if not os.path.isdir(args.folder):
|
|
158
|
+
print(f"ezco: no folder called {args.folder}")
|
|
159
|
+
return 2
|
|
160
|
+
return 1 if clone.guard(args.folder, quarantine=not args.no_quarantine, use_deep=args.deep) else 0
|
|
161
|
+
if args.command == "install":
|
|
162
|
+
result = hook.install(args.force) or 0
|
|
163
|
+
for harness in (gate.HARNESSES if args.agent == "all" else [args.agent] if args.agent else []):
|
|
164
|
+
gate.install_agent(harness=harness)
|
|
165
|
+
return result
|
|
166
|
+
if args.command == "uninstall":
|
|
167
|
+
for harness in gate.HARNESSES:
|
|
168
|
+
gate.uninstall_agent(harness=harness)
|
|
169
|
+
return hook.uninstall() or 0
|
|
170
|
+
|
|
171
|
+
in_hook = args.command == "hook"
|
|
172
|
+
findings, deps, review_text = staged() if in_hook else scan(args.paths)
|
|
173
|
+
findings += packages.check_packages(sorted(set(deps)))
|
|
174
|
+
notes = []
|
|
175
|
+
# git can't pass flags to a hook, so deep mode in a commit is turned on with EZCO_DEEP=1
|
|
176
|
+
if (args.deep or os.environ.get("EZCO_DEEP") == "1") and review_text:
|
|
177
|
+
deep_findings, note = deep.review(review_text)
|
|
178
|
+
findings += deep_findings
|
|
179
|
+
notes.append(note)
|
|
180
|
+
print_report(findings, notes, in_hook)
|
|
181
|
+
# exit code 1 tells git to stop the commit
|
|
182
|
+
return 1 if any(f["severity"] == "BLOCK" for f in findings) else 0
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
if __name__ == "__main__":
|
|
186
|
+
sys.exit(main())
|
ezco/clone.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Clone guard: check a repo's AI-agent files BEFORE an agent opens the folder.
|
|
2
|
+
|
|
3
|
+
A cloned repo can ship a poisoned CLAUDE.md / .cursorrules, or a .claude/settings.json
|
|
4
|
+
hook that runs a command on your machine. Claude Code loads those the moment you start it
|
|
5
|
+
in the folder, and no hook of ours can stop that. So we check right after `git clone` and
|
|
6
|
+
rename anything dangerous to <name>.quarantined, where no agent looks for it."""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import shlex
|
|
12
|
+
import subprocess
|
|
13
|
+
import tomllib
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from ezco import deep, leaks, mcp_check
|
|
17
|
+
|
|
18
|
+
SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__"}
|
|
19
|
+
# (folder, file) that can hold hook commands or MCP servers an agent runs on its own.
|
|
20
|
+
# Formats from each tool's docs: Claude Code, Cursor, Codex (TOML too), Gemini CLI.
|
|
21
|
+
HARNESS_FILES = {(".claude", "settings.json"), (".claude", "settings.local.json"), (".cursor", "hooks.json"),
|
|
22
|
+
(".codex", "hooks.json"), (".codex", "config.toml"), (".gemini", "settings.json")}
|
|
23
|
+
# Hook commands no honest project needs: sending data out, running encoded or downloaded code.
|
|
24
|
+
HOOK_DANGER = re.compile(
|
|
25
|
+
r"\b(curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b.*(\s-d\b|--data|\s-F\b|--form|\s-T\b|--upload-file"
|
|
26
|
+
r"|--post-(data|file)|-method\s+post|\s-body\b)" # uploads something
|
|
27
|
+
r"|\s-(e|enc|encodedcommand)\s+[A-Za-z0-9+/=]{20,}|base64\s+(-d|--decode)|frombase64string" # hidden payload
|
|
28
|
+
r"|exec\(.*urlopen|\|\s*(sh|bash|zsh|iex|python3?)\s*-?\s*$", # runs downloaded or piped-in code
|
|
29
|
+
re.IGNORECASE)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def is_harness_file(path):
|
|
33
|
+
p = Path(path)
|
|
34
|
+
return (p.parent.name.lower(), p.name.lower()) in HARNESS_FILES
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def is_guarded(path):
|
|
38
|
+
name = Path(path).name.lower()
|
|
39
|
+
return (name in mcp_check.AGENT_FILES or name.endswith(".mdc") or mcp_check.is_mcp_config(path)
|
|
40
|
+
or is_harness_file(path))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def agent_files(root):
|
|
44
|
+
for folder, dirs, files in os.walk(root):
|
|
45
|
+
dirs[:] = [d for d in dirs if d not in SKIP_DIRS]
|
|
46
|
+
for f in files:
|
|
47
|
+
if is_guarded(f) or is_guarded(os.path.join(folder, f)):
|
|
48
|
+
yield os.path.join(folder, f)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def hook_commands(node):
|
|
52
|
+
"""Every "command" string anywhere under a hooks section. Claude Code, Codex and Gemini nest
|
|
53
|
+
event -> matcher group -> hooks; Cursor uses event -> [{command}]. Walking finds both."""
|
|
54
|
+
if isinstance(node, dict):
|
|
55
|
+
for key, value in node.items():
|
|
56
|
+
if key in ("command", "commandWindows") and isinstance(value, str):
|
|
57
|
+
yield value
|
|
58
|
+
else:
|
|
59
|
+
yield from hook_commands(value)
|
|
60
|
+
elif isinstance(node, list):
|
|
61
|
+
for value in node:
|
|
62
|
+
yield from hook_commands(value)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# Same attacks written in Python/JS/PowerShell instead of one shell line: network use PLUS reading secrets,
|
|
66
|
+
# evaluating code, or saving a file and running it. Network alone (a health check, a chat notification) only warns.
|
|
67
|
+
NETWORK = re.compile(r"urlopen|urllib\.request|\brequests\.(get|post|put)\b|httpx\.|\bfetch\(|\bhttps?\.(get|request)\(|"
|
|
68
|
+
r"axios|XMLHttpRequest|Net\.WebClient|\b(curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b",
|
|
69
|
+
re.IGNORECASE)
|
|
70
|
+
SECRETS = re.compile(r"\.ssh\b|id_rsa|id_ed25519|\.aws[/\\'\"]|os\.environ(?![.\[])|process\.env(?![.\[])|\benv\s*\|",
|
|
71
|
+
re.IGNORECASE)
|
|
72
|
+
EVAL = re.compile(r"\beval\(|new Function\(|\bexec\(|Invoke-Expression|\biex\b", re.IGNORECASE)
|
|
73
|
+
SAVES = re.compile(r"createWriteStream|writeFile|urlretrieve|open\([^)]*['\"]wb|\s-o\s|--output\b|-OutFile", re.IGNORECASE)
|
|
74
|
+
RUNS = re.compile(r"chmod|execSync|execFile|spawn|subprocess|os\.system|Start-Process", re.IGNORECASE)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def dangerous(text):
|
|
78
|
+
if any(mcp_check.CURL_PIPE_SH.search(line) or HOOK_DANGER.search(line) for line in text.splitlines()):
|
|
79
|
+
return True
|
|
80
|
+
return bool(NETWORK.search(text) and (SECRETS.search(text) or EVAL.search(text)
|
|
81
|
+
or (SAVES.search(text) and RUNS.search(text))))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def repo_scripts(command, root):
|
|
85
|
+
"""Files inside the repo that a hook command runs, e.g. `bash .cursor/hooks/setup.sh`."""
|
|
86
|
+
try: # shortcut: posix shlex eats backslashes, so `.\x.ps1` style Windows paths aren't followed; upgrade if seen in the wild
|
|
87
|
+
words = shlex.split(command)
|
|
88
|
+
except ValueError:
|
|
89
|
+
words = command.split()
|
|
90
|
+
base = Path(root).resolve()
|
|
91
|
+
for word in words:
|
|
92
|
+
word = re.sub(r"^\$\{?\w+\}?[\\/]", "", word) # $CLAUDE_PROJECT_DIR/x.sh -> x.sh
|
|
93
|
+
target = (base / word).resolve()
|
|
94
|
+
if base in target.parents and target.is_file():
|
|
95
|
+
yield word, target
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def check_settings(where, text, root=None):
|
|
99
|
+
"""Agent settings/hook files: every hook command runs on your machine without asking,
|
|
100
|
+
and MCP servers listed here are launched by the agent."""
|
|
101
|
+
try:
|
|
102
|
+
data = tomllib.loads(text) if where.endswith(".toml") else json.loads(text)
|
|
103
|
+
commands = list(hook_commands(data.get("hooks", {})))
|
|
104
|
+
servers = data.get("mcpServers") or data.get("mcp_servers") or {}
|
|
105
|
+
except (ValueError, AttributeError, TypeError): # TOMLDecodeError is a ValueError
|
|
106
|
+
return [{"severity": "WARN", "where": where, "reason": "agent settings file can't be parsed"}]
|
|
107
|
+
findings = mcp_check.check_servers(where, servers)[0] if isinstance(servers, dict) else []
|
|
108
|
+
for command in commands:
|
|
109
|
+
shown = command if len(command) <= 120 else command[:117] + "..."
|
|
110
|
+
scripts = [name for name, path in repo_scripts(command, root)
|
|
111
|
+
if dangerous(path.read_text(encoding="utf-8", errors="replace"))] if root else []
|
|
112
|
+
if dangerous(command) or scripts:
|
|
113
|
+
via = f" (inside {scripts[0]})" if scripts else ""
|
|
114
|
+
findings.append({"severity": "BLOCK", "where": where,
|
|
115
|
+
"reason": f"agent hook sends data out or runs downloaded/hidden code{via}: {shown}"})
|
|
116
|
+
else:
|
|
117
|
+
findings.append({"severity": "WARN", "where": where,
|
|
118
|
+
"reason": f"agent hook runs a command on your machine: {shown}"})
|
|
119
|
+
return findings
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def check_file(path, where):
|
|
123
|
+
# errors="replace": one bad byte must not make an agent file "binary" and skip the check
|
|
124
|
+
# utf-8-sig: a BOM must not make settings.json "invalid JSON" and hide its hooks
|
|
125
|
+
text = Path(path).read_text(encoding="utf-8-sig", errors="replace")
|
|
126
|
+
# The repo's author controls ezco:ignore marks and .ezcoignore, so neither counts here.
|
|
127
|
+
lines = [(n, line.replace(leaks.IGNORE_MARK, "")) for n, line in enumerate(text.splitlines(), start=1)]
|
|
128
|
+
findings = leaks.scan_lines(lines, where) + mcp_check.scan_lines(lines, where, text)
|
|
129
|
+
if mcp_check.is_agent_file(path, text):
|
|
130
|
+
# A stranger's instructions aimed at your agent: any injection sign is worth a (reversible) rename.
|
|
131
|
+
for f in findings:
|
|
132
|
+
if "prompt injection" in f["reason"]:
|
|
133
|
+
f["severity"] = "BLOCK"
|
|
134
|
+
if mcp_check.is_mcp_config(path):
|
|
135
|
+
findings += mcp_check.check_config(where, text)[0]
|
|
136
|
+
if is_harness_file(path):
|
|
137
|
+
root = Path(path).parents[len(Path(where).parts) - 1]
|
|
138
|
+
findings += check_settings(where, text, root)
|
|
139
|
+
return findings
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def deep_findings(files):
|
|
143
|
+
"""LLM second opinion on {where: text}. Unlike at commit time, a hit here quarantines the file:
|
|
144
|
+
the LLM can only ADD a reversible rename, never clear what the rules found."""
|
|
145
|
+
found, note = deep.review("\n".join(f"### {where}\n{text}" for where, text in files.items()))
|
|
146
|
+
for f in found:
|
|
147
|
+
named = f["where"].removeprefix("./").replace("\\", "/")
|
|
148
|
+
match = next((w for w in files if named == w or named.startswith(w + ":")), None)
|
|
149
|
+
if match is None and len(files) == 1: # the LLM sometimes writes "<code>:4"; with one file it can only mean that one
|
|
150
|
+
match = next(iter(files))
|
|
151
|
+
if match: # an answer naming no real file stays a warning
|
|
152
|
+
f["severity"], f["file"] = "BLOCK", match
|
|
153
|
+
return found, note
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def guard(root, quarantine=True, use_deep=False):
|
|
157
|
+
"""Scan root's agent files, print a report, quarantine BLOCKed files. Returns the flagged paths."""
|
|
158
|
+
findings, texts, paths = [], {}, {}
|
|
159
|
+
for path in agent_files(root):
|
|
160
|
+
where = os.path.relpath(path, root).replace("\\", "/")
|
|
161
|
+
findings += [dict(f, file=where) for f in check_file(path, where)]
|
|
162
|
+
texts[where] = Path(path).read_text(encoding="utf-8", errors="replace")
|
|
163
|
+
paths[where] = path
|
|
164
|
+
note = None
|
|
165
|
+
if use_deep and texts:
|
|
166
|
+
extra, note = deep_findings(texts)
|
|
167
|
+
findings += extra
|
|
168
|
+
bad_names = sorted({f["file"] for f in findings if f["severity"] == "BLOCK" and "file" in f})
|
|
169
|
+
bad = [(paths[w], w) for w in bad_names]
|
|
170
|
+
for f in findings:
|
|
171
|
+
print(f"[{f['severity']}] {f['where']}: {f['reason']}")
|
|
172
|
+
if note:
|
|
173
|
+
print(f"note: {note}")
|
|
174
|
+
if not bad:
|
|
175
|
+
print("ezco: agent files look clean" if not findings else
|
|
176
|
+
f"\nezco: {len(findings)} warning(s) in agent files, nothing quarantined. Read them before opening an agent here.")
|
|
177
|
+
return []
|
|
178
|
+
if not quarantine:
|
|
179
|
+
print(f"\nezco: {len(bad)} agent file(s) look dangerous. Do NOT open an AI agent here until you have read them.")
|
|
180
|
+
return [p for p, _ in bad]
|
|
181
|
+
print(f"\nezco: quarantined {len(bad)} file(s) so no AI agent loads them:")
|
|
182
|
+
for path, where in bad:
|
|
183
|
+
os.replace(path, path + ".quarantined") # replace: a pre-shipped .quarantined file can't block the rename
|
|
184
|
+
print(f" {where} -> {where}.quarantined")
|
|
185
|
+
print(f"Read them first, e.g. cat \"{bad[0][1]}.quarantined\"\n"
|
|
186
|
+
"Only restore a file you have read and trust (a settings.json hook runs commands on your machine):\n"
|
|
187
|
+
f" mv \"{bad[0][1]}.quarantined\" \"{bad[0][1]}\" (works in PowerShell too)\n"
|
|
188
|
+
"git will show them as deleted until you do; don't commit that.")
|
|
189
|
+
return [p for p, _ in bad]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def default_folder(url):
|
|
193
|
+
"""Same folder name git would pick: last part of the URL, minus .git."""
|
|
194
|
+
name = url.rstrip("/\\").replace("\\", "/").rsplit("/", 1)[-1].rsplit(":", 1)[-1]
|
|
195
|
+
return name.removesuffix(".git") or "repo"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def clone(url, folder=None, use_deep=False):
|
|
199
|
+
folder = folder or default_folder(url)
|
|
200
|
+
# "--" so a URL starting with "-" can't be read as a git option. Submodules are not fetched.
|
|
201
|
+
code = subprocess.run(["git", "clone", "--", url, folder]).returncode
|
|
202
|
+
if code != 0:
|
|
203
|
+
return code
|
|
204
|
+
print(f"\nezco: checking the agent files in {folder} ...")
|
|
205
|
+
return 1 if guard(folder, use_deep=use_deep) else 0
|