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
@@ -212,14 +212,47 @@ class ASTMutationEngine:
212
212
 
213
213
  return mutants
214
214
 
215
+ _ALLOWED_TEST_ARGS = {
216
+ tok: tok
217
+ for tok in ("-m", "unittest", "discover", "pytest", "-v", "-q", "--verbose", "-s", "-p", "-x", "--tb=short", "test_*.py")
218
+ }
219
+
220
+ @classmethod
221
+ def _build_allowed_test_entries(cls, roots: List[str]) -> Dict[str, str]:
222
+ """Builds an allowlist mapping real filesystem paths to verified on-disk paths."""
223
+ allowed: Dict[str, str] = {}
224
+ for root in roots:
225
+ if not os.path.isdir(root):
226
+ continue
227
+ real_root = os.path.realpath(root)
228
+ for walk_root, dirnames, files in os.walk(real_root):
229
+ dirnames[:] = [d for d in dirnames if not d.startswith(".") and d != "__pycache__"]
230
+ real_dir = os.path.realpath(walk_root)
231
+ rel_dir = os.path.relpath(real_dir, real_root)
232
+ if rel_dir != ".." and not rel_dir.startswith(".." + os.sep) and not os.path.isabs(rel_dir):
233
+ allowed[real_dir] = real_dir
234
+ for fname in files:
235
+ if not fname.endswith(".py"):
236
+ continue
237
+ real_entry = os.path.realpath(os.path.join(walk_root, fname))
238
+ rel_entry = os.path.relpath(real_entry, real_root)
239
+ if rel_entry != ".." and not rel_entry.startswith(".." + os.sep) and not os.path.isabs(rel_entry):
240
+ allowed[real_entry] = real_entry
241
+ return allowed
242
+
215
243
  @staticmethod
216
244
  def _sanitize_target_path(target_path: str) -> str:
217
245
  if not target_path or "\x00" in target_path:
218
246
  raise ValueError("Invalid target path.")
219
247
  ws_root = os.path.realpath(".")
220
248
  tmp_root = os.path.realpath(tempfile.gettempdir())
221
- real_target = os.path.normpath(os.path.realpath(os.path.abspath(target_path)))
222
- if not real_target.startswith(ws_root + os.sep) and not real_target.startswith(tmp_root + os.sep):
249
+ resolved = os.path.realpath(os.path.abspath(target_path))
250
+ base_root = tmp_root if (resolved == tmp_root or resolved.startswith(tmp_root + os.sep)) else ws_root
251
+ rel = os.path.relpath(resolved, base_root)
252
+ if rel == ".." or rel.startswith(".." + os.sep) or os.path.isabs(rel):
253
+ raise ValueError(f"Path outside allowed workspace or temp scope: {target_path}")
254
+ real_target = os.path.normpath(os.path.join(base_root, rel))
255
+ if not real_target.startswith(base_root):
223
256
  raise ValueError(f"Path outside allowed workspace or temp scope: {target_path}")
224
257
  return real_target
225
258
 
@@ -233,7 +266,16 @@ class ASTMutationEngine:
233
266
  ) -> MutationReport:
234
267
  """Executes full mutation testing on target_file against test_command."""
235
268
  start_time = time.time()
236
- abs_target = cls._sanitize_target_path(target_file)
269
+ ws_root = os.path.realpath(".")
270
+ tmp_root = os.path.realpath(tempfile.gettempdir())
271
+ resolved_t = os.path.realpath(os.path.abspath(cls._sanitize_target_path(target_file)))
272
+ base_root = tmp_root if (resolved_t == tmp_root or resolved_t.startswith(tmp_root + os.sep)) else ws_root
273
+ rel_t = os.path.relpath(resolved_t, base_root)
274
+ if rel_t == ".." or rel_t.startswith(".." + os.sep) or os.path.isabs(rel_t):
275
+ raise ValueError(f"Target path outside allowed root: {target_file}")
276
+ abs_target = os.path.normpath(os.path.join(base_root, rel_t))
277
+ if not abs_target.startswith(base_root):
278
+ raise ValueError(f"Target path outside allowed root: {target_file}")
237
279
  if not os.path.isfile(abs_target):
238
280
  raise FileNotFoundError(f"Target file not found: {target_file}")
239
281
 
@@ -254,15 +296,33 @@ class ASTMutationEngine:
254
296
  mutants=[]
255
297
  )
256
298
 
