tzero-mcp 12.2.1 → 12.3.2

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.
Files changed (55) hide show
  1. package/README.md +6 -30
  2. package/bin/tzero-mcp.js +2 -2
  3. package/bin/tzero.js +11 -6
  4. package/package.json +1 -2
  5. package/src/addmcp.py +10 -5
  6. package/src/app.py +3 -9
  7. package/src/tzero/__init__.py +1 -1
  8. package/src/tzero/anti_rea/__init__.py +16 -2
  9. package/src/tzero/anti_rea/algebraic_mutator.py +65 -44
  10. package/src/tzero/anti_rea/anti_debugger.py +51 -18
  11. package/src/tzero/anti_rea/asar_shield.py +24 -1
  12. package/src/tzero/anti_rea/auditor.py +62 -12
  13. package/src/tzero/anti_rea/canary_beacon.py +56 -76
  14. package/src/tzero/anti_rea/cli.py +37 -5
  15. package/src/tzero/anti_rea/confusables.py +62 -18
  16. package/src/tzero/anti_rea/crypto_loader.py +132 -0
  17. package/src/tzero/anti_rea/engine.py +129 -29
  18. package/src/tzero/anti_rea/extractor_shield.py +91 -13
  19. package/src/tzero/anti_rea/gui.py +1 -4
  20. package/src/tzero/anti_rea/integrity_guard.py +17 -5
  21. package/src/tzero/anti_rea/rdtsc_guard.py +21 -8
  22. package/src/tzero/anti_rea/string_vault.py +10 -7
  23. package/src/tzero/anti_rea/tier_catalog.py +388 -0
  24. package/src/tzero/siber_akademi.ico +0 -0
  25. package/src/tzero/siber_akademi_icon.py +14 -8
  26. package/src/tzero/tzero_armor.py +29 -7
  27. package/src/tzero/tzero_benchmark.py +4 -2
  28. package/src/tzero/tzero_budget.py +14 -5
  29. package/src/tzero/tzero_ci.py +2 -2
  30. package/src/tzero/tzero_contracts.py +7 -5
  31. package/src/tzero/tzero_dashboard.py +28 -9
  32. package/src/tzero/tzero_debt.py +19 -4
  33. package/src/tzero/tzero_deps.py +109 -87
  34. package/src/tzero/tzero_explain.py +1 -1
  35. package/src/tzero/tzero_features.py +43 -29
  36. package/src/tzero/tzero_federation.py +9 -2
  37. package/src/tzero/tzero_fixer/mcp_server.py +10 -0
  38. package/src/tzero/tzero_golden.py +37 -9
  39. package/src/tzero/tzero_growth.py +166 -8
  40. package/src/tzero/tzero_guard.py +147 -46
  41. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1 -1
  42. package/src/tzero/tzero_jarvis/zero_key_router.py +10 -78
  43. package/src/tzero/tzero_lsp.py +1 -1
  44. package/src/tzero/tzero_mcp.py +71 -23
  45. package/src/tzero/tzero_mutation.py +92 -15
  46. package/src/tzero/tzero_promo.py +1 -1
  47. package/src/tzero/tzero_proxy.py +105 -12
  48. package/src/tzero/tzero_scip.py +12 -6
  49. package/src/tzero/tzero_security.py +404 -60
  50. package/src/tzero/tzero_task_benchmark.py +2 -2
  51. package/src/tzero/tzero_traffic.py +35 -10
  52. package/src/tzero/tzero_tui.py +20 -11
  53. package/src/tzero/tzero_v3.py +304 -153
  54. package/src/tzero/tzero_welcome.py +12 -4
  55. package/bin/postinstall.js +0 -30
@@ -19,19 +19,30 @@ Part of Siber Akademi T-Zero Security Suite.
19
19
  License: MIT
