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
package/README.md CHANGED
@@ -5,6 +5,7 @@
5
5
  [![npm version](https://img.shields.io/npm/v/tzero-mcp.svg?color=cb3837&logo=npm)](https://www.npmjs.com/package/tzero-mcp)
6
6
  [![License: AGPL-3.0-only](https://img.shields.io/badge/License-AGPL--3.0--only-yellow.svg)](./LICENSE)
7
7
  [![Socket Badge](https://socket.dev/api/badge/npm/package/tzero-mcp)](https://socket.dev/npm/package/tzero-mcp)
8
+ [![Product Hunt](https://img.shields.io/badge/Product%20Hunt-T--Zero%20Launch-DA552F?style=flat-square&logo=producthunt&logoColor=white)](https://www.producthunt.com/products/tzeroalgorithm?launch=tzeroalgorithm)
8
9
  [![GitHub Stars](https://img.shields.io/github/stars/toprakahmetaydogmus/TZeroAlgorithm?style=social)](https://github.com/toprakahmetaydogmus/TZeroAlgorithm)
9
10
 
10
11
  ---
@@ -20,44 +21,19 @@ If this package helps your engineering team or AI workflows:
20
21
 
21
22
  ---
22
23
 
23
- ## Instant MCP Execution (Zero Install Needed)
24
+ ## Security advisory
24
25
 
25
- Run directly via `npx` in your `claude_desktop_config.json`, Cursor MCP settings, or Windsurf / Antigravity config:
26
+ GitHub flags **`tzero-mcp@12.3.0`** in [GHSA-pm3r-rxg9-cj5j](https://github.com/advisories/GHSA-pm3r-rxg9-cj5j). If you installed or ran that version, follow the advisory's remediation guidance. GitHub lists no patched version.
26
27
 
27
- ```json
28
- {
29
- "mcpServers": {
30
- "tzero": {
31
- "command": "npx",
32
- "args": ["-y", "tzero-mcp@latest"]
33
- }
34
- }
35
- }
36
- ```
37
-
38
- ## CLI Installation & Usage
39
-
40
- ```bash
41
- # Global installation via npm
42
- npm install -g tzero-mcp
43
-
44
- # Compress any project directory into an AST Skeleton tree (95% token savings)
45
- tzero --tree . --out tree.txt
46
-
47
- # Launch interactive Model Context Protocol (MCP) Server
48
- tzero-mcp
49
-
50
- # 1-Click connect to Cursor, Claude Desktop, Antigravity & VS Code
51
- tzero-add-mcp
52
- ```
28
+ This npm package uses a separate Python interpreter. It requires Python dependencies to be installed explicitly for that interpreter. See the [source repository](https://github.com/toprakahmetaydogmus/TZeroAlgorithm) for setup instructions and [network and system behavior](https://github.com/toprakahmetaydogmus/TZeroAlgorithm/blob/main/PRIVACY.md).
53
29
 
54
30
  ## Key Capabilities
55
31
 
56
32
  - **95% Deterministic Token Reduction:** Compresses source code into AST skeletons preserving function signatures, type annotations, and docstrings while pruning redundant logic bodies.
57
- - **100% Zero-Leak Security Guard:** Deep Shannon Entropy ($H \ge 4.75$) scanner for API keys and secrets before LLM context ingestion.
33
+ - **Secret scanning:** Deep Shannon Entropy ($H \ge 4.75$) scanner for API keys and secrets before LLM context ingestion.
58
34
  - **Reality-Lock Pre-Flight:** Catches hallucinations before code execution by validating imports and call hierarchies against real AST nodes.
59
35
  - **20 Native Developer Tools:** AST PageRank, call-chain tracer, BM25 semantic hybrid search, change blast radius analyzer, and system doctor.
60
- - **100% Private, Local & Free:** Pure offline operation — $0 API cost, zero cloud lock-in.
36
+ - **Local AST parsing and lexical search:** These operations run on the machine hosting T-Zero.
61
37
 
62
38
  ## License
63
39
 
package/bin/tzero-mcp.js CHANGED
@@ -15,9 +15,9 @@ const pkg = require("../package.json");
15
15
  const banner = `\x1b[36m
16
16
  ┌──────────────────────────────────────────────────────────────────────────────┐
17
17
  │ ⚡ T-ZERO MCP SERVER v${pkg.version} (Model Context Protocol) │
18
- │ Enterprise AST Context Compressor, Zero-Leak Guard & 20 Canonical Tools │
18
+ │ Enterprise AST Context Compressor, Zero-Leak Guard & 21 Canonical Tools │
19
19
  │ │
20
- │ ⭐ Help Reach 100 Stars: https://github.com/toprakahmetaydogmus/TZeroAlgorithm │
20
+ │ ⭐ GitHub (119+ Stars): https://github.com/toprakahmetaydogmus/TZeroAlgorithm │
21
21
  │ 🔌 Connected to: Cursor, Claude Desktop, Antigravity, Windsurf & Cline │
22
22
  └──────────────────────────────────────────────────────────────────────────────┘
23
23
  \x1b[0m`;
package/bin/tzero.js CHANGED
@@ -35,17 +35,22 @@ if (!isQuiet) {
35
35
  if (process.argv.includes("star") || process.argv.includes("--star")) {
36
36
  console.log(`\x1b[33m
37
37
  ╔══════════════════════════════════════════════════════════════════════════════╗
38
- ║ ⭐ T-ZERO 100 STARS GOAL: JOIN THE COMMUNITY! ║
38
+ ║ ⭐ T-ZERO OPEN SOURCE: SUPPORT US WITH A GITHUB STAR! ║
39
39
  ╠══════════════════════════════════════════════════════════════════════════════╣
40
- ║ 🎉 20,880+ Downloads across PyPI & npm! ║
41
- ║ ⭐ Current Stars: 45 / 100 Target ║
40
+ ║ 🎉 26,290+ Downloads across PyPI, npm, Open VSX, VS Code & Releases! ║
41
+ ║ ⭐ Live Stars: 119+ (Goal: 250) ║
42
42
  ║ ► Opening GitHub: https://github.com/toprakahmetaydogmus/TZeroAlgorithm ║
43
43
  ╚══════════════════════════════════════════════════════════════════════════════╝
44
44
  \x1b[0m`);
45
- const openCmd = process.platform === "win32" ? "start" : process.platform === "darwin" ? "open" : "xdg-open";
45
+ const repoUrl = "https://github.com/toprakahmetaydogmus/TZeroAlgorithm";
46
46
  try {
47
- const { exec } = require("child_process");
48
- exec(`${openCmd} https://github.com/toprakahmetaydogmus/TZeroAlgorithm`);
47
+ if (process.platform === "win32") {
48
+ spawn("cmd.exe", ["/c", "start", "", repoUrl], { shell: false, stdio: "ignore", detached: true }).unref();
49
+ } else if (process.platform === "darwin") {
50
+ spawn("open", [repoUrl], { shell: false, stdio: "ignore", detached: true }).unref();
51
+ } else {
52
+ spawn("xdg-open", [repoUrl], { shell: false, stdio: "ignore", detached: true }).unref();
53
+ }
49
54
  } catch (e) {}
50
55
  }
51
56
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tzero-mcp",
3
- "version": "12.2.1",
3
+ "version": "12.3.2",
4
4
  "description": "Deterministic AST Context Compressor, 95% Token Reducer & 20-Tool MCP Server for Cursor, Claude Desktop & Copilot",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -36,7 +36,6 @@
36
36
  "tzero-mcp": "bin/tzero-mcp.js"
37
37
  },
38
38
  "scripts": {
39
- "postinstall": "node bin/postinstall.js",
40
39
  "test": "node --test test/package.test.js"
41
40
  },
42
41
  "repository": {
package/src/addmcp.py CHANGED
@@ -22,7 +22,7 @@ from pathlib import Path
22
22
  from typing import Callable, Dict, List, Optional, Tuple
23
23
 
24
24
 
25
- APP_VERSION = "12.2.1"
25
+ APP_VERSION = "12.3.2"
26
26
  SERVER_NAME = "tzero"
27
27
  SERVER_FILENAME = "TZeroMCP.exe"
28
28
 
@@ -1131,7 +1131,7 @@ def run_init(argv: Optional[List[str]] = None) -> int:
1131
1131
  # Print banner
1132
1132
  print(sanitize_terminal_text("""
1133
1133
  \033[1;36m================================================================================
1134
- ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v12.2.1)
1134
+ ⚡ SİBER AKADEMİ — T-ZERO 1-CLICK MCP INITIALIZATION (v12.3.2)
1135
1135
  ================================================================================\033[0m
1136
1136
  \033[32m★ Zero-Config AST Codebase Context & 100% Zero-Leak Security Guard\033[0m
1137
1137
  """))
@@ -1182,7 +1182,12 @@ def run_init(argv: Optional[List[str]] = None) -> int:
1182
1182
  if failures:
1183
1183
  print(sanitize_terminal_text(f"\033[33m⚠️ {failures} client(s) could not be updated.\033[0m"))
1184
1184
 
1185
- print(sanitize_terminal_text("""
1185
+ try:
1186
+ from tzero.tzero_growth import get_cached_community_stats
1187
+ _st = get_cached_community_stats()
1188
+ except Exception:
1189
+ _st = {"stars": 111, "target_stars": 250, "downloads_label": "22,900+"}
1190
+ print(sanitize_terminal_text(f"""
1186
1191
  \033[1;37m★ HOW TO USE IN YOUR IDE (CURSOR, CLAUDE, WINDSURF):
1187
1192
  1. Restart your IDE or Reload Window.
1188
1193
  2. In Composer / Chat, prompt your agent:\033[0m
@@ -1196,8 +1201,8 @@ def run_init(argv: Optional[List[str]] = None) -> int:
1196
1201
  │ to eliminate token bloat, costs, and AI hallucinations worldwide. │
1197
1202
  │ Search "Toprak Ahmet Aydoğmuş" on Google to learn more! │
1198
1203
  │ │
1199
- │ 🎉 \033[1;32m20,880+ Downloads across PyPI & npm!\033[1;36m │
1200
- │ ⭐ \033[1;33mHELP US REACH OUR 100 STARS GOAL (Current: 45 / 100):\033[1;36m │
1204
+ │ 🎉 \033[1;32m{_st['downloads_label']} Downloads across PyPI & npm!\033[1;36m │
1205
+ │ ⭐ \033[1;33mHELP US REACH OUR {_st['target_stars']} STARS GOAL (Current: {_st['stars']} / {_st['target_stars']}):\033[1;36m │
1201
1206
  │ \033[1;32m► Run 'tzero star' or visit: https://github.com/toprakahmetaydogmus/TZeroAlgorithm\033[1;36m │
1202
1207
  │ │
1203
1208
  │ 100% Free & Open-Source under AGPL-3.0 License. Thank you! ★ │
package/src/app.py CHANGED
@@ -11,15 +11,12 @@
11
11
  from __future__ import annotations
12
12
 
13
13
  import ast
14
- import html
15
14
  import json
16
15
  import math
17
- import os
18
16
  import re
19
- import sys
20
17
  import time
21
- from dataclasses import dataclass, field
22
- from typing import Any, Dict, List, Optional, Tuple
18
+ from dataclasses import dataclass
19
+ from typing import Any, Dict, List, Tuple
23
20
 
24
21
  # ==================================================================================================
25
22
  # ZERO-GPU COMPATIBILITY LAYER
@@ -45,7 +42,7 @@ import gradio as gr
45
42
  # ==================================================================================================
46
43
  # CONSTANTS, PALETTES & MULTI-MODEL PRICING TIERS
47
44
  # ==================================================================================================
48
- APP_VERSION = "12.2.1"
45
+ APP_VERSION = "12.3.2"
49
46
  REPO_URL = "https://github.com/toprakahmetaydogmus/TZeroAlgorithm"
50
47
  VERCEL_URL = "https://tzero-indol.vercel.app"
51
48
  SPACE_URL = "https://huggingface.co/spaces/toprakke4/tzero-token-reducer"
@@ -945,7 +942,6 @@ class SecurityQualityAuditor:
945
942
  @classmethod
946
943
  def run_full_audit(cls, code_str: str) -> Tuple[int, List[AuditFinding], Dict[str, Any]]:
947
944
  findings: List[AuditFinding] = []
948
- lines = code_str.splitlines()
949
945
 
950
946
  # 1. T-001 Zero-Leak Checks
951
947
  from tzero.tzero_security import ZeroLeakEngine
@@ -1346,8 +1342,6 @@ def calculate_roi_controller(
1346
1342
  tokens_saved_str = f"{res['monthly_tokens_saved'] / 1_000_000:,.1f} M Tokens / mo"
1347
1343
  carbon_str = f"{res['co2_kg_saved_annual']:,} kg CO2 / yr"
1348
1344
 
1349
- pricing = MODEL_PRICING.get(model_choice, MODEL_PRICING["OpenAI GPT-4o"])
1350
-
1351
1345
  roi_card_html = f"""
1352
1346
  <div class="tzero-card" style="margin-top: 10px;">
1353
1347
  <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 12px; margin-bottom: 16px;">
@@ -7,7 +7,7 @@
7
7
 
8
8
  from importlib import import_module
9
9
 
10
- __version__ = "12.2.1"
10
+ __version__ = "12.3.2"
11
11
  __author__ = "Toprak Ahmet Aydoğmuş"
12
12
  __license__ = "AGPL-3.0-only"
13
13
 
@@ -4,14 +4,14 @@
4
4
  World-class, 24-tier anti-reverse-engineering defense matrix against autonomous
5
5
  AI agents (morluto/rea, Ghidra MCP, pyinstxtractor, IDA LLM) and uncensored/jailbroken LLMs.
6
6
  Includes native Ring-3 anti-debugging against x64dbg, IDA Pro, WinDbg, and Cheat Engine,
7
- stealth canary beacon telemetry, in-flight string vault, and Electron asar shielding.
7
+ opt-in tamper alert webhook, in-flight string vault, and Electron asar shielding.
8
8
 
9
9
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
10
10
  Part of Siber Akademi T-Zero Security Suite.
11
11
  License: MIT
12
12
  """
13
13
 
14
- __version__ = "4.1.0"
14
+ __version__ = "5.0.0"
15
15
  __author__ = "Toprak Ahmet Aydoğmuş"
16
16
  __license__ = "MIT"
17
17
 
@@ -40,6 +40,14 @@ from .string_vault import StringVault
40
40
  from .asar_shield import AsarShield
41
41
  from .anti_vm import AntiVMGuard
42
42
  from .rdtsc_guard import RDTSCTimingGuard
43
+ from .crypto_loader import CryptoBytecodeEnvelope
44
+ from .tier_catalog import (
45
+ ANTI_REA_DOMAINS,
46
+ ANTI_REA_TIERS,
47
+ TOTAL_TIER_COUNT,
48
+ get_tier_catalog,
49
+ evaluate_static_tier_coverage,
50
+ )
43
51
 
44
52
  __all__ = [
45
53
  "AntiREAEngine",
@@ -67,4 +75,10 @@ __all__ = [
67
75
  "AsarShield",
68
76
  "AntiVMGuard",
69
77
  "RDTSCTimingGuard",
78
+ "CryptoBytecodeEnvelope",
79
+ "ANTI_REA_DOMAINS",
80
+ "ANTI_REA_TIERS",
81
+ "TOTAL_TIER_COUNT",
82
+ "get_tier_catalog",
83
+ "evaluate_static_tier_coverage",
70
84
  ]
@@ -1,86 +1,107 @@
1
1
  # -*- coding: utf-8 -*-
2
- """Tier 17: AST Algebraic Identity & Polymorphic Mutator.
2
+ """Tier 76-90 (Domain D06): Type-Safe AST Algebraic Identity & MBA Mutator.
3
3
 
4
- Transforms elementary arithmetic expressions (+, -, *, <<) into complex
5
- Boolean Ring identities (Mixed Boolean-Arithmetic / MBA).
4
+ Transforms integer arithmetic expressions (+, -, *) into Mixed Boolean-Arithmetic
5
+ (MBA) equivalents while guaranteeing 100% runtime compatibility for strings, floats,
6
+ lists, booleans, and custom objects via strict runtime type guards:
7
+ int + int ==> (x ^ y) + ((x & y) << 1)
8
+ int - int ==> (x ^ y) - (((~x) & y) << 1)
9
+ int * 2 ==> (x << 1)
6
10
 
7
- For example:
8
- x + y ==> (x ^ y) + 2 * (x & y)
9
- x - y ==> (x ^ y) - 2 * ((~x) & y)
10
- x * 2 ==> (x << 1)
11
- x * 4 ==> (x << 2)
12
-
13
- This destroys pattern-matching heuristics in decompilers (Ghidra, IDA, pycdc)
14
- and forces LLMs to solve exponential symbolic constraint systems to infer
15
- the original business equations.
16
-
17
- Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
11
+ Developer: Toprak Ahmet Aydogmus (Siber Akademi)
18
12
  Part of Siber Akademi T-Zero Security Suite.
19
13
  License: MIT
20
14
  """
21
15
 
22
16
  import ast
23
- from typing import Optional
17
+
18
+
19
+ _MBA_RUNTIME_HEADER = '''# --- SIBER AKADEMI TYPE-SAFE MBA ARITHMETIC ENGINE (D06: REA-076..090) ---
20
+ def _tzero_mba_add(_a, _b):
21
+ if type(_a) is int and type(_b) is int:
22
+ return (_a ^ _b) + ((_a & _b) << 1)
23
+ return _a + _b
24
+
25
+ def _tzero_mba_sub(_a, _b):
26
+ if type(_a) is int and type(_b) is int:
27
+ return (_a ^ _b) - (((~_a) & _b) << 1)
28
+ return _a - _b
29
+ '''
24
30
 
25
31
 
26
32
  class AlgebraicIdentityTransformer(ast.NodeTransformer):
27
- """AST transformer converting elementary arithmetic into MBA representations."""
33
+ """AST transformer converting pure/typed arithmetic into MBA representations safely."""
34
+
35
+ @staticmethod
36
+ def _is_pure_int_const(node: ast.AST) -> bool:
37
+ return isinstance(node, ast.Constant) and type(node.value) is int
38
+
39
+ @staticmethod
40
+ def _is_eligible_operand(node: ast.AST) -> bool:
41
+ return isinstance(node, (ast.Name, ast.BinOp, ast.Call)) or (
42
+ isinstance(node, ast.Constant) and type(node.value) is int
43
+ )
28
44
 
29
45
  def visit_BinOp(self, node: ast.BinOp) -> ast.AST:
30
46
  self.generic_visit(node)
31
47
 
32
- # 1. Transform addition: x + y ==> (x ^ y) + 2 * (x & y)
33
48
  if isinstance(node.op, ast.Add):
34
- # Only transform if operands are variables or integers (avoid string concatenation)
35
- if self._is_numeric_or_variable(node.left) and self._is_numeric_or_variable(node.right):
49
+ if self._is_pure_int_const(node.left) and self._is_pure_int_const(node.right):
36
50
  xor_part = ast.BinOp(left=node.left, op=ast.BitXor(), right=node.right)
37
51
  and_part = ast.BinOp(left=node.left, op=ast.BitAnd(), right=node.right)
38
- two_times_and = ast.BinOp(left=ast.Constant(value=2), op=ast.Mult(), right=and_part)
39
- return ast.BinOp(left=xor_part, op=ast.Add(), right=two_times_and)
52
+ shifted = ast.BinOp(left=and_part, op=ast.LShift(), right=ast.Constant(value=1))
53
+ return ast.copy_location(ast.BinOp(left=xor_part, op=ast.Add(), right=shifted), node)
54
+ if self._is_eligible_operand(node.left) and self._is_eligible_operand(node.right):
55
+ return ast.copy_location(
56
+ ast.Call(
57
+ func=ast.Name(id="_tzero_mba_add", ctx=ast.Load()),
58
+ args=[node.left, node.right],
59
+ keywords=[],
60
+ ),
61
+ node,
62
+ )
40
63
 
41
- # 2. Transform subtraction: x - y ==> (x ^ y) - 2 * ((~x) & y)
42
64
  elif isinstance(node.op, ast.Sub):
43
- if self._is_numeric_or_variable(node.left) and self._is_numeric_or_variable(node.right):
65
+ if self._is_pure_int_const(node.left) and self._is_pure_int_const(node.right):
44
66
  xor_part = ast.BinOp(left=node.left, op=ast.BitXor(), right=node.right)
45
67
  inv_left = ast.UnaryOp(op=ast.Invert(), operand=node.left)
46
68
  and_part = ast.BinOp(left=inv_left, op=ast.BitAnd(), right=node.right)
47
- two_times = ast.BinOp(left=ast.Constant(value=2), op=ast.Mult(), right=and_part)
48
- return ast.BinOp(left=xor_part, op=ast.Sub(), right=two_times)
69
+ shifted = ast.BinOp(left=and_part, op=ast.LShift(), right=ast.Constant(value=1))
70
+ return ast.copy_location(ast.BinOp(left=xor_part, op=ast.Sub(), right=shifted), node)
71
+ if self._is_eligible_operand(node.left) and self._is_eligible_operand(node.right):
72
+ return ast.copy_location(
73
+ ast.Call(
74
+ func=ast.Name(id="_tzero_mba_sub", ctx=ast.Load()),
75
+ args=[node.left, node.right],
76
+ keywords=[],
77
+ ),
78
+ node,
79
+ )
49
80
 
50
- # 3. Transform multiplication by 2, 4, 8: x * 2 ==> x << 1
51
81
  elif isinstance(node.op, ast.Mult):
52
- if isinstance(node.right, ast.Constant) and node.right.value in (2, 4, 8):
82
+ # Shift optimization ONLY when one operand is 2/4/8 AND the other is provably an int literal
83
+ if self._is_pure_int_const(node.right) and node.right.value in (2, 4, 8) and self._is_pure_int_const(node.left):
53
84
  shift = {2: 1, 4: 2, 8: 3}[node.right.value]
54
- return ast.BinOp(left=node.left, op=ast.LShift(), right=ast.Constant(value=shift))
55
- elif isinstance(node.left, ast.Constant) and node.left.value in (2, 4, 8):
85
+ return ast.copy_location(ast.BinOp(left=node.left, op=ast.LShift(), right=ast.Constant(value=shift)), node)
86
+ if self._is_pure_int_const(node.left) and node.left.value in (2, 4, 8) and self._is_pure_int_const(node.right):
56
87
  shift = {2: 1, 4: 2, 8: 3}[node.left.value]
57
- return ast.BinOp(left=node.right, op=ast.LShift(), right=ast.Constant(value=shift))
88
+ return ast.copy_location(ast.BinOp(left=node.right, op=ast.LShift(), right=ast.Constant(value=shift)), node)
58
89
 
59
90
  return node
60
91
 
61
- def _is_numeric_or_variable(self, node: ast.AST) -> bool:
62
- """Determines if node is suitable for MBA arithmetic mutation."""
63
- if isinstance(node, ast.Name):
64
- return True
65
- if isinstance(node, ast.Constant) and isinstance(node.value, int):
66
- return True
67
- if isinstance(node, ast.BinOp):
68
- return True
69
- return False
70
-
71
92
 
72
93
  class AlgebraicMutator:
73
- """Public interface for applying Mixed Boolean-Arithmetic (MBA) AST mutations."""
94
+ """Public interface for applying type-safe Mixed Boolean-Arithmetic (MBA) AST mutations."""
74
95
 
75
96
  @classmethod
76
97
  def mutate_source_code(cls, source_code: str) -> str:
77
- """Applies algebraic identity mutation across all functions in source code."""
98
+ """Applies type-safe algebraic identity mutation across expressions cleanly."""
78
99
  try:
79
100
  tree = ast.parse(source_code)
80
101
  transformer = AlgebraicIdentityTransformer()
81
102
  mutated_tree = transformer.visit(tree)
82
103
  ast.fix_missing_locations(mutated_tree)
83
- return ast.unparse(mutated_tree)
104
+ mutated = ast.unparse(mutated_tree)
105
+ return f"{_MBA_RUNTIME_HEADER}\n{mutated}"
84
106
  except Exception:
85
- # Fallback to unmodified code on unparseable edge cases
86
107
  return source_code
@@ -87,29 +87,47 @@ class AntiDebugger:
87
87
 
88
88
  @classmethod
89
89
  def check_blacklisted_processes(cls) -> List[str]:
90
- """Scans running system processes for known debugger binaries."""
90
+ """Scans running system processes natively (<2ms on Windows Toolhelp32, zero subprocess)."""
91
91
  detected = []
92
92
  try:
93
93
  if sys.platform == "win32":
94
- import subprocess
95
- # Run lightweight tasklist /fo csv
96
- res = subprocess.run(
97
- ["tasklist", "/fo", "csv", "/nh"],
98
- capture_output=True,
99
- text=True,
100
- timeout=3,
101
- creationflags=0x08000000 if hasattr(subprocess, "CREATE_NO_WINDOW") else 0
102
- )
103
- output_lower = res.stdout.lower()
104
- for proc in cls.DEBUGGER_PROCESS_NAMES:
105
- if proc in output_lower:
106
- detected.append(proc)
94
+ import ctypes
95
+ from ctypes import wintypes
96
+
97
+ class _PE32(ctypes.Structure):
98
+ _fields_ = [
99
+ ("dwSize", wintypes.DWORD),
100
+ ("cntUsage", wintypes.DWORD),
101
+ ("th32ProcessID", wintypes.DWORD),
102
+ ("th32DefaultHeapID", ctypes.c_size_t),
103
+ ("th32ModuleID", wintypes.DWORD),
104
+ ("cntThreads", wintypes.DWORD),
105
+ ("th32ParentProcessID", wintypes.DWORD),
106
+ ("pcPriClassBase", wintypes.LONG),
107
+ ("dwFlags", wintypes.DWORD),
108
+ ("szExeFile", ctypes.c_char * 260),
109
+ ]
110
+
111
+ k32 = ctypes.windll.kernel32
112
+ snap = k32.CreateToolhelp32Snapshot(0x00000002, 0)
113
+ if snap not in (-1, 0):
114
+ try:
115
+ pe = _PE32()
116
+ pe.dwSize = ctypes.sizeof(_PE32)
117
+ if k32.Process32First(snap, ctypes.byref(pe)):
118
+ while True:
119
+ exe_name = pe.szExeFile.decode("latin-1", errors="ignore").lower()
120
+ if exe_name in cls.DEBUGGER_PROCESS_NAMES:
121
+ detected.append(exe_name)
122
+ if not k32.Process32Next(snap, ctypes.byref(pe)):
123
+ break
124
+ finally:
125
+ k32.CloseHandle(snap)
107
126
  else:
108
- # POSIX process check
109
127
  for pid_dir in os.listdir("/proc"):
110
128
  if pid_dir.isdigit():
111
129
  try:
112
- with open(f"/proc/{pid_dir}/comm", "r") as f:
130
+ with open(f"/proc/{pid_dir}/comm", "r", encoding="utf-8", errors="ignore") as f:
113
131
  comm = f.read().strip().lower()
114
132
  for proc in cls.DEBUGGER_PROCESS_NAMES:
115
133
  if proc.replace(".exe", "") == comm:
@@ -153,17 +171,32 @@ class AntiDebugger:
153
171
 
154
172
  @classmethod
155
173
  def scan_debugger_environment(cls) -> Dict[str, Any]:
156
- """Performs a comprehensive scan of host debugger artifacts."""
174
+ """Performs a comprehensive scan of host debugger artifacts across Win32/POSIX/Python."""
157
175
  py_tracer = sys.gettrace() is not None
176
+ py_monitoring = False
177
+ mon = getattr(sys, "monitoring", None)
178
+ if mon is not None:
179
+ try:
180
+ py_monitoring = any(mon.get_tool(tid) is not None and tid != 5 for tid in range(6))
181
+ except Exception:
182
+ pass
183
+ preload_envs = [
184
+ env_k for env_k in ("LD_PRELOAD", "DYLD_INSERT_LIBRARIES", "PYTHONINSPECT")
185
+ if os.environ.get(env_k)
186
+ ]
158
187
  win32_dbg = cls.is_debugger_present_win32()
159
188
  posix_tracer = cls.is_tracer_pid_active_posix()
160
189
  detected_procs = cls.check_blacklisted_processes()
161
190
 
162
- is_debugged = py_tracer or win32_dbg or posix_tracer or bool(detected_procs)
191
+ is_debugged = (
192
+ py_tracer or py_monitoring or win32_dbg or posix_tracer or bool(detected_procs) or bool(preload_envs)
193
+ )
163
194
 
164
195
  return {
165
196
  "debugger_detected": is_debugged,
166
197
  "python_tracer_active": py_tracer,
198
+ "python_monitoring_active": py_monitoring,
199
+ "preload_env_detected": preload_envs,
167
200
  "win32_debugger_active": win32_dbg,
168
201
  "posix_tracer_active": posix_tracer,
169
202
  "blacklisted_debuggers_running": detected_procs,
@@ -22,7 +22,6 @@ License: MIT
22
22
 
23
23
  import os
24
24
  import struct
25
- import json
26
25
  from typing import Dict, Any, Optional, Tuple
27
26
 
28
27
 
@@ -66,6 +65,9 @@ class AsarShield:
66
65
 
67
66
  return shielded_data, {
68
67
  "shielded": True,
68
+ "original_u32_4": orig_u32_4,
69
+ "original_total_size": orig_total_size,
70
+ "original_header_size": orig_header_size,
69
71
  "original_json_len": orig_json_len,
70
72
  "poisoned_json_len": poisoned_json_len,
71
73
  "status": "ASAR_EXTRACTOR_POISONED"
@@ -97,3 +99,24 @@ class AsarShield:
97
99
  }
98
100
  except Exception as e:
99
101
  return {"success": False, "error": str(e)}
102
+
103
+ @classmethod
104
+ def protect_js_source(cls, js_source: str) -> str:
105
+ """Wraps JavaScript / Electron source with anti-debug, prototype freeze & integrity traps."""
106
+ guard = """/* SIBER AKADEMI ANTI-REA D11: ELECTRON / NODE JS GUARD */
107
+ (function(_g){
108
+ try {
109
+ if (typeof process !== 'undefined' && process.execArgv && process.execArgv.some(function(a){ return a.indexOf('--inspect') === 0; })) {
110
+ process.exit(1);
111
+ }
112
+ var _t0 = Date.now();
113
+ if (typeof Object.freeze === 'function') {
114
+ try { Object.freeze(Object.prototype); } catch(_) {}
115
+ }
116
+ if ((Date.now() - _t0) > 2500 && typeof process !== 'undefined') {
117
+ process.exit(1);
118
+ }
119
+ } catch(_) {}
120
+ })(typeof globalThis !== 'undefined' ? globalThis : this);
121
+ """
122
+ return f"{guard}\n{js_source}"