257
- # Build argv safely without shell=True
299
+ target_dir = os.path.dirname(abs_target)
300
+ expected_test_name = f"test_{os.path.splitext(os.path.basename(abs_target))[0]}.py"
301
+
302
+ # Discover untainted test files from workspace root, validated target_dir, and tzero_* temp dirs
303
+ discover_roots = [ws_root]
304
+ if base_root == tmp_root and target_dir not in discover_roots:
305
+ discover_roots.append(target_dir)
306
+ try:
307
+ for d_entry in os.scandir(tmp_root):
308
+ if d_entry.is_dir() and d_entry.name.startswith("tzero_"):
309
+ entry_real = os.path.realpath(d_entry.path)
310
+ if entry_real not in discover_roots:
311
+ discover_roots.append(entry_real)
312
+ except OSError:
313
+ pass
314
+
315
+ # Build argv strictly from fixed flags and untainted on-disk entries without shell=True
258
316
  if not test_command:
259
- base_name = os.path.splitext(os.path.basename(abs_target))[0]
260
- candidate_a = os.path.join(os.path.dirname(abs_target), "tests", f"test_{base_name}.py")
261
- candidate_b = os.path.realpath(os.path.join(".", "tests", f"test_{base_name}.py"))
262
- if os.path.isfile(candidate_a):
263
- test_cmd_args = [sys.executable, "-m", "unittest", candidate_a]
264
- elif os.path.isfile(candidate_b):
265
- test_cmd_args = [sys.executable, "-m", "unittest", candidate_b]
317
+ ws_tests_map: Dict[str, str] = {}
318
+ ws_tests_root = os.path.join(ws_root, "tests")
319
+ if os.path.isdir(ws_tests_root):
320
+ for fn in os.listdir(ws_tests_root):
321
+ if fn.startswith("test_") and fn.endswith(".py"):
322
+ ws_tests_map[fn] = os.path.join(ws_tests_root, fn)
323
+ matched_test = ws_tests_map.get(expected_test_name)
324
+ if matched_test:
325
+ test_cmd_args = [sys.executable, "-m", "unittest", matched_test]
266
326
  else:
267
327
  test_cmd_args = [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-p", "test_*.py"]
268
328
  else:
@@ -277,20 +337,35 @@ class ASTMutationEngine:
277
337
  raise ValueError("Empty test_command.")
278
338
  bin_name = os.path.basename(parsed_args[0]).lower()
279
339
  if bin_name.startswith("python"):
280
- test_cmd_args = [sys.executable] + parsed_args[1:]
340
+ runner_prefix = [sys.executable]
281
341
  elif bin_name in ("pytest", "pytest.exe"):
282
- test_cmd_args = [sys.executable, "-m", "pytest"] + parsed_args[1:]
342
+ runner_prefix = [sys.executable, "-m", "pytest"]
283
343
  else:
284
344
  raise ValueError(f"Unsupported test runner executable: {parsed_args[0]}")
285
345
 
346
+ allowed_entries = cls._build_allowed_test_entries(discover_roots)
347
+ safe_tail: List[str] = []
348
+ for tok in parsed_args[1:]:
349
+ if tok in cls._ALLOWED_TEST_ARGS:
350
+ safe_tail.append(cls._ALLOWED_TEST_ARGS[tok])
351
+ else:
352
+ cand_primary = os.path.realpath(os.path.abspath(tok))
353
+ cand_rel = os.path.realpath(os.path.join(target_dir, tok))
354
+ matched_rel = allowed_entries.get(cand_primary) or allowed_entries.get(cand_rel)
355
+ if not matched_rel:
356
+ raise ValueError(f"Unsupported or missing test argument: {tok}")
357
+ safe_tail.append(matched_rel)
358
+ test_cmd_args = runner_prefix + safe_tail
359
+
286
360
  killed = 0
287
361
  survived = 0
288
362
  timeouts = 0
289
363
  errors = 0
290
364
 
291
- target_dir = os.path.dirname(abs_target)
292
365
  safe_bak_name = os.path.basename(abs_target) + ".tzero_mut_bak"
293
- backup_path = os.path.join(target_dir, safe_bak_name)
366
+ backup_path = os.path.normpath(os.path.join(target_dir, safe_bak_name))
367
+ if not backup_path.startswith(target_dir):
368
+ raise ValueError("Backup path escaped target directory.")
294
369
  with open(backup_path, "w", encoding="utf-8") as f:
295
370
  f.write(original_code)
296
371
 
@@ -301,6 +376,8 @@ class ASTMutationEngine:
301
376
  try:
302
377
  for m in mutants:
303
378
  # Write mutant to disk
379
+ if not abs_target.startswith(base_root):
380
+ raise ValueError("Target path escaped allowed root.")
304
381
  with open(abs_target, "w", encoding="utf-8") as f:
305
382
  f.write(m.mutated_code)
306
383
 
@@ -37,7 +37,7 @@ AUTHOR = "Toprak Ahmet Aydoğmuş"
37
37
  ORGANIZATION = "Siber Akademi"
38
38
  PYPI_PKG = "tzero-mcp"
39
39
  NPM_PKG = "tzero-mcp"
40
- CANONICAL_VERSION = "v12.2.1"
40
+ CANONICAL_VERSION = "v12.3.2"
41
41
 
42
42
 
43
43
  def get_current_version() -> str:
@@ -15,6 +15,7 @@ import re
15
15
  import socketserver
16
16
  import sys
17
17
  import threading
18
+ import time
18
19
  from typing import Any, Dict, Optional, Tuple
19
20
 
20
21
  logger = logging.getLogger("tzero.proxy")
@@ -84,16 +85,93 @@ class LiveContextPruner:
84
85
 
85
86
 
86
87
  class ContextProxyHandler(http.server.BaseHTTPRequestHandler):
87
- """HTTP handler that intercepts /v1/chat/completions."""
88
+ """HTTP handler that intercepts /v1/chat/completions with strict request bounds."""
89
+
90
+ MAX_BODY_BYTES = 2 * 1024 * 1024 # 2 MiB max JSON payload
91
+ MAX_REJECT_DRAIN_BYTES = 8 * 1024 * 1024 # Bound unread TCP drain on 413 to avoid Winsock RST
92
+ REQUEST_TIMEOUT = 10.0
93
+
94
+ def setup(self) -> None:
95
+ super().setup()
96
+ try:
97
+ self.connection.settimeout(self.REQUEST_TIMEOUT)
98
+ except Exception:
99
+ pass
88
100
 
89
101
  def log_message(self, format: str, *args: Any) -> None:
90
102
  pass # quiet
91
103
 
104
+ def _drain_rejected_body(self, content_length: int) -> None:
105
+ """Briefly drain bounded unread bytes so TCP close sends FIN instead of RST."""
106
+ to_drain = min(max(0, content_length), self.MAX_REJECT_DRAIN_BYTES)
107
+ if to_drain <= 0:
108
+ return
109
+ deadline = time.monotonic() + 0.5
110
+ try:
111
+ self.connection.settimeout(0.1)
112
+ remaining = to_drain
113
+ while remaining > 0 and time.monotonic() < deadline:
114
+ chunk = self.rfile.read1(min(remaining, 65536)) if hasattr(self.rfile, "read1") else self.rfile.read(min(remaining, 65536))
115
+ if not chunk:
116
+ break
117
+ remaining -= len(chunk)
118
+ except Exception:
119
+ pass
120
+
121
+ def _send_json_error(self, code: int, msg: str, drain_bytes: int = 0) -> None:
122
+ err_msg = json.dumps({"error": msg}).encode("utf-8")
123
+ self.close_connection = True
124
+ self.send_response(code)
125
+ self.send_header("Content-Type", "application/json")
126
+ self.send_header("Content-Length", str(len(err_msg)))
127
+ self.send_header("Connection", "close")
128
+ self.end_headers()
129
+ self.wfile.write(err_msg)
130
+ self.wfile.flush()
131
+ if drain_bytes > 0:
132
+ self._drain_rejected_body(drain_bytes)
133
+
92
134
  def do_POST(self) -> None:
93
- content_length = int(self.headers.get("Content-Length", 0))
94
- body = self.rfile.read(content_length).decode("utf-8", errors="replace")
135
+ sem = getattr(self.server, "concurrency_semaphore", None)
136
+ acquired = False
137
+ if sem is not None:
138
+ acquired = sem.acquire(blocking=False)
139
+ if not acquired:
140
+ self._send_json_error(503, "Too many concurrent requests")
141
+ return
95
142
 
96
143
  try:
144
+ raw_len = self.headers.get("Content-Length")
145
+ if raw_len is None:
146
+ self._send_json_error(411, "Content-Length header required")
147
+ return
148
+ try:
149
+ content_length = int(raw_len)
150
+ except ValueError:
151
+ self._send_json_error(400, "Invalid Content-Length header")
152
+ return
153
+ if content_length < 0:
154
+ self._send_json_error(400, "Negative Content-Length rejected")
155
+ return
156
+ if content_length > self.MAX_BODY_BYTES:
157
+ self._send_json_error(
158
+ 413,
159
+ f"Payload exceeds {self.MAX_BODY_BYTES} byte limit",
160
+ drain_bytes=content_length,
161
+ )
162
+ return
163
+
164
+ raw_bytes = bytearray()
165
+ remaining = content_length
166
+ while remaining > 0:
167
+ chunk = self.rfile.read(min(remaining, 65536))
168
+ if not chunk:
169
+ self._send_json_error(400, "Truncated request body")
170
+ return
171
+ raw_bytes.extend(chunk)
172
+ remaining -= len(chunk)
173
+
174
+ body = raw_bytes.decode("utf-8", errors="replace")
97
175
  data = json.loads(body)
98
176
  pruned_data, saved = LiveContextPruner.prune_payload(data)
99
177
  resp = {
@@ -110,18 +188,33 @@ class ContextProxyHandler(http.server.BaseHTTPRequestHandler):
110
188
  self.send_header("X-TZero-Saved-Tokens", str(saved))
111
189
  self.end_headers()
112
190
  self.wfile.write(resp_bytes)
191
+ except TimeoutError:
192
+ try:
193
+ self._send_json_error(408, "Request body read timed out")
194
+ except Exception:
195
+ pass
113
196
  except Exception as exc:
114
- err_msg = json.dumps({"error": str(exc)}).encode("utf-8")
115
- self.send_response(400)
116
- self.send_header("Content-Type", "application/json")
117
- self.send_header("Content-Length", str(len(err_msg)))
118
- self.end_headers()
119
- self.wfile.write(err_msg)
197
+ try:
198
+ self._send_json_error(400, str(exc))
199
+ except Exception:
200
+ pass
201
+ finally:
202
+ if sem is not None and acquired:
203
+ sem.release()
204
+
205
+
206
+ class _BoundedThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
207
+ daemon_threads = True
208
+ allow_reuse_address = True
209
+
210
+ def __init__(self, server_address: Tuple[str, int], handler_cls: Any, max_concurrent: int = 16):
211
+ self.concurrency_semaphore = threading.Semaphore(max(1, int(max_concurrent)))
212
+ super().__init__(server_address, handler_cls)
120
213
 
121
214
 
122
- def start_context_proxy(host: str = "127.0.0.1", port: int = 7350) -> socketserver.TCPServer:
123
- """Start local transparent context optimizer proxy."""
124
- server = socketserver.TCPServer((host, port), ContextProxyHandler)
215
+ def start_context_proxy(host: str = "127.0.0.1", port: int = 7350, max_concurrent: int = 16) -> socketserver.TCPServer:
216
+ """Start local transparent context optimizer proxy with timeout and concurrency limits."""
217
+ server = _BoundedThreadingHTTPServer((host, port), ContextProxyHandler, max_concurrent=max_concurrent)
125
218
  server_thread = threading.Thread(target=server.serve_forever, daemon=True)
126
219
  server_thread.start()
127
220
  return server
@@ -344,12 +344,18 @@ class ScipIndexImporter:
344
344
  ws_root = os.path.realpath(".")
345
345
  tmp_root = os.path.realpath(tempfile.gettempdir())
346
346
  home_root = os.path.realpath(os.path.expanduser("~"))
347
- real_path = os.path.normpath(os.path.realpath(os.path.abspath(path)))
348
- if (
349
- not real_path.startswith(ws_root + os.sep)
350
- and not real_path.startswith(tmp_root + os.sep)
351
- and not real_path.startswith(home_root + os.sep)
352
- ):
347
+ cand_path = os.path.realpath(os.path.abspath(path))
348
+ if cand_path == tmp_root or cand_path.startswith(tmp_root + os.sep):
349
+ base_root = tmp_root
350
+ elif cand_path == home_root or cand_path.startswith(home_root + os.sep):
351
+ base_root = home_root
352
+ else:
353
+ base_root = ws_root
354
+ rel_path = os.path.relpath(cand_path, base_root)
355
+ if rel_path == ".." or rel_path.startswith(".." + os.sep) or os.path.isabs(rel_path):
356
+ raise ValueError(f"SCIP/LSIF path outside allowed scope: {path}")
357
+ real_path = os.path.normpath(os.path.join(base_root, rel_path))
358
+ if not real_path.startswith(base_root):
353
359
  raise ValueError(f"SCIP/LSIF path outside allowed scope: {path}")
354
360
  if not os.path.isfile(real_path):
355
361
  raise FileNotFoundError(f"SCIP/LSIF index file not found: {path}")