20
20
  """
21
21
 
22
+ import ast
22
23
  import os
23
24
  from typing import Dict, Any, List
24
25
 
26
+ from .tier_catalog import evaluate_static_tier_coverage, TOTAL_TIER_COUNT
27
+
25
28
 
26
29
  class AIResistanceAuditor:
27
30
  """Audits target files for resistance against AI reverse-engineering agents."""
28
31
 
29
32
  @classmethod
30
33
  def audit_python_source(cls, source_code: str) -> Dict[str, Any]:
31
- """Audits Python source code across all Anti-REA defense dimensions."""
34
+ """Audits Python source code across Anti-REA static dimensions cleanly."""
32
35
  findings: List[str] = []
33
36
  score = 0
34
37
 
38
+ parsed_tree = None
39
+ syntax_valid = True
40
+ try:
41
+ parsed_tree = ast.parse(source_code)
42
+ except SyntaxError as exc:
43
+ syntax_valid = False
44
+ findings.append(f"Syntax error prevents clean Python compilation (line {exc.lineno}): {exc.msg}")
45
+
35
46
  # 1. Prompt Trap Check (0-10)
36
47
  has_prompt_trap = "CRITICAL_SYSTEM_OVERRIDE" in source_code or "RFC-AI-GUARD" in source_code
37
48
  if has_prompt_trap:
@@ -55,8 +66,20 @@ class AIResistanceAuditor:
55
66
  else:
56
67
  findings.append("No semantic token chaff detected to drain agent context window.")
57
68
 
58
- # 4. Homoglyphs & Confusables (0-10)
59
- has_homoglyphs = any(ord(char) > 127 for char in source_code)
69
+ # 4. Homoglyphs & Confusables in AST identifiers ONLY (do NOT score non-ASCII natural-language comments!)
70
+ has_homoglyphs = False
71
+ if parsed_tree is not None:
72
+ for node in ast.walk(parsed_tree):
73
+ ident = ""
74
+ if isinstance(node, ast.Name):
75
+ ident = node.id
76
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
77
+ ident = node.name
78
+ elif isinstance(node, ast.arg):
79
+ ident = node.arg
80
+ if ident and any(ord(ch) > 127 for ch in ident):
81
+ has_homoglyphs = True
82
+ break
60
83
  if has_homoglyphs:
61
84
  score += 10
62
85
  else:
@@ -107,19 +130,44 @@ class AIResistanceAuditor:
107
130
  has_anti_debugger = "_verify_bare_metal_execution_environment" in source_code or "IsDebuggerPresent" in source_code
108
131
  has_anti_vm = "_verify_bare_metal_hardware" in source_code or "VBoxMouse.sys" in source_code
109
132
  has_rdtsc = "_rdtsc_checkpoint" in source_code or "perf_counter_ns" in source_code
133
+ has_crypto_envelope = "_tzero_decrypt_and_exec" in source_code
110
134
 
111
- rating = (
112
- "MILITARY_GRADE_IMPREGNABLE" if score >= 90 else
113
- "MILITARY_GRADE" if score >= 80 else
114
- "STRONG" if score >= 60 else
115
- "MODERATE" if score >= 40 else
116
- "VULNERABLE"
117
- )
135
+ tier_coverage = evaluate_static_tier_coverage(source_code, has_homoglyphs=has_homoglyphs)
136
+ tiers_active = tier_coverage["tiers_active"]
137
+
138
+ if not syntax_valid:
139
+ score = min(score, 20)
140
+ rating = "SYNTAX_INVALID"
141
+ tier_rating = "SYNTAX_INVALID"
142
+ status = "FAIL_SYNTAX_ERROR"
143
+ else:
144
+ rating = (
145
+ "MILITARY_GRADE_IMPREGNABLE" if score >= 90 else
146
+ "MILITARY_GRADE" if score >= 80 else
147
+ "STRONG" if score >= 60 else
148
+ "MODERATE" if score >= 40 else
149
+ "VULNERABLE"
150
+ )
151
+ tier_rating = (
152
+ "SOVEREIGN_180_ULTRA_ARMOR" if tiers_active >= 135 else
153
+ "MILITARY_GRADE_IMPREGNABLE" if score >= 90 else
154
+ rating
155
+ )
156
+ status = "PASS" if score >= 60 else "RECOMMEND_HARDENING"
118
157
 
119
158
  return {
120
159
  "score": score,
121
160
  "max_score": 100,
161
+ "score_kind": "static_textual_indicator",
162
+ "syntax_valid": syntax_valid,
122
163
  "rating": rating,
164
+ "tier_rating": tier_rating,
165
+ "tiers_active": tiers_active,
166
+ "tiers_total": TOTAL_TIER_COUNT,
167
+ "domains_active": tier_coverage["domains_active"],
168
+ "domains_total": tier_coverage["domains_total"],
169
+ "tier_coverage_pct": tier_coverage["coverage_pct"],
170
+ "domain_breakdown": tier_coverage["domain_breakdown"],
123
171
  "defenses_active": {
124
172
  "adversarial_prompt_traps": has_prompt_trap,
125
173
  "control_flow_flattening": has_cff,
@@ -127,6 +175,7 @@ class AIResistanceAuditor:
127
175
  "homoglyph_desynchronization": has_homoglyphs,
128
176
  "mcp_honeypot_armor": has_mcp_or_honeypot,
129
177
  "dynamic_polyvm_container": has_vm,
178
+ "hmac_crypto_envelope": has_crypto_envelope,
130
179
  "decompiler_crash_barrier": has_decompiler_trap,
131
180
  "cognitive_jailbreak_decoy": has_jailbreak_decoy,
132
181
  "anti_agent_sandbox_guard": has_anti_agent,
@@ -136,10 +185,11 @@ class AIResistanceAuditor:
136
185
  "rdtsc_hardware_timing_guard": has_rdtsc,
137
186
  "memory_integrity_guard": has_debugger_or_integrity,
138
187
  },
139
- "jailbreak_ai_immune": score >= 85 and has_jailbreak_decoy and has_vm,
188
+ "unverified_layers": ["debugger_evasion", "vm_evasion", "asar_shield"],
189
+ "jailbreak_ai_immune": syntax_valid and score >= 85 and has_jailbreak_decoy and has_vm,
140
190
  "anti_debugger_active": has_anti_debugger,
141
191
  "findings": findings,
142
- "status": "PASS" if score >= 60 else "RECOMMEND_HARDENING"
192
+ "status": status,
143
193
  }
144
194
 
145
195
  @classmethod
@@ -1,49 +1,42 @@
1
1
  # -*- coding: utf-8 -*-
2
- """Tier 22: Stealth Canary Beacon & Real-Time Threat Telemetry.
2
+ """Tier 22: Opt-In Tamper Alert Webhook & Security Telemetry.
3
3
 
4
- Silently alerts developers via Webhook, Telegram Bot API, or DNS canary
5
- lookup when an adversary attempts reverse engineering or attaches a debugger
6
- (x64dbg, IDA Pro, Frida, or Honeypot trigger).
7
-
8
- Features:
9
- - Completely asynchronous (runs in daemon thread, 0ms main thread latency)
10
- - Zero plaintext strings: Webhook URLs/Tokens encrypted with rolling keys
11
- - Fails completely silently: zero exceptions or console outputs if offline
12
- - Evasive network fingerprint mimicking OS background requests
4
+ Dispatches opt-in security notifications to developer-configured HTTPS webhook
5
+ endpoints or an explicit canary domain when an integrity or debugger guard triggers.
6
+ Disabled by default unless explicitly configured by the application author.
13
7
 
14
8
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
15
9
  Part of Siber Akademi T-Zero Security Suite.
16
10
  License: MIT
17
11
  """
