tarpit-guard 0.2.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.
@@ -0,0 +1,4 @@
1
+ from .detector import analyze_file, analyze_text, repo_fingerprints
2
+
3
+ __all__ = ["analyze_file", "analyze_text", "repo_fingerprints"]
4
+ __version__ = "0.2.0"
tarpit_guard/cli.py ADDED
@@ -0,0 +1,87 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import sys
5
+
6
+ from .detector import analyze_file, repo_fingerprints
7
+
8
+ SCAN_EXTS = {".js", ".mjs", ".cjs", ".ts", ".jsx", ".tsx", ".py", ".wasm.js"}
9
+ SKIP_DIRS = {"node_modules", ".git", "dist", "build", "__pycache__", ".venv"}
10
+
11
+
12
+ def _iter_files(root):
13
+ if os.path.isfile(root):
14
+ yield root
15
+ return
16
+ for dirpath, dirnames, filenames in os.walk(root):
17
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
18
+ for f in filenames:
19
+ if os.path.splitext(f)[1] in SCAN_EXTS:
20
+ yield os.path.join(dirpath, f)
21
+
22
+
23
+ def main(argv=None):
24
+ parser = argparse.ArgumentParser(
25
+ prog="tarpit-guard",
26
+ description="Flag AI-reverse-engineering tarpits (obfuscated / token-burning code) before you waste a budget analyzing them.")
27
+ parser.add_argument("path", help="File or directory to scan.")
28
+ parser.add_argument("--json", action="store_true", help="Emit raw JSON.")
29
+ parser.add_argument("--threshold", type=float, default=55.0,
30
+ help="Score at/above which a file is called a tarpit.")
31
+ parser.add_argument("--quiet", action="store_true",
32
+ help="Only print files at/above the threshold.")
33
+ args = parser.parse_args(argv)
34
+
35
+ if not os.path.exists(args.path):
36
+ print(f"path not found: {args.path}", file=sys.stderr)
37
+ return 2
38
+
39
+ fingerprints = repo_fingerprints(args.path) if os.path.isdir(args.path) else []
40
+
41
+ results = []
42
+ for fp in _iter_files(args.path):
43
+ r = analyze_file(fp)
44
+ if "error" in r:
45
+ continue
46
+ r["hardened"] = r["score"] >= args.threshold
47
+ results.append(r)
48
+
49
+ results.sort(key=lambda r: r["score"], reverse=True)
50
+ flagged = [r for r in results if r["hardened"]]
51
+
52
+ report = {
53
+ "scanned": len(results),
54
+ "flagged": len(flagged),
55
+ "tool_fingerprints": fingerprints,
56
+ "results": results,
57
+ }
58
+
59
+ if args.json:
60
+ print(json.dumps(report, indent=2))
61
+ return 0
62
+
63
+ if fingerprints:
64
+ print("Tool fingerprints found (strong signal of deliberate hardening):")
65
+ for h in fingerprints:
66
+ print(f" [{h['tool']}] {h['kind']}: {h['path']}")
67
+ print()
68
+
69
+ shown = flagged if args.quiet else results
70
+ if not shown:
71
+ print("No tarpit-like files found.")
72
+ for r in shown:
73
+ tag = "TARPIT" if r["hardened"] else "ok"
74
+ print(f"[{tag}] score={r['score']:>5} conf={r['confidence']:.2f} {r['path']}")
75
+ if r["hardened"]:
76
+ ev = r["evidence"]
77
+ print(f" {ev['size_bytes']}B / {ev['line_count']} lines, "
78
+ f"Math.imul×{ev['math_imul_count']}, decoder_pairs={ev['decoder_pairs']}, "
79
+ f"garbled_idents={ev['garbled_identifiers']}, decoy_hits={ev['decoy_vocab_hits']}")
80
+ print(f" fired: {', '.join(r['fired_signals'])}")
81
+ print(f" -> {r['recommended_strategy']}")
82
+
83
+ return 1 if flagged else 0
84
+
85
+
86
+ if __name__ == "__main__":
87
+ sys.exit(main())
@@ -0,0 +1,184 @@
1
+ import math
2
+ import os
3
+ import re
4
+
5
+ FINGERPRINT_FILES = {
6
+ ".blarc": "bla",
7
+ "bla-harden-summary.json": "bla",
8
+ }
9
+ FINGERPRINT_DIRS = {
10
+ ".bla-hardened": "bla",
11
+ }
12
+
13
+ DECOY_VOCAB = [
14
+ "enclave", "attestation", "tpm", "hsm", "canary", "honeypot",
15
+ "decoy", "opaque", "interlock", "containment", "nitro", "vsock", "hkdf",
16
+ "sealed", "zerotrust", "entangle", "tarpit",
17
+ ]
18
+
19
+ IDENT_RE = re.compile(r"[A-Za-z_$][A-Za-z0-9_$]*")
20
+ HEX_IDENT_RE = re.compile(r"_0x[0-9a-fA-F]{3,}")
21
+ HEX_ESCAPE_RE = re.compile(r"\\x[0-9a-fA-F]{2}")
22
+ TRUTHY_RE = re.compile(r"!\[\]")
23
+
24
+
25
+ def _shannon_entropy(s):
26
+ if not s:
27
+ return 0.0
28
+ counts = {}
29
+ for ch in s:
30
+ counts[ch] = counts.get(ch, 0) + 1
31
+ n = len(s)
32
+ return -sum((c / n) * math.log2(c / n) for c in counts.values())
33
+
34
+
35
+ def _clamp(x):
36
+ return max(0.0, min(1.0, x))
37
+
38
+
39
+ def _is_garbled(ident):
40
+ if len(ident) < 14:
41
+ return False
42
+ if not any(c.isdigit() for c in ident):
43
+ return False
44
+ has_upper = any(c.isupper() for c in ident)
45
+ has_lower = any(c.islower() for c in ident)
46
+ return has_upper and has_lower and any(c.isdigit() for c in ident[-5:])
47
+
48
+
49
+ def repo_fingerprints(root):
50
+ hits = []
51
+ for dirpath, dirnames, filenames in os.walk(root):
52
+ for d in dirnames:
53
+ if d in FINGERPRINT_DIRS:
54
+ hits.append({"kind": "dir", "name": d,
55
+ "tool": FINGERPRINT_DIRS[d],
56
+ "path": os.path.join(dirpath, d)})
57
+ for f in filenames:
58
+ if f in FINGERPRINT_FILES:
59
+ hits.append({"kind": "file", "name": f,
60
+ "tool": FINGERPRINT_FILES[f],
61
+ "path": os.path.join(dirpath, f)})
62
+ return hits
63
+
64
+
65
+ def analyze_text(text, path=None):
66
+ size = len(text)
67
+ lines = text.splitlines() or [""]
68
+ kb = max(size / 1024.0, 0.001)
69
+
70
+ imul = text.count("Math.imul")
71
+ hex_ident = len(HEX_IDENT_RE.findall(text))
72
+ hex_escape = len(HEX_ESCAPE_RE.findall(text))
73
+ truthy = len(TRUTHY_RE.findall(text))
74
+ split_pipe = text.count(".split('|')") + text.count('.split("|")')
75
+ from_char = len(re.findall(r"fromCharCode", text))
76
+ char_at = len(re.findall(r"charCodeAt", text))
77
+ decoder_pairs = min(from_char, char_at)
78
+
79
+ low = text.lower()
80
+ decoy_hits = sum(low.count(w) for w in DECOY_VOCAB)
81
+
82
+ idents = IDENT_RE.findall(text)
83
+ unique = set(idents)
84
+ garbled = {i for i in unique if _is_garbled(i)}
85
+ garble_ratio = (len(garbled) / len(unique)) if unique else 0.0
86
+ short_ratio = (sum(1 for i in idents if len(i) <= 2) / len(idents)) if idents else 0.0
87
+
88
+ imul_per_kb = imul / kb
89
+ hex_ident_per_kb = hex_ident / kb
90
+ decoy_per_kb = decoy_hits / kb
91
+
92
+ signals = {
93
+ "opaque_predicate_density": _clamp(imul_per_kb / 1.5),
94
+ "decoder_loops": _clamp((decoder_pairs - 1) / 4.0),
95
+ "hex_identifier_array": _clamp(hex_ident_per_kb / 5.0),
96
+ "obfuscator_control_tricks": _clamp(truthy / 3.0 + split_pipe / 2.0),
97
+ "decoy_vocabulary_density": _clamp(decoy_per_kb / 3.0),
98
+ "garbled_identifier_ratio": _clamp(garble_ratio / 0.25),
99
+ }
100
+ weights = {
101
+ "opaque_predicate_density": 0.28,
102
+ "decoder_loops": 0.22,
103
+ "hex_identifier_array": 0.28,
104
+ "obfuscator_control_tricks": 0.12,
105
+ "decoy_vocabulary_density": 0.06,
106
+ "garbled_identifier_ratio": 0.04,
107
+ }
108
+ graded = sum(signals[k] * weights[k] for k in weights) * 100.0
109
+
110
+ markers = []
111
+ if hex_ident_per_kb >= 3.0:
112
+ markers.append(("hex_identifier_array", 85,
113
+ "dense _0x string-array identifiers (javascript-obfuscator style)"))
114
+ if decoder_pairs >= 3:
115
+ markers.append(("decoder_loops", 78,
116
+ "runtime string-decryption loops (fromCharCode/charCodeAt)"))
117
+ if imul >= 20 and imul_per_kb >= 0.5:
118
+ markers.append(("opaque_predicate_density", 78,
119
+ "Math.imul opaque-predicate chains"))
120
+ if truthy >= 3:
121
+ markers.append(("obfuscator_control_tricks", 68,
122
+ "self-defending / control-flow !![] tricks"))
123
+
124
+ floor = max((m[1] for m in markers), default=0)
125
+ score = max(graded, floor)
126
+
127
+ minified_profile = short_ratio >= 0.45 and len(idents) > 300
128
+ if not markers and minified_profile:
129
+ score = min(score, 35.0)
130
+
131
+ fired = [k for k, v in signals.items() if v >= 0.5]
132
+ confidence = _clamp((len(markers) + len(fired)) / 3.0)
133
+
134
+ evidence = {
135
+ "size_bytes": size,
136
+ "line_count": len(lines),
137
+ "math_imul_count": imul,
138
+ "hex_identifiers": hex_ident,
139
+ "hex_escapes": hex_escape,
140
+ "truthy_tricks": truthy,
141
+ "decoder_pairs": decoder_pairs,
142
+ "decoy_vocab_hits": decoy_hits,
143
+ "unique_identifiers": len(unique),
144
+ "garbled_identifiers": len(garbled),
145
+ "short_identifier_ratio": round(short_ratio, 3),
146
+ "identifier_entropy": round(_shannon_entropy("".join(sorted(unique))), 3),
147
+ }
148
+
149
+ return {
150
+ "path": path,
151
+ "score": round(score, 1),
152
+ "confidence": round(confidence, 2),
153
+ "hardened": score >= 55,
154
+ "markers": [{"signal": m[0], "why": m[2]} for m in markers],
155
+ "signals": {k: round(v, 3) for k, v in signals.items()},
156
+ "fired_signals": fired,
157
+ "benign_minification": bool(minified_profile and not markers),
158
+ "evidence": evidence,
159
+ "recommended_strategy": _strategy(score, markers, minified_profile),
160
+ }
161
+
162
+
163
+ def _strategy(score, markers, minified_profile):
164
+ if score >= 55:
165
+ return ("Treat as a tarpit. Do NOT read the whole file or trace it "
166
+ "statically. Prefer dynamic analysis (run in a sandbox and "
167
+ "observe I/O) or escalate to a human.")
168
+ if minified_profile and not markers:
169
+ return ("Looks like ordinary minified/bundled code, not hostile "
170
+ "obfuscation. Read the original source or a source map instead "
171
+ "of the bundle.")
172
+ if score >= 30:
173
+ return ("Mixed signals. Probe with grep/targeted reads before any full "
174
+ "ingest; cap the analysis budget.")
175
+ return "Looks like ordinary source. Normal analysis is fine."
176
+
177
+
178
+ def analyze_file(path):
179
+ try:
180
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
181
+ text = fh.read()
182
+ except (OSError, UnicodeError) as exc:
183
+ return {"path": path, "error": str(exc)}
184
+ return analyze_text(text, path=path)
@@ -0,0 +1,66 @@
1
+ import os
2
+
3
+ from fastmcp import FastMCP
4
+
5
+ from .detector import analyze_file, analyze_text, repo_fingerprints
6
+
7
+ mcp = FastMCP("tarpit-guard")
8
+
9
+ SCAN_EXTS = {".js", ".mjs", ".cjs", ".ts", ".jsx", ".tsx", ".py"}
10
+ SKIP_DIRS = {"node_modules", ".git", "dist", "build", "__pycache__", ".venv"}
11
+
12
+
13
+ @mcp.tool()
14
+ def check_file(path: str) -> dict:
15
+ """Score a single file for obfuscation / anti-analysis tarpit signals.
16
+
17
+ Call this BEFORE reading or statically analyzing an unfamiliar file.
18
+ If hardened is true, do not ingest the whole file; run it in a sandbox
19
+ and observe its behavior instead.
20
+ """
21
+ return analyze_file(path)
22
+
23
+
24
+ @mcp.tool()
25
+ def check_source(text: str, label: str = "snippet") -> dict:
26
+ """Score a raw source string for tarpit signals without touching disk."""
27
+ return analyze_text(text, path=label)
28
+
29
+
30
+ @mcp.tool()
31
+ def scan_repo(root: str, threshold: float = 55.0) -> dict:
32
+ """Scan a directory tree: report tool fingerprints and any tarpit files.
33
+
34
+ Use this before an agent commits a budget to understanding a repo.
35
+ """
36
+ if not os.path.isdir(root):
37
+ return {"error": f"not a directory: {root}"}
38
+
39
+ results = []
40
+ for dirpath, dirnames, filenames in os.walk(root):
41
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
42
+ for f in filenames:
43
+ if os.path.splitext(f)[1] in SCAN_EXTS:
44
+ r = analyze_file(os.path.join(dirpath, f))
45
+ if "error" not in r:
46
+ r["hardened"] = r["score"] >= threshold
47
+ results.append(r)
48
+
49
+ results.sort(key=lambda r: r["score"], reverse=True)
50
+ flagged = [r for r in results if r["hardened"]]
51
+ return {
52
+ "root": root,
53
+ "scanned": len(results),
54
+ "flagged": len(flagged),
55
+ "tool_fingerprints": repo_fingerprints(root),
56
+ "flagged_files": flagged,
57
+ "all_results": results,
58
+ }
59
+
60
+
61
+ def run():
62
+ mcp.run()
63
+
64
+
65
+ if __name__ == "__main__":
66
+ run()
@@ -0,0 +1,316 @@
1
+ Metadata-Version: 2.4
2
+ Name: tarpit-guard
3
+ Version: 0.2.0
4
+ Summary: Flag AI-reverse-engineering tarpits (obfuscated / token-burning code) before you waste a budget analyzing them.
5
+ Author: Maniram
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ManiraM-1/tarpit-guard
8
+ Project-URL: Repository, https://github.com/ManiraM-1/tarpit-guard
9
+ Project-URL: Issues, https://github.com/ManiraM-1/tarpit-guard/issues
10
+ Keywords: mcp,llm,ai-agents,obfuscation,reverse-engineering,static-analysis,security,developer-tools
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: Software Development :: Quality Assurance
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Provides-Extra: mcp
27
+ Requires-Dist: fastmcp>=2.0; extra == "mcp"
28
+ Dynamic: license-file
29
+
30
+ # 🪤 tarpit-guard
31
+
32
+ **A pre-flight guard for AI code-analysis agents.** It scores a file or repository for signs of deliberate *anti-analysis hardening* — the obfuscation and "token-burning" tricks that tools like [BLA](https://github.com/qybaihe/bla) apply to make AI reverse-engineering expensive — and tells an agent, **before it spends a budget**, whether a target is a tarpit and what to do instead.
33
+
34
+ > One ~1K-token check that prevents a 60K-token mistake.
35
+
36
+ ---
37
+
38
+ ## Table of contents
39
+
40
+ - [The problem](#the-problem)
41
+ - [What this is — and what it is not](#what-this-is--and-what-it-is-not)
42
+ - [How it works](#how-it-works)
43
+ - [Signals](#signals)
44
+ - [Tool fingerprints](#tool-fingerprints)
45
+ - [Scoring and thresholds](#scoring-and-thresholds)
46
+ - [Install](#install)
47
+ - [CLI usage](#cli-usage)
48
+ - [MCP usage (for agents)](#mcp-usage-for-agents)
49
+ - [Example output](#example-output)
50
+ - [Project layout](#project-layout)
51
+ - [Limitations and false positives](#limitations-and-false-positives)
52
+ - [Roadmap](#roadmap)
53
+ - [FAQ](#faq)
54
+ - [License](#license)
55
+
56
+ ---
57
+
58
+ ## The problem
59
+
60
+ Source-hardening tools defend software by making it hostile to static analysis. A tiny, readable source file is transformed into a large, deliberately confusing one that still behaves identically:
61
+
62
+ | | Original | Hardened |
63
+ |---|---|---|
64
+ | Size | 418 B | 184 KB (**~440×**) |
65
+ | Lines | 15 | 2,998 |
66
+ | Secret string in cleartext | yes | no (encrypted) |
67
+ | Output when run | identical | identical |
68
+
69
+ The hardened file pads real logic with decoy functions, wraps branches behind opaque-predicate math, encrypts string literals behind runtime decoder loops, and plants jargon "canaries" written specifically to mislead a reading agent.
70
+
71
+ For an AI agent, the trap is cost. Read-and-trace the whole thing and you burn input tokens on ingestion and reasoning tokens on dead ends — and often still reach a wrong conclusion. The cheap counter is not to out-analyze the obfuscation; it is to **detect the tarpit first** and switch to dynamic analysis (run it in a sandbox, observe its behavior), which walks past nearly all static obfuscation for almost no tokens.
72
+
73
+ `tarpit-guard` is that detection step.
74
+
75
+ ---
76
+
77
+ ## What this is — and what it is not
78
+
79
+ **It is** a detector and triage guard. It answers one question: *does this look deliberately hardened, and if so, what is the cheaper way in?* It emits a score, the signals that fired, and a recommended strategy.
80
+
81
+ **It is not** a deobfuscator, a cracker, or a secret extractor. It never reverses anyone's protection or recovers hidden values. That is precisely the reverse-engineering these hardening tools exist to stop — building it would make this project the thing it is meant to warn about. The line is deliberate and permanent: `tarpit-guard` reads *shape*, never *meaning*.
82
+
83
+ ---
84
+
85
+ ## How it works
86
+
87
+ The engine is pure Python standard library — no dependencies, no network, nothing to install for the core. It runs entirely on local text.
88
+
89
+ 1. **Repository sweep** (directory mode): walk the tree, skipping `node_modules`, `.git`, `dist`, `build`, and the like, and look for tool fingerprints.
90
+ 2. **Per-file analysis**: for each candidate file, compute a set of cheap structural and statistical signals from the raw text — no execution, no parsing of untrusted code.
91
+ 3. **Weighted score**: combine the signals into a 0–100 score and a confidence derived from how many independent signals fired.
92
+ 4. **Verdict**: above the threshold, the file is a tarpit; the engine returns the evidence and a recommended strategy instead of a pile of extracted facts.
93
+
94
+ Because every signal is a count or ratio over text, the check is orders of magnitude cheaper than the analysis it protects.
95
+
96
+ ---
97
+
98
+ ## Signals
99
+
100
+ Detection keys on signals that benign code — even heavily minified code — essentially never produces. This is deliberate: the hard problem is not spotting that a file is *machine-generated* (minified bundles are too); it is telling *hostile* obfuscation apart from *ordinary* minification. Size and line-length are explicitly **not** primary signals, because that is exactly what minification trips.
101
+
102
+ | Signal | Weight | What it catches |
103
+ |---|---:|---|
104
+ | `opaque_predicate_density` | 0.28 | `Math.imul` tautology chains that guard real branches behind always-true math (BLA) |
105
+ | `hex_identifier_array` | 0.28 | dense `_0x…` string-array identifiers (javascript-obfuscator family) |
106
+ | `decoder_loops` | 0.22 | `fromCharCode` + `charCodeAt` loops that reconstruct encrypted string literals at runtime |
107
+ | `obfuscator_control_tricks` | 0.12 | self-defending / control-flow tricks (`!![]`, `.split('\|')` dispatch) |
108
+ | `decoy_vocabulary_density` | 0.06 | planted jargon clusters (enclave / attestation / TPM / canary) meant to mislead a reader |
109
+ | `garbled_identifier_ratio` | 0.04 | mangled names such as `encodeFrozenScopeV4ue7` |
110
+
111
+ On top of the weighted score, four **categorical markers** apply a decisive floor, because they are signatures essentially impossible in hand-written or merely-minified code: a dense `_0x` identifier array, three or more runtime decoder loops, `Math.imul` opaque-predicate chains, or repeated `!![]` self-defending tricks. Any one present pushes the file over the line.
112
+
113
+ Conversely, a file **dominated by 1–2 character identifiers** (the minification tell — 60–70% in jQuery/Lodash builds, versus ~10% in hostile files) with **none** of those markers is recognized as benign minification and capped low, with the strategy "read the original source or a source map, not the bundle."
114
+
115
+ The `evidence` block reports the raw counts (`Math.imul`, hex identifiers, decoder pairs, decoy hits, short-identifier ratio, …) so a human or agent can sanity-check *why* a file scored as it did.
116
+
117
+ ---
118
+
119
+ ## Tool fingerprints
120
+
121
+ Some artifacts are near-certain evidence of deliberate hardening on their own, independent of file contents. Directory scans report them separately as a strong standalone signal:
122
+
123
+ | Fingerprint | Tool |
124
+ |---|---|
125
+ | `.bla-hardened/` directory | BLA |
126
+ | `.blarc` | BLA |
127
+ | `bla-harden-summary.json` | BLA |
128
+
129
+ The fingerprint map is a plain table in `detector.py` and is meant to grow as more hardeners are catalogued.
130
+
131
+ ---
132
+
133
+ ## Scoring and thresholds
134
+
135
+ - **Score** — 0–100, the weighted sum of signals.
136
+ - **Confidence** — rises with the number of independent signals that cross their own half-way mark; four or more means full confidence.
137
+ - **Threshold** — default **55**. At or above it, `hardened` is true. Tunable with `--threshold` (CLI) or the `threshold` argument (MCP).
138
+
139
+ ### Evaluation
140
+
141
+ `eval_corpus.py` scores a labelled corpus (`corpus/`) of clean source, real
142
+ minified bundles, and hostile obfuscation, and reports false positives /
143
+ negatives. It doubles as a regression test (non-zero exit on any miss).
144
+
145
+ v0.2 results (threshold 55):
146
+
147
+ | Bucket | File | Score | Verdict |
148
+ |---|---|---:|---|
149
+ | clean | jquery.source.js / lodash.source.js | 0.0 | ok |
150
+ | clean | detector.py (contains the decoy word list) | 9.5 | ok |
151
+ | minified | jquery.min.js | 0.0 | ok |
152
+ | minified | lodash.min.js | 0.0 | ok |
153
+ | obfuscated | bla_hardened_app.js | 78.0 | **TARPIT** |
154
+ | obfuscated | js-obfuscator_sample.js | 85.0 | **TARPIT** |
155
+
156
+ **0 false positives, 0 false negatives.** Highest benign score 9.5, lowest
157
+ hostile score 78.0 — a **+68.5** margin, stable across any threshold from ~10 to
158
+ ~77. (For contrast, v0.1 leaned on file size and scored minified jQuery *above*
159
+ a real obfuscated file; that regression is what this corpus exists to prevent.)
160
+
161
+ ---
162
+
163
+ ## Install
164
+
165
+ ```bash
166
+ git clone https://github.com/ManiraM-1/tarpit-guard.git
167
+ cd tarpit-guard
168
+
169
+ pip install -e . # core CLI — standard library only
170
+ pip install -e ".[mcp]" # adds the FastMCP server (fastmcp>=2.0)
171
+ ```
172
+
173
+ Requires Python 3.9+.
174
+
175
+ ---
176
+
177
+ ## CLI usage
178
+
179
+ ```bash
180
+ tarpit-guard path/to/file.js # score a single file
181
+ tarpit-guard path/to/repo # scan a tree + report fingerprints
182
+ tarpit-guard path/to/repo --quiet # only show flagged files
183
+ tarpit-guard path/to/repo --json # machine-readable report
184
+ tarpit-guard path/to/repo --threshold 45
185
+
186
+ python -m tarpit_guard.cli path/to/file.js # run without installing
187
+ ```
188
+
189
+ **Exit codes** make it a drop-in CI gate:
190
+
191
+ | Code | Meaning |
192
+ |---:|---|
193
+ | `0` | nothing flagged |
194
+ | `1` | at least one tarpit found |
195
+ | `2` | path not found |
196
+
197
+ ```yaml
198
+ # e.g. fail a job if a dependency ships hardened artifacts
199
+ - run: tarpit-guard ./vendor --quiet
200
+ ```
201
+
202
+ ---
203
+
204
+ ## MCP usage (for agents)
205
+
206
+ Run the server:
207
+
208
+ ```bash
209
+ python -m tarpit_guard.mcp_server
210
+ ```
211
+
212
+ It exposes three tools:
213
+
214
+ | Tool | Use |
215
+ |---|---|
216
+ | `check_file(path)` | score one file before reading it |
217
+ | `check_source(text, label)` | score a raw snippet without touching disk |
218
+ | `scan_repo(root, threshold)` | sweep a tree for fingerprints and tarpit files |
219
+
220
+ **The intended agent loop:**
221
+
222
+ ```
223
+ encounter unfamiliar file
224
+ │
225
+ ▼
226
+ check_file(path)
227
+ │
228
+ hardened? ──no──▶ analyze normally
229
+ │
230
+ yes
231
+ │
232
+ ▼
233
+ skip the full read →
234
+ run it in a sandbox and observe I/O,
235
+ or escalate to a human
236
+ ```
237
+
238
+ The guard turns "read everything and hope" into a deliberate, budgeted decision.
239
+
240
+ ---
241
+
242
+ ## Example output
243
+
244
+ ```
245
+ $ tarpit-guard ./BLA
246
+
247
+ Tool fingerprints found (strong signal of deliberate hardening):
248
+ [bla] dir: ./BLA/.bla-hardened
249
+ [bla] file: ./BLA/.blarc
250
+ [bla] file: ./BLA/.bla-hardened/bla-harden-summary.json
251
+
252
+ [TARPIT] score= 78 conf=1.00 ./BLA/.bla-hardened/app.js
253
+ 182865B / 2998 lines, Math.imul×246, decoder_pairs=8, garbled_idents=190, decoy_hits=487
254
+ fired: opaque_predicate_density, decoder_loops, decoy_vocabulary_density
255
+ -> Treat as a tarpit. Do NOT read the whole file or trace it statically.
256
+ Prefer dynamic analysis (run in a sandbox and observe I/O) or escalate to a human.
257
+ [ok] score= 0.0 conf=0.00 ./BLA/app.js
258
+ ```
259
+
260
+ ---
261
+
262
+ ## Project layout
263
+
264
+ ```
265
+ tarpit-guard/
266
+ ├── pyproject.toml
267
+ ├── README.md
268
+ ├── LICENSE
269
+ ├── .gitignore
270
+ ├── eval_corpus.py # scores corpus/, reports false positives/negatives
271
+ ├── corpus/ # labelled samples: clean / minified / obfuscated
272
+ └── tarpit_guard/
273
+ ├── __init__.py # public API: analyze_file, analyze_text, repo_fingerprints
274
+ ├── detector.py # scoring engine (stdlib only)
275
+ ├── cli.py # command-line entry point
276
+ └── mcp_server.py # FastMCP wrapper
277
+ ```
278
+
279
+ ---
280
+
281
+ ## Limitations and false positives
282
+
283
+ This is a v0.2 heuristic, and honesty about its edges matters more than a clean pitch:
284
+
285
+ - **Small corpus.** It is calibrated on two hardeners (BLA, javascript-obfuscator) against clean source and real minified bundles — nine files. The separation is wide and clean, but a larger corpus (more obfuscators, more real-world bundles) is needed before leaning on it blindly.
286
+ - **Minified vs hardened is handled, not solved.** v0.2 correctly passes minified jQuery and Lodash while flagging both obfuscators, using short-identifier dominance plus categorical markers. An exotic bundler or a deliberately minification-mimicking obfuscator could still fool it; that is what growing the corpus guards against.
287
+ - **Static only.** It reads the file as text. It does not and should not execute anything it scans.
288
+ - **Thresholds are empirical.** 55 is the default, with a stable margin from ~10 to ~77 on the current corpus — but it is tuned, not derived. Expect to revisit it per language and per codebase.
289
+
290
+ ---
291
+
292
+ ## Roadmap
293
+
294
+ - [x] False-positive corpus: normal + minified + obfuscated samples to calibrate against (`corpus/`, `eval_corpus.py`).
295
+ - [x] Detect a second hardener family (javascript-obfuscator) alongside BLA.
296
+ - [x] Separate hostile obfuscation from ordinary minification.
297
+ - [ ] More tool fingerprints (webpack/terser signatures, PyArmor, obfuscator.io variants).
298
+ - [ ] Grow the corpus (more real bundles, more obfuscators) and pin thresholds against it.
299
+ - [ ] Per-language signal profiles (JS/TS vs Python vs WASM-glue).
300
+ - [ ] Optional sandbox-runner helper that an agent can call after a tarpit verdict.
301
+
302
+ ---
303
+
304
+ ## FAQ
305
+
306
+ **Does this crack or defeat BLA?** No. It detects that hardening is present and recommends a cheaper strategy. It never reverses the protection or extracts secrets.
307
+
308
+ **Is "burning all the AI's tokens" real?** Partly. Hardening genuinely raises the cost of *static* analysis and genuinely hides string secrets. It does not reliably exhaust a budget — a dynamic approach (run it, watch it) or a budget-aware agent that probes instead of ingesting sidesteps most of it. `tarpit-guard` exists to make that cheaper path the default.
309
+
310
+ **Why stdlib-only for the core?** Portability and auditability. The thing that inspects untrusted code should itself be tiny, dependency-free, and easy to read.
311
+
312
+ ---
313
+
314
+ ## License
315
+
316
+ MIT (see `LICENSE`).
@@ -0,0 +1,10 @@
1
+ tarpit_guard/__init__.py,sha256=L6EzEO6j1_Y5Vh5ye1HPt_zu5VEfqn6vq5pHZPV2nCY,155
2
+ tarpit_guard/cli.py,sha256=mBfk87_MiNJFOpP3HAzT_FkR7pDzLRL9CTrwiPmfOzc,3069
3
+ tarpit_guard/detector.py,sha256=hECXEM_mBXkCXsqfiuE4r6kIE2xpGwIWON9vG8Lqbo4,6498
4
+ tarpit_guard/mcp_server.py,sha256=nUe4wxD9IxcZgKYjFZoS1hilYaG9E6iHkNabXhOBuZQ,1959
5
+ tarpit_guard-0.2.0.dist-info/licenses/LICENSE,sha256=Wkiv5jqiUWD7smgYaKj-U6YcTPnpz5VOnk2xAlhkkA0,1064
6
+ tarpit_guard-0.2.0.dist-info/METADATA,sha256=JmDnlPAT68SFUmEC-fdLV0vpvkA16PbYGiw2u5_DY3Y,14147
7
+ tarpit_guard-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ tarpit_guard-0.2.0.dist-info/entry_points.txt,sha256=dM0tQCpGrqaZtkgQ42L-hquzGVnHAVaLIYWN1z48SbA,55
9
+ tarpit_guard-0.2.0.dist-info/top_level.txt,sha256=ATyzFGCgXPoiPTokqUlPMMFKIH4A7SjxAVQQA7eOQEg,13
10
+ tarpit_guard-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tarpit-guard = tarpit_guard.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maniram
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ tarpit_guard