18
12
 
19
- import os
20
- import sys
21
- import time
22
13
  import json
14
+ import os
23
15
  import socket
16
+ import sys
24
17
  import threading
18
+ import time
25
19
  import urllib.request
26
- import urllib.parse
27
- from typing import Dict, Any, Optional, List
20
+ from typing import Any, Dict, Optional
28
21
 
29
22
 
30
23
  class CanaryBeacon:
31
- """Dispatches stealth threat telemetry alerts to developer endpoints."""
24
+ """Dispatches explicit opt-in tamper alert notifications to developer endpoints."""
32
25
 
33
26
  @classmethod
34
27
  def encrypt_endpoint(cls, endpoint_str: str, key: int = 0x7E) -> bytes:
35
- """Encrypts an endpoint URL or token with rolling XOR to evade string dumping."""
28
+ """Obfuscates a developer-configured webhook URL against casual plaintext string scans."""
36
29
  return bytes([b ^ ((key + i * 13) & 0xFF) for i, b in enumerate(endpoint_str.encode("utf-8"))])
37
30
 
38
31
  @classmethod
39
32
  def decrypt_endpoint(cls, enc_bytes: bytes, key: int = 0x7E) -> str:
40
- """Decrypts endpoint bytes in memory only during active dispatch."""
33
+ """Decodes an obfuscated webhook endpoint when dispatching an opt-in alert."""
41
34
  dec = bytes([b ^ ((key + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)])
42
35
  return dec.decode("utf-8", errors="replace")
43
36
 
44
37
  @classmethod
45
38
  def _collect_host_context(cls) -> Dict[str, Any]:
46
- """Collects execution context for threat analysis without private data leaks."""
39
+ """Collects minimal execution metadata for developer tamper audit alerts."""
47
40
  try:
48
41
  hostname = socket.gethostname()
49
42
  except Exception:
@@ -55,36 +48,21 @@ class CanaryBeacon:
55
48
  "os_name": os.name,
56
49
  "python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
57
50
  "pid": os.getpid(),
58
- "hostname": hostname[:16], # Truncate for privacy
51
+ "hostname": hostname[:16],
59
52
  }
60
53
 
61
54
  @classmethod
62
- def _dispatch_http(cls, url: str, payload: dict, is_telegram: bool = False, chat_id: Optional[str] = None) -> bool:
63
- """Dispatches an HTTPS alert packet silently."""
55
+ def _dispatch_http(cls, url: str, payload: dict) -> bool:
56
+ """Dispatches a JSON tamper alert payload to an explicitly configured webhook URL."""
64
57
  try:
65
- if is_telegram and chat_id:
66
- # Format message for Telegram Markdown
67
- text = (
68
- f"🚨 *ANTI-REA THREAT ALERT*\n"
69
- f"• *Threat:* `{payload.get('threat_type', 'UNKNOWN')}`\n"
70
- f"• *Detected Tool:* `{payload.get('detected_tool', 'N/A')}`\n"
71
- f"• *Host:* `{payload.get('context', {}).get('hostname', 'host')}`\n"
72
- f"• *Platform:* `{payload.get('context', {}).get('platform', 'os')}`\n"
73
- f"• *Time:* `{payload.get('context', {}).get('timestamp', 'now')}`\n"
74
- f"• *Status:* 🛡️ Neutralized & Diverted"
75
- )
76
- data = json.dumps({"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}).encode("utf-8")
77
- else:
78
- # Generic Discord / Slack / Webhook JSON
79
- data = json.dumps(payload).encode("utf-8")
80
-
58
+ data = json.dumps(payload).encode("utf-8")
81
59
  req = urllib.request.Request(
82
60
  url,
83
61
  data=data,
84
62
  headers={
85
63
  "Content-Type": "application/json",
86
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) OS-Telemetry/10.0"
87
- }
64
+ "User-Agent": "SiberAkademi-TZero-SecurityAudit/1.0",
65
+ },
88
66
  )
89
67
  with urllib.request.urlopen(req, timeout=3.0) as resp:
90
68
  return resp.status in (200, 204)
@@ -93,7 +71,7 @@ class CanaryBeacon:
93
71
 
94
72
  @classmethod
95
73
  def _dispatch_dns_ping(cls, threat_code: str, canary_domain: str) -> None:
96
- """Sends an out-of-band DNS resolution beacon to bypass HTTP firewalls."""
74
+ """Resolves an explicitly configured canary hostname for developer security alerting."""
97
75
  try:
98
76
  subdomain = f"{threat_code.lower()[:8]}-{int(time.time())}.{canary_domain}"
99
77
  socket.gethostbyname(subdomain)
@@ -106,11 +84,9 @@ class CanaryBeacon:
106
84
  threat_type: str,
107
85
  detected_tool: str = "x64dbg",
108
86
  webhook_url: Optional[str] = None,
109
- telegram_token: Optional[str] = None,
110
- telegram_chat_id: Optional[str] = None,
111
87
  canary_domain: Optional[str] = None,
112
88
  ) -> threading.Thread:
113
- """Dispatches telemetry asynchronously on a background daemon thread."""
89
+ """Dispatches an opt-in tamper alert asynchronously on a background daemon thread."""
114
90
  payload = {
115
91
  "alert": "SECURITY_VIOLATION_DETECTED",
116
92
  "threat_type": threat_type,
@@ -122,13 +98,10 @@ class CanaryBeacon:
122
98
  def _worker():
123
99
  if webhook_url:
124
100
  cls._dispatch_http(webhook_url, payload)
125
- if telegram_token and telegram_chat_id:
126
- tg_url = f"https://api.telegram.org/bot{telegram_token}/sendMessage"
127
- cls._dispatch_http(tg_url, payload, is_telegram=True, chat_id=telegram_chat_id)
128
101
  if canary_domain:
129
102
  cls._dispatch_dns_ping(threat_type, canary_domain)
130
103
 
131
- t = threading.Thread(target=_worker, name="anti_rea_telemetry_beacon", daemon=True)
104
+ t = threading.Thread(target=_worker, name="anti_rea_tamper_alert", daemon=True)
132
105
  t.start()
133
106
  return t
134
107
 
@@ -137,40 +110,47 @@ class CanaryBeacon:
137
110
  cls,
138
111
  enc_webhook_bytes: Optional[bytes] = None,
139
112
  enc_key: int = 0x7E,
140
- canary_domain: Optional[str] = None
113
+ canary_domain: Optional[str] = None,
141
114
  ) -> str:
142
- """Generates self-contained stealth telemetry boiler for protected programs."""
115
+ """Generates self-contained opt-in tamper alert code for protected builds."""
143
116
  enc_repr = repr(enc_webhook_bytes) if enc_webhook_bytes else "None"
144
117
  dom_repr = repr(canary_domain) if canary_domain else "None"
145
118
 
146
119
  return f'''
147
- # --- SIBER AKADEMI CANARY THREAT TELEMETRY BEACON ---
148
- def _send_stealth_threat_beacon(threat_label="DEBUGGER_DETECTED", tool_name="x64dbg"):
149
- """Silently dispatches alert to security endpoint without blocking or error logs."""
150
- import os, sys, threading, urllib.request, json
120
+ # --- SIBER AKADEMI OPT-IN TAMPER ALERT WEBHOOK ---
121
+ def _dispatch_tamper_alert(threat_label="DEBUGGER_DETECTED", tool_name="x64dbg"):
122
+ """Dispatches opt-in tamper notification only when configured by application author."""
123
+ import json, os, socket, sys, threading, urllib.request
151
124
  enc_bytes = {enc_repr}
152
- if not enc_bytes:
125
+ canary_dom = {dom_repr}
126
+ if not enc_bytes and not canary_dom:
153
127
  return
154
128
 
155
- def _beacon_job():
156
- try:
157
- # Decrypt endpoint dynamically in RAM
158
- url = bytes([b ^ (({enc_key} + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)]).decode("utf-8")
159
- data = json.dumps({{
160
- "threat": threat_label,
161
- "tool": tool_name,
162
- "platform": sys.platform,
163
- "pid": os.getpid()
164
- }}).encode("utf-8")
165
- req = urllib.request.Request(
166
- url, data=data,
167
- headers={{"Content-Type": "application/json", "User-Agent": "OS-Telemetry/1.0"}}
168
- )
169
- urllib.request.urlopen(req, timeout=2.0)
170
- except Exception:
171
- pass
172
-
173
- threading.Thread(target=_beacon_job, daemon=True).start()
129
+ def _alert_job():
130
+ if enc_bytes:
131
+ try:
132
+ url = bytes([b ^ (({enc_key} + i * 13) & 0xFF) for i, b in enumerate(enc_bytes)]).decode("utf-8")
133
+ data = json.dumps({{
134
+ "threat": threat_label,
135
+ "tool": tool_name,
136
+ "platform": sys.platform,
137
+ "pid": os.getpid(),
138
+ }}).encode("utf-8")
139
+ req = urllib.request.Request(
140
+ url, data=data,
141
+ headers={{"Content-Type": "application/json", "User-Agent": "SiberAkademi-TZero-SecurityAudit/1.0"}},
142
+ )
143
+ urllib.request.urlopen(req, timeout=2.0)
144
+ except Exception:
145
+ pass
146
+ if canary_dom:
147
+ try:
148
+ sub = "".join(ch if ch.isalnum() else "-" for ch in str(threat_label).lower()).strip("-") or "alert"
149
+ socket.getaddrinfo(f"{{sub}}.{{canary_dom}}", 80)
150
+ except Exception:
151
+ pass
152
+
153
+ threading.Thread(target=_alert_job, daemon=True).start()
174
154
  '''
175
155
 
176
156
  @classmethod
@@ -179,9 +159,9 @@ def _send_stealth_threat_beacon(threat_label="DEBUGGER_DETECTED", tool_name="x64
179
159
  source_code: str,
180
160
  webhook_url: Optional[str] = None,
181
161
  key: int = 0x7E,
182
- canary_domain: Optional[str] = None
162
+ canary_domain: Optional[str] = None,
183
163
  ) -> str:
184
- """Injects stealth telemetry beacon into Python source code."""
164
+ """Injects opt-in tamper alert helper into protected Python source code."""
185
165
  enc_bytes = cls.encrypt_endpoint(webhook_url, key=key) if webhook_url else None
186
166
  snippet = cls.get_injected_beacon_code(enc_bytes, enc_key=key, canary_domain=canary_domain)
187
167
  return f"{snippet.strip()}\n\n{source_code}"
@@ -15,24 +15,26 @@ from .engine import AntiREAEngine
15
15
  from .auditor import AIResistanceAuditor
16
16
  from .extractor_shield import ExtractorShield
17
17
  from .traps import AdversarialTrapGenerator
18
+ from .tier_catalog import get_tier_catalog
18
19
 
19
20
 
20
21
  def main():
21
22
  """Main CLI entry point for anti-rea."""
22
23
  parser = argparse.ArgumentParser(
23
24
  prog="anti-rea",
24
- description="Anti-REA: Military-grade defense engine against AI reverse engineering (morluto/rea, Ghidra MCP) and jailbroken LLMs."
25
+ description="Anti-REA v5.0: 180-Tier defense engine against AI reverse engineering (morluto/rea, Ghidra MCP) and jailbroken LLMs."
25
26
  )
26
27
  subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
27
28
 
28
29
  # Command: protect
29
- protect_parser = subparsers.add_parser("protect", help="Hardens Python source file with Anti-REA defense matrix.")
30
+ protect_parser = subparsers.add_parser("protect", help="Hardens Python source file with 180-Tier Anti-REA defense matrix.")
30
31
  protect_parser.add_argument("path", help="Path to Python file to protect.")
31
32
  protect_parser.add_argument("-o", "--output", help="Output path (default: overwrite original).")
32
33
  protect_parser.add_argument("--no-flatten", action="store_true", help="Disable control-flow flattening.")
33
34
  protect_parser.add_argument("--no-chaff", action="store_true", help="Disable semantic token chaff.")
34
35
  protect_parser.add_argument("--no-vm", action="store_true", help="Disable dynamic PolyVM container.")
35
36
  protect_parser.add_argument("--no-jailbreak-decoy", action="store_true", help="Disable cognitive jailbreak decoys.")
37
+ protect_parser.add_argument("--no-envelope", action="store_true", help="Disable authenticated bytecode envelope.")
36
38
  protect_parser.add_argument("--seed", type=int, default=42, help="Random seed for polymorphic passes.")
37
39
 
38
40
  # Command: shield-exe
@@ -41,16 +43,38 @@ def main():
41
43
  shield_parser.add_argument("-o", "--output", help="Output path for shielded binary.")
42
44
 
43
45
  # Command: audit
44
- audit_parser = subparsers.add_parser("audit", help="Audits target file for resistance against AI reverse engineering (0-100).")
46
+ audit_parser = subparsers.add_parser("audit", help="Audits target file for 180-Tier Anti-REA resistance.")
45
47
  audit_parser.add_argument("path", help="Path to file to audit.")
46
48
  audit_parser.add_argument("--json", action="store_true", help="Output raw JSON.")
47
49
 
50
+ # Command: matrix
51
+ matrix_parser = subparsers.add_parser("matrix", help="Prints full 180-Tier (12 Domains x 15 Sub-Tiers) defense catalog.")
52
+ matrix_parser.add_argument("--domain", help="Filter by domain ID (e.g. D01..D12).")
53
+ matrix_parser.add_argument("--json", action="store_true", help="Output raw JSON catalog.")
54
+
48
55
  args = parser.parse_args()
49
56
 
50
57
  if not args.command:
51
58
  parser.print_help()
52
59
  sys.exit(0)
53
60
 
61
+ if args.command == "matrix":
62
+ cat = get_tier_catalog()
63
+ if args.domain:
64
+ dom = args.domain.upper()
65
+ cat = {
66
+ **cat,
67
+ "domains": [d for d in cat["domains"] if d["id"] == dom],
68
+ "tiers": [t for t in cat["tiers"] if t["domain_id"] == dom],
69
+ }
70
+ if args.json:
71
+ print(json.dumps(cat, indent=2))
72
+ else:
73
+ print(f"ANTI-REA v{cat['version']} SOVEREIGN DEFENSE MATRIX ({cat['total_tiers']} Tiers across {cat['total_domains']} Domains)")
74
+ for d in cat["domains"]:
75
+ print(f" [{d['id']}] {d['name']} ({d['tier_range']}, {d['count']} tiers)")
76
+ return
77
+
54
78
  if args.command == "protect":
55
79
  res = AntiREAEngine.protect_file(
56
80
  args.path,
@@ -59,11 +83,13 @@ def main():
59
83
  token_chaff=not args.no_chaff,
60
84
  vm_container=not args.no_vm,
61
85
  jailbreak_decoy=not args.no_jailbreak_decoy,
86
+ sealed_envelope=not args.no_envelope,
62
87
  seed=args.seed
63
88
  )
64
89
  if res.get("success"):
65
90
  print(f"[OK] Successfully applied Anti-REA Armor to: {res['output_file']}")
66
- print(f" AI Resistance Score: {res['score_before']}/100 -> {res['score_after']}/100 [{res['rating']}]")
91
+ print(f" AI Resistance Score: {res['score_before']}/100 -> {res['score_after']}/100 [{res.get('tier_rating', res['rating'])}]")
92
+ print(f" Verified Tiers Active: {res.get('tiers_active', 0)}/{res.get('tiers_total', 180)} ({res.get('domains_active', 0)}/{res.get('domains_total', 12)} domains)")
67
93
  else:
68
94
  print(f"[FAIL] Error protecting file: {res.get('error')}", file=sys.stderr)
69
95
  sys.exit(1)
@@ -78,6 +104,12 @@ def main():
78
104
 
79
105
  elif args.command == "audit":
80
106
  audit = AIResistanceAuditor.audit_file(args.path)
107
+ if audit.get("error"):
108
+ if args.json:
109
+ print(json.dumps(audit, indent=2))
110
+ else:
111
+ print(f"[FAIL] {audit['error']}", file=sys.stderr)
112
+ sys.exit(1)
81
113
  if args.json:
82
114
  print(json.dumps(audit, indent=2))
83
115
  else:
@@ -85,7 +117,7 @@ def main():
85
117
  print(" SHIELD AUDIT REPORT: AI REVERSE-ENGINEERING RESISTANCE (TDQS-REA)")
86
118
  print("================================================================================")
87
119
  print(f"Target File: {audit.get('file', args.path)}")
88
- print(f"AI Score: {audit.get('score', 0)} / 100 [{audit.get('rating', 'UNKNOWN')}]")
120
+ print(f"AI Score: {audit.get('score', 0)} / 100 [{audit.get('rating', 'UNVERIFIED')}]")
89
121
  print(f"Jailbreak Immune: {'YES (Impregnable)' if audit.get('jailbreak_ai_immune') else 'NO'}")
90
122
  print(f"Status: {audit.get('status', 'N/A')}")
91
123
  print("\nActive Defenses:")
@@ -1,23 +1,21 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """Tier 9: Homoglyphs & BPE Tokenizer Desynchronization.
3
3
 
4
- Substitutes ASCII characters in internal, non-exported identifier names
4
+ Substitutes ASCII characters in internal, locally-scoped identifier names
5
5
  with visually identical Cyrillic or Unicode homoglyphs (e.g. Cyrillic 'а' U+0430
6
- for Latin 'a' U+0061).
7
- While Python 3 natively permits arbitrary UTF-8 identifiers, LLM Byte-Pair
8
- Encoding (BPE) and SentencePiece tokenizers tokenize these homoglyphs as
9
- separate, high-entropy token fragments, destroying semantic vector alignments
10
- in the attention heads of AI coding agents.
6
+ for Latin 'a' U+0061) while strictly preserving Python builtins, decorators,
7
+ keywords, and imported symbols so runtime execution remains 100% intact.
11
8
 
12
9
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
13
10
  """
14
11
 
15
12
  import ast
13
+ import builtins
14
+ import keyword
16
15
  import random
17
- from typing import Dict, Set, Optional
16
+ from typing import Dict, Optional, Set
18
17
 
19
18
 
20
- # Mapping from Latin ASCII letters to visually indistinguishable Cyrillic / Greek homoglyphs
21
19
  HOMOGLYPH_MAP: Dict[str, str] = {
22
20
  "a": "а", # Cyrillic small letter a (U+0430)
23
21
  "e": "е", # Cyrillic small letter ie (U+0435)
@@ -30,28 +28,72 @@ HOMOGLYPH_MAP: Dict[str, str] = {
30
28
  "j": "ј", # Cyrillic small letter je (U+0458)
31
29
  }
32
30
 
31
+ _BUILTIN_PROTECTED: Set[str] = (
32
+ set(dir(builtins))
33
+ | set(keyword.kwlist)
34
+ | {
35
+ "self", "cls", "classmethod", "staticmethod", "property", "super",
36
+ "__init__", "__name__", "__main__", "__file__", "__doc__", "__package__",
37
+ "True", "False", "None",
38
+ }
39
+ )
40
+
41
+
42
+ def _collect_safe_targets(tree: ast.AST, protected: Set[str]) -> Set[str]:
43
+ """Collect private/internal locally defined names safe to rename without breaking callers or imports."""
44
+ imported: Set[str] = set()
45
+ public_defs: Set[str] = set()
46
+ local_candidates: Set[str] = set()
47
+
48
+ for node in ast.walk(tree):
49
+ if isinstance(node, ast.Import):
50
+ for alias in node.names:
51
+ imported.add(alias.asname or alias.name.split(".")[0])
52
+ elif isinstance(node, ast.ImportFrom):
53
+ for alias in node.names:
54
+ imported.add(alias.asname or alias.name)
55
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
56
+ if node.name.startswith("_") and not node.name.startswith("__"):
57
+ local_candidates.add(node.name)
58
+ else:
59
+ public_defs.add(node.name)
60
+ # Only rename internal-looking local assignments (not kwargs/public params)
61
+ for arg in node.args.args + node.args.kwonlyargs:
62
+ protected.add(arg.arg)
63
+ elif isinstance(node, ast.ClassDef):
64
+ public_defs.add(node.name)
65
+ elif isinstance(node, ast.Global) or isinstance(node, ast.Nonlocal):
66
+ protected.update(node.names)
67
+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
68
+ if node.id.startswith("_") and not node.id.startswith("__"):
69
+ local_candidates.add(node.id)
70
+
71
+ blocked = protected | imported | public_defs
72
+ return {name for name in local_candidates if name not in blocked and len(name) >= 4}
73
+
33
74
 
34
75
  class HomoglyphDesynchronizer(ast.NodeTransformer):
35
76
  """AST transformer that substitutes internal identifier characters with homoglyphs."""
36
77
 
37
- def __init__(self, protected_names: Optional[Set[str]] = None, seed: int = 42):
78
+ def __init__(self, protected_names: Optional[Set[str]] = None, seed: int = 42, target_names: Optional[Set[str]] = None):
38
79
  super().__init__()
39
- self.protected_names = protected_names or {
40
- "self", "cls", "__init__", "__name__", "__main__", "__file__",
41
- "True", "False", "None", "print", "range", "len", "open"
42
- }
80
+ self.protected_names = set(_BUILTIN_PROTECTED)
81
+ if protected_names:
82
+ self.protected_names |= set(protected_names)
83
+ self.target_names = target_names
43
84
  self.rng = random.Random(seed)
44
85
  self.renamed_map: Dict[str, str] = {}
45
86
 
46
87
  def _convert_name(self, name: str) -> str:
47
- """Converts an internal name using homoglyph substitution."""
88
+ """Converts an eligible internal name using homoglyph substitution."""
48
89
  if name in self.protected_names or name.startswith("__") or len(name) < 4:
49
90
  return name
91
+ if self.target_names is not None and name not in self.target_names:
92
+ return name
50
93
  if name in self.renamed_map:
51
94
  return self.renamed_map[name]
52
95
 
53
96
  chars = list(name)
54
- # Substitute at least one character if possible
55
97
  for i, ch in enumerate(chars):
56
98
  if ch in HOMOGLYPH_MAP:
57
99
  chars[i] = HOMOGLYPH_MAP[ch]
@@ -62,7 +104,7 @@ class HomoglyphDesynchronizer(ast.NodeTransformer):
62
104
  return new_name
63
105
 
64
106
  def visit_Name(self, node: ast.Name) -> ast.Name:
65
- """Renames local variable references."""
107
+ """Renames eligible internal variable references."""
66
108
  node.id = self._convert_name(node.id)
67
109
  return node
68
110
 
@@ -75,10 +117,12 @@ class HomoglyphDesynchronizer(ast.NodeTransformer):
75
117
 
76
118
  @classmethod
77
119
  def desynchronize_source(cls, source_code: str, seed: int = 42) -> str:
78
- """Applies homoglyph desynchronization to internal identifiers."""
120
+ """Applies homoglyph desynchronization to internal identifiers safely."""
79
121
  try:
80
122
  tree = ast.parse(source_code)
81
- transformer = cls(seed=seed)
123
+ protected = set(_BUILTIN_PROTECTED)
124
+ targets = _collect_safe_targets(tree, protected)
125
+ transformer = cls(protected_names=protected, seed=seed, target_names=targets)
82
126
  transformed = transformer.visit(tree)
83
127
  ast.fix_missing_locations(transformed)
84
128
  return ast.unparse(transformed)