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.
- package/README.md +6 -30
- package/bin/tzero-mcp.js +2 -2
- package/bin/tzero.js +11 -6
- package/package.json +1 -2
- package/src/addmcp.py +10 -5
- package/src/app.py +3 -9
- package/src/tzero/__init__.py +1 -1
- package/src/tzero/anti_rea/__init__.py +16 -2
- package/src/tzero/anti_rea/algebraic_mutator.py +65 -44
- package/src/tzero/anti_rea/anti_debugger.py +51 -18
- package/src/tzero/anti_rea/asar_shield.py +24 -1
- package/src/tzero/anti_rea/auditor.py +62 -12
- package/src/tzero/anti_rea/canary_beacon.py +56 -76
- package/src/tzero/anti_rea/cli.py +37 -5
- package/src/tzero/anti_rea/confusables.py +62 -18
- package/src/tzero/anti_rea/crypto_loader.py +132 -0
- package/src/tzero/anti_rea/engine.py +129 -29
- package/src/tzero/anti_rea/extractor_shield.py +91 -13
- package/src/tzero/anti_rea/gui.py +1 -4
- package/src/tzero/anti_rea/integrity_guard.py +17 -5
- package/src/tzero/anti_rea/rdtsc_guard.py +21 -8
- package/src/tzero/anti_rea/string_vault.py +10 -7
- package/src/tzero/anti_rea/tier_catalog.py +388 -0
- package/src/tzero/siber_akademi.ico +0 -0
- package/src/tzero/siber_akademi_icon.py +14 -8
- package/src/tzero/tzero_armor.py +29 -7
- package/src/tzero/tzero_benchmark.py +4 -2
- package/src/tzero/tzero_budget.py +14 -5
- package/src/tzero/tzero_ci.py +2 -2
- package/src/tzero/tzero_contracts.py +7 -5
- package/src/tzero/tzero_dashboard.py +28 -9
- package/src/tzero/tzero_debt.py +19 -4
- package/src/tzero/tzero_deps.py +109 -87
- package/src/tzero/tzero_explain.py +1 -1
- package/src/tzero/tzero_features.py +43 -29
- package/src/tzero/tzero_federation.py +9 -2
- package/src/tzero/tzero_fixer/mcp_server.py +10 -0
- package/src/tzero/tzero_golden.py +37 -9
- package/src/tzero/tzero_growth.py +166 -8
- package/src/tzero/tzero_guard.py +147 -46
- package/src/tzero/tzero_jarvis/workspace_orchestrator.py +1 -1
- package/src/tzero/tzero_jarvis/zero_key_router.py +10 -78
- package/src/tzero/tzero_lsp.py +1 -1
- package/src/tzero/tzero_mcp.py +71 -23
- package/src/tzero/tzero_mutation.py +92 -15
- package/src/tzero/tzero_promo.py +1 -1
- package/src/tzero/tzero_proxy.py +105 -12
- package/src/tzero/tzero_scip.py +12 -6
- package/src/tzero/tzero_security.py +404 -60
- package/src/tzero/tzero_task_benchmark.py +2 -2
- package/src/tzero/tzero_traffic.py +35 -10
- package/src/tzero/tzero_tui.py +20 -11
- package/src/tzero/tzero_v3.py +304 -153
- package/src/tzero/tzero_welcome.py +12 -4
- package/bin/postinstall.js +0 -30
|
@@ -208,8 +208,8 @@ SECRET_RULES: List[SecretRule] = [
|
|
|
208
208
|
SecretRule(
|
|
209
209
|
rule_id="SEC-CRYPTO-001",
|
|
210
210
|
provider="PKI",
|
|
211
|
-
description="Private Key Header (RSA, EC, OPENSSH, DSA, PGP)",
|
|
212
|
-
pattern=re.compile(r"-----BEGIN (?:
|
|
211
|
+
description="Private Key Block or Header (RSA, EC, OPENSSH, DSA, PGP)",
|
|
212
|
+
pattern=re.compile(r"-----BEGIN (?:[A-Z0-9 ]{1,32} )?PRIVATE KEY-----"),
|
|
213
213
|
mask_tag="[ZERO_LEAK_MASKED_PRIVATE_KEY]"
|
|
214
214
|
),
|
|
215
215
|
SecretRule(
|
|
@@ -265,6 +265,38 @@ class ZeroLeakEngine:
|
|
|
265
265
|
|
|
266
266
|
MIN_ENTROPY_THRESHOLD: float = 4.75
|
|
267
267
|
MIN_ENTROPY_LENGTH: int = 28
|
|
268
|
+
_PEM_BEGIN_RE = re.compile(r"-----BEGIN (?:[A-Z0-9 ]{1,32} )?PRIVATE KEY-----")
|
|
269
|
+
_PEM_END_RE = re.compile(r"-----END (?:[A-Z0-9 ]{1,32} )?PRIVATE KEY-----")
|
|
270
|
+
|
|
271
|
+
@classmethod
|
|
272
|
+
def _iter_pem_block_spans(cls, text: str) -> List[Tuple[int, int]]:
|
|
273
|
+
"""Linearly locates complete PEM BEGIN..END block byte spans without polynomial regex backtracking."""
|
|
274
|
+
spans: List[Tuple[int, int]] = []
|
|
275
|
+
pos = 0
|
|
276
|
+
for begin_match in cls._PEM_BEGIN_RE.finditer(text):
|
|
277
|
+
if begin_match.start() < pos:
|
|
278
|
+
continue
|
|
279
|
+
end_match = cls._PEM_END_RE.search(text, begin_match.end())
|
|
280
|
+
if not end_match:
|
|
281
|
+
break
|
|
282
|
+
spans.append((begin_match.start(), end_match.end()))
|
|
283
|
+
pos = end_match.end()
|
|
284
|
+
return spans
|
|
285
|
+
|
|
286
|
+
@classmethod
|
|
287
|
+
def _mask_pem_blocks(cls, text: str, replacement: str = "[ZERO_LEAK_MASKED_PRIVATE_KEY]") -> str:
|
|
288
|
+
"""Replaces complete PEM BEGIN..END blocks linearly cleanly."""
|
|
289
|
+
spans = cls._iter_pem_block_spans(text)
|
|
290
|
+
if not spans:
|
|
291
|
+
return text
|
|
292
|
+
chunks: List[str] = []
|
|
293
|
+
last = 0
|
|
294
|
+
for s, e in spans:
|
|
295
|
+
chunks.append(text[last:s])
|
|
296
|
+
chunks.append(replacement)
|
|
297
|
+
last = e
|
|
298
|
+
chunks.append(text[last:])
|
|
299
|
+
return "".join(chunks)
|
|
268
300
|
|
|
269
301
|
@classmethod
|
|
270
302
|
def is_placeholder(cls, s: str) -> bool:
|
|
@@ -291,28 +323,71 @@ class ZeroLeakEngine:
|
|
|
291
323
|
|
|
292
324
|
@classmethod
|
|
293
325
|
def scan_text(cls, text: str, check_entropy: bool = True) -> List[SecretFinding]:
|
|
294
|
-
"""Scans in-memory text
|
|
326
|
+
"""Scans in-memory text (including comments and multiline PEM blocks) for secrets."""
|
|
295
327
|
if not text:
|
|
296
328
|
return []
|
|
297
329
|
|
|
298
330
|
findings: List[SecretFinding] = []
|
|
299
331
|
lines = text.splitlines()
|
|
300
332
|
|
|
333
|
+
# Pre-compute line numbers covered by complete multi-line PEM blocks
|
|
334
|
+
pem_ranges: List[Tuple[int, int]] = []
|
|
335
|
+
for s_pos, e_pos in cls._iter_pem_block_spans(text):
|
|
336
|
+
block_txt = text[s_pos:e_pos]
|
|
337
|
+
start_line = text[:s_pos].count("\n") + 1
|
|
338
|
+
end_line = text[:e_pos].count("\n") + 1
|
|
339
|
+
pem_ranges.append((start_line, end_line))
|
|
340
|
+
findings.append(SecretFinding(
|
|
341
|
+
rule_id="SEC-CRYPTO-001",
|
|
342
|
+
provider="PKI",
|
|
343
|
+
description="Private Key Block (PEM)",
|
|
344
|
+
severity="CRITICAL",
|
|
345
|
+
line_no=start_line,
|
|
346
|
+
preview="[ZERO_LEAK_MASKED_PRIVATE_KEY]",
|
|
347
|
+
entropy=round(calculate_shannon_entropy(block_txt), 2),
|
|
348
|
+
is_entropy_anomaly=False,
|
|
349
|
+
secret_value=block_txt,
|
|
350
|
+
))
|
|
351
|
+
|
|
352
|
+
def _in_pem_block(ln: int) -> bool:
|
|
353
|
+
return any(s <= ln <= e for s, e in pem_ranges)
|
|
354
|
+
|
|
301
355
|
for lineno, line in enumerate(lines, 1):
|
|
302
356
|
stripped = line.strip()
|
|
303
|
-
if not stripped or
|
|
357
|
+
if not stripped or _in_pem_block(lineno):
|
|
304
358
|
continue
|
|
305
359
|
|
|
306
|
-
# 1. Signature Rule Matching
|
|
360
|
+
# 1. Signature Rule Matching (scans code AND comment lines alike)
|
|
307
361
|
has_specific_provider_match = False
|
|
308
362
|
for rule in SECRET_RULES:
|
|
363
|
+
if rule.rule_id == "SEC-CRYPTO-001":
|
|
364
|
+
if cls._PEM_BEGIN_RE.search(line):
|
|
365
|
+
val = cls._PEM_BEGIN_RE.search(line).group(0)
|
|
366
|
+
findings.append(SecretFinding(
|
|
367
|
+
rule_id=rule.rule_id,
|
|
368
|
+
provider=rule.provider,
|
|
369
|
+
description=rule.description,
|
|
370
|
+
severity=rule.severity,
|
|
371
|
+
line_no=lineno,
|
|
372
|
+
preview=cls.mask_preview(line),
|
|
373
|
+
entropy=round(calculate_shannon_entropy(val), 2),
|
|
374
|
+
is_entropy_anomaly=False,
|
|
375
|
+
secret_value=val,
|
|
376
|
+
))
|
|
377
|
+
has_specific_provider_match = True
|
|
378
|
+
continue
|
|
379
|
+
|
|
309
380
|
# If a specific provider rule matched, avoid duplicate generic rule hit on same line
|
|
310
381
|
if rule.rule_id == "SEC-GENERIC-001" and has_specific_provider_match:
|
|
311
382
|
continue
|
|
312
383
|
|
|
313
384
|
for match in rule.pattern.finditer(line):
|
|
314
|
-
|
|
315
|
-
if
|
|
385
|
+
# Preserve capture group 1 for generic/Bearer assignment rules so LHS variable stays intact
|
|
386
|
+
if rule.rule_id in ("SEC-GENERIC-001", "SEC-AUTH-002") and match.lastindex and match.lastindex >= 1:
|
|
387
|
+
val = match.group(1)
|
|
388
|
+
else:
|
|
389
|
+
val = match.group(0)
|
|
390
|
+
if cls.is_placeholder(val) or cls.is_placeholder(match.group(0)):
|
|
316
391
|
continue
|
|
317
392
|
|
|
318
393
|
ent = calculate_shannon_entropy(val)
|
|
@@ -325,13 +400,13 @@ class ZeroLeakEngine:
|
|
|
325
400
|
preview=cls.mask_preview(line),
|
|
326
401
|
entropy=round(ent, 2),
|
|
327
402
|
is_entropy_anomaly=False,
|
|
328
|
-
secret_value=val
|
|
403
|
+
secret_value=val,
|
|
329
404
|
))
|
|
330
405
|
if rule.provider != "Generic":
|
|
331
406
|
has_specific_provider_match = True
|
|
332
407
|
|
|
333
408
|
# 2. Shannon Entropy Scanner for Unmatched Candidate Tokens
|
|
334
|
-
if check_entropy:
|
|
409
|
+
if check_entropy and not stripped.startswith(("#", "//", "*", "/*")):
|
|
335
410
|
# Candidate secrets must be single compact tokens without whitespace, slashes, or URL schemas
|
|
336
411
|
candidate_tokens = re.findall(r"""['"]([A-Za-z0-9+/=_\-]{28,})['"]""", line)
|
|
337
412
|
for tok in candidate_tokens:
|
|
@@ -347,7 +422,7 @@ class ZeroLeakEngine:
|
|
|
347
422
|
continue
|
|
348
423
|
if cls.is_natural_or_identifier(tok):
|
|
349
424
|
continue
|
|
350
|
-
|
|
425
|
+
|
|
351
426
|
ent = calculate_shannon_entropy(tok)
|
|
352
427
|
if ent >= cls.MIN_ENTROPY_THRESHOLD and len(tok) >= cls.MIN_ENTROPY_LENGTH:
|
|
353
428
|
already_reported = any(f.line_no == lineno for f in findings)
|
|
@@ -361,7 +436,7 @@ class ZeroLeakEngine:
|
|
|
361
436
|
preview=cls.mask_preview(line),
|
|
362
437
|
entropy=round(ent, 2),
|
|
363
438
|
is_entropy_anomaly=True,
|
|
364
|
-
secret_value=tok
|
|
439
|
+
secret_value=tok,
|
|
365
440
|
))
|
|
366
441
|
|
|
367
442
|
return findings
|
|
@@ -369,21 +444,31 @@ class ZeroLeakEngine:
|
|
|
369
444
|
@classmethod
|
|
370
445
|
def mask_preview(cls, line: str, max_len: int = 70) -> str:
|
|
371
446
|
"""Sanitizes line for safe terminal output and logging."""
|
|
372
|
-
sanitized = cls.sanitize_text(line)
|
|
447
|
+
sanitized = cls.sanitize_text(line, allow_incomplete_pem=True)
|
|
373
448
|
if len(sanitized) > max_len:
|
|
374
449
|
return sanitized[:max_len] + "..."
|
|
375
450
|
return sanitized
|
|
376
451
|
|
|
377
452
|
@classmethod
|
|
378
|
-
def sanitize_text(cls, text: str) -> str:
|
|
453
|
+
def sanitize_text(cls, text: str, allow_incomplete_pem: bool = False) -> str:
|
|
379
454
|
"""Sanitizes text by masking all detected secrets with Zero-Leak tokens."""
|
|
380
455
|
if not text:
|
|
381
456
|
return ""
|
|
382
457
|
|
|
383
|
-
sanitized = text
|
|
458
|
+
sanitized = cls._mask_pem_blocks(text, "[ZERO_LEAK_MASKED_PRIVATE_KEY]")
|
|
459
|
+
|
|
460
|
+
if cls._PEM_BEGIN_RE.search(sanitized):
|
|
461
|
+
if not allow_incomplete_pem:
|
|
462
|
+
raise ValueError(
|
|
463
|
+
"Incomplete PEM private key block detected without END delimiter; aborting redaction to prevent body leak."
|
|
464
|
+
)
|
|
465
|
+
sanitized = cls._PEM_BEGIN_RE.sub("[ZERO_LEAK_MASKED_PRIVATE_KEY]", sanitized)
|
|
384
466
|
|
|
385
467
|
# 1. Mask specific patterns
|
|
386
468
|
for rule in SECRET_RULES:
|
|
469
|
+
if rule.rule_id == "SEC-CRYPTO-001":
|
|
470
|
+
continue
|
|
471
|
+
|
|
387
472
|
def _replace_match(m):
|
|
388
473
|
full_val = m.group(0)
|
|
389
474
|
if cls.is_placeholder(full_val):
|
|
@@ -401,15 +486,41 @@ class ZeroLeakEngine:
|
|
|
401
486
|
sanitized = re.sub(r"""['"]([^'"]{20,})['"]""", _replace_entropy, sanitized)
|
|
402
487
|
return sanitized
|
|
403
488
|
|
|
489
|
+
@classmethod
|
|
490
|
+
def _sanitize_string_value(cls, val: str, allow_incomplete_pem: bool = False) -> str:
|
|
491
|
+
"""Sanitize an extracted string value even when unquoted inside an AST literal."""
|
|
492
|
+
cleaned = cls.sanitize_text(val, allow_incomplete_pem=allow_incomplete_pem)
|
|
493
|
+
if cleaned != val:
|
|
494
|
+
return cleaned
|
|
495
|
+
# Strip unquoted high-entropy raw tokens inside AST constants if scan_text flags them
|
|
496
|
+
stripped = val.strip()
|
|
497
|
+
if cls.scan_text(f'val = "{stripped}"'):
|
|
498
|
+
if len(stripped) >= cls.MIN_ENTROPY_LENGTH and calculate_shannon_entropy(stripped) >= 4.4 and not cls.is_placeholder(stripped):
|
|
499
|
+
return f"{stripped[:4]}...[ZERO_LEAK_HIGH_ENTROPY_SECRET]"
|
|
500
|
+
if len(stripped) >= 12 and not cls.is_placeholder(stripped):
|
|
501
|
+
return "[ZERO_LEAK_MASKED_VALUE]"
|
|
502
|
+
return cleaned
|
|
503
|
+
|
|
404
504
|
@classmethod
|
|
405
505
|
def sanitize_ast(cls, tree: ast.AST) -> ast.AST:
|
|
406
506
|
"""Walks an AST tree and replaces hardcoded string literals containing secrets."""
|
|
407
507
|
for node in ast.walk(tree):
|
|
408
508
|
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
509
|
+
node.value = cls._sanitize_string_value(node.value)
|
|
510
|
+
ast.fix_missing_locations(tree)
|
|
511
|
+
# Re-verify unparsed code so no AST literal secret survives
|
|
512
|
+
try:
|
|
513
|
+
rendered = ast.unparse(tree)
|
|
514
|
+
remaining = cls.scan_text(rendered)
|
|
515
|
+
if remaining:
|
|
516
|
+
secret_vals = {f.secret_value for f in remaining if f.secret_value}
|
|
517
|
+
for node in ast.walk(tree):
|
|
518
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
519
|
+
for sv in secret_vals:
|
|
520
|
+
if sv and sv in node.value:
|
|
521
|
+
node.value = node.value.replace(sv, "[ZERO_LEAK_MASKED_VALUE]")
|
|
522
|
+
except Exception:
|
|
523
|
+
pass
|
|
413
524
|
return tree
|
|
414
525
|
|
|
415
526
|
@classmethod
|
|
@@ -461,26 +572,97 @@ class ZeroLeakEngine:
|
|
|
461
572
|
pass
|
|
462
573
|
return cls.scan_files_map(files_map)
|
|
463
574
|
|
|
575
|
+
@classmethod
|
|
576
|
+
def resolve_project_root(cls, target_path: str) -> str:
|
|
577
|
+
"""Resolve nearest project root (.git ancestor) or target directory consistently."""
|
|
578
|
+
abs_p = os.path.abspath(target_path)
|
|
579
|
+
start = abs_p if os.path.isdir(abs_p) else os.path.dirname(abs_p)
|
|
580
|
+
curr = start
|
|
581
|
+
while True:
|
|
582
|
+
if os.path.isdir(os.path.join(curr, ".git")):
|
|
583
|
+
return curr
|
|
584
|
+
parent = os.path.dirname(curr)
|
|
585
|
+
if parent == curr:
|
|
586
|
+
return start
|
|
587
|
+
curr = parent
|
|
588
|
+
|
|
589
|
+
@classmethod
|
|
590
|
+
def check_env_git_status(
|
|
591
|
+
cls, env_file_path: str, gitignore_path: Optional[str] = None
|
|
592
|
+
) -> Dict[str, Any]:
|
|
593
|
+
"""Use Git check-ignore/ls-files when available (fallback to real rule parsing)."""
|
|
594
|
+
import subprocess
|
|
595
|
+
abs_env = os.path.abspath(env_file_path)
|
|
596
|
+
proj_root = cls.resolve_project_root(abs_env)
|
|
597
|
+
env_name = os.path.basename(abs_env)
|
|
598
|
+
in_git = os.path.isdir(os.path.join(proj_root, ".git"))
|
|
599
|
+
tracked = False
|
|
600
|
+
ignored = False
|
|
601
|
+
|
|
602
|
+
if in_git:
|
|
603
|
+
rel_env = os.path.relpath(abs_env, proj_root).replace("\\", "/")
|
|
604
|
+
tr = subprocess.run(
|
|
605
|
+
["git", "-C", proj_root, "ls-files", "--error-unmatch", rel_env],
|
|
606
|
+
capture_output=True, text=True, check=False,
|
|
607
|
+
)
|
|
608
|
+
tracked = tr.returncode == 0
|
|
609
|
+
ig = subprocess.run(
|
|
610
|
+
["git", "-C", proj_root, "check-ignore", "-q", abs_env],
|
|
611
|
+
capture_output=True, text=True, check=False,
|
|
612
|
+
)
|
|
613
|
+
ignored = ig.returncode == 0
|
|
614
|
+
elif gitignore_path and os.path.isfile(gitignore_path):
|
|
615
|
+
with open(gitignore_path, "r", encoding="utf-8", errors="ignore") as gf:
|
|
616
|
+
for raw_line in gf:
|
|
617
|
+
rule = raw_line.strip()
|
|
618
|
+
if not rule or rule.startswith("#") or rule.startswith("!"):
|
|
619
|
+
continue
|
|
620
|
+
norm = rule.lstrip("/")
|
|
621
|
+
if norm in (env_name, "*.env") or (norm == ".env" and env_name == ".env"):
|
|
622
|
+
ignored = True
|
|
623
|
+
break
|
|
624
|
+
return {
|
|
625
|
+
"in_git": in_git,
|
|
626
|
+
"tracked": tracked,
|
|
627
|
+
"ignored": ignored,
|
|
628
|
+
"warning": f"WARNING: {abs_env} is already tracked by Git! Run `git rm --cached {env_name}`." if tracked else "",
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
@classmethod
|
|
632
|
+
def _load_existing_env(cls, env_file_path: Optional[str]) -> Dict[str, str]:
|
|
633
|
+
env_map: Dict[str, str] = {}
|
|
634
|
+
if env_file_path and os.path.isfile(env_file_path):
|
|
635
|
+
with open(env_file_path, "r", encoding="utf-8", errors="replace") as ef:
|
|
636
|
+
for raw in ef:
|
|
637
|
+
line = raw.strip()
|
|
638
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
639
|
+
continue
|
|
640
|
+
k, _, v = line.partition("=")
|
|
641
|
+
k = k.strip()
|
|
642
|
+
if k:
|
|
643
|
+
env_map[k] = v.strip()
|
|
644
|
+
return env_map
|
|
645
|
+
|
|
464
646
|
@classmethod
|
|
465
647
|
def auto_migrate_to_env(
|
|
466
648
|
cls,
|
|
467
649
|
code_str: str,
|
|
468
650
|
env_file_path: Optional[str] = None,
|
|
469
|
-
gitignore_path: Optional[str] = None
|
|
651
|
+
gitignore_path: Optional[str] = None,
|
|
652
|
+
shared_env_registry: Optional[Dict[str, str]] = None,
|
|
653
|
+
dry_run: bool = False,
|
|
470
654
|
) -> Tuple[str, str, int, str]:
|
|
471
|
-
"""
|
|
655
|
+
"""Extract hardcoded secrets to .env atomically without variable collisions or partial writes."""
|
|
472
656
|
findings = cls.scan_text(code_str)
|
|
473
657
|
valid_findings = [f for f in findings if f.secret_value and not cls.is_placeholder(f.secret_value)]
|
|
474
|
-
|
|
658
|
+
|
|
475
659
|
if not valid_findings:
|
|
476
660
|
return code_str, "# No secrets detected.", 0, "### 100% Zero-Leak Certified\nNo hardcoded credentials found in source code."
|
|
477
661
|
|
|
478
662
|
migrated_code = code_str
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
counter = 1
|
|
663
|
+
env_registry: Dict[str, str] = shared_env_registry if shared_env_registry is not None else cls._load_existing_env(env_file_path)
|
|
664
|
+
new_env_entries: Dict[str, str] = {}
|
|
482
665
|
|
|
483
|
-
# Sort findings descending by length to avoid partial substrings
|
|
484
666
|
unique_findings = []
|
|
485
667
|
seen_vals = set()
|
|
486
668
|
for f in valid_findings:
|
|
@@ -502,6 +684,7 @@ class ZeroLeakEngine:
|
|
|
502
684
|
"Slack": "SLACK_BOT_TOKEN",
|
|
503
685
|
"Database": "DATABASE_URL",
|
|
504
686
|
"JWT": "JWT_SECRET_TOKEN",
|
|
687
|
+
"PKI": "PRIVATE_KEY_PEM",
|
|
505
688
|
"PrivateKey": "PRIVATE_KEY_PEM",
|
|
506
689
|
}
|
|
507
690
|
|
|
@@ -512,23 +695,30 @@ class ZeroLeakEngine:
|
|
|
512
695
|
"| :--- | :--- | :--- |",
|
|
513
696
|
]
|
|
514
697
|
|
|
698
|
+
# Build reverse map secret_value -> existing env var for idempotent reuse
|
|
699
|
+
val_to_var = {v: k for k, v in env_registry.items()}
|
|
700
|
+
|
|
515
701
|
for f in unique_findings:
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
base_var = f"
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
702
|
+
if f.secret_value in val_to_var:
|
|
703
|
+
var_name = val_to_var[f.secret_value]
|
|
704
|
+
else:
|
|
705
|
+
base_var = provider_map.get(f.provider, "")
|
|
706
|
+
if not base_var:
|
|
707
|
+
clean_desc = re.sub(r"[^A-Z0-9_]", "_", f.description.upper()[:20]).strip("_")
|
|
708
|
+
base_var = f"{clean_desc or 'APP'}_SECRET"
|
|
709
|
+
|
|
710
|
+
var_name = base_var
|
|
711
|
+
idx = 2
|
|
712
|
+
while var_name in env_registry:
|
|
713
|
+
var_name = f"{base_var}_{idx}"
|
|
714
|
+
idx += 1
|
|
715
|
+
env_registry[var_name] = f.secret_value
|
|
716
|
+
val_to_var[f.secret_value] = var_name
|
|
717
|
+
new_env_entries[var_name] = f.secret_value
|
|
718
|
+
|
|
528
719
|
redacted = f.secret_value[:6] + "..." + f.secret_value[-4:] if len(f.secret_value) > 12 else "***"
|
|
529
720
|
report_lines.append(f"| `{f.provider}` | `{var_name}` | `{redacted}` |")
|
|
530
721
|
|
|
531
|
-
# Replace quotes in code
|
|
532
722
|
pat_d = f'"{f.secret_value}"'
|
|
533
723
|
pat_s = f"'{f.secret_value}'"
|
|
534
724
|
replacement = f'os.environ.get("{var_name}", "")'
|
|
@@ -537,37 +727,191 @@ class ZeroLeakEngine:
|
|
|
537
727
|
elif pat_s in migrated_code:
|
|
538
728
|
migrated_code = migrated_code.replace(pat_s, replacement)
|
|
539
729
|
else:
|
|
540
|
-
|
|
730
|
+
# Preserve surrounding quotes/assignment cleanly if matched inside a quoted value
|
|
731
|
+
escaped_v = re.escape(f.secret_value)
|
|
732
|
+
if re.search(rf"""(['"]){escaped_v}\1""", migrated_code):
|
|
733
|
+
migrated_code = re.sub(rf"""(['"]){escaped_v}\1""", replacement, migrated_code)
|
|
734
|
+
else:
|
|
735
|
+
migrated_code = migrated_code.replace(f.secret_value, replacement)
|
|
541
736
|
|
|
542
|
-
# Check if os is imported
|
|
543
737
|
if "os.environ" in migrated_code and "import os" not in migrated_code and "from os import" not in migrated_code:
|
|
544
|
-
|
|
738
|
+
lines_m = migrated_code.splitlines(keepends=True)
|
|
739
|
+
ins_idx = 0
|
|
740
|
+
for idx_l, ln_txt in enumerate(lines_m):
|
|
741
|
+
s_ln = ln_txt.strip()
|
|
742
|
+
if idx_l == 0 and s_ln.startswith("#!"):
|
|
743
|
+
ins_idx = idx_l + 1
|
|
744
|
+
elif s_ln.startswith("# -*-") or s_ln.startswith("# coding"):
|
|
745
|
+
ins_idx = idx_l + 1
|
|
746
|
+
elif s_ln.startswith("from __future__ import"):
|
|
747
|
+
ins_idx = idx_l + 1
|
|
748
|
+
elif s_ln and not s_ln.startswith("#"):
|
|
749
|
+
break
|
|
750
|
+
lines_m.insert(ins_idx, "import os\n")
|
|
751
|
+
migrated_code = "".join(lines_m)
|
|
545
752
|
|
|
546
|
-
# Build .env text
|
|
547
753
|
env_lines = ["# Auto-Vault Generated by T-Zero Zero-Leak Engine", "# DO NOT COMMIT THIS FILE TO PUBLIC REPOSITORIES", ""]
|
|
548
|
-
for k, v in
|
|
754
|
+
for k, v in env_registry.items():
|
|
549
755
|
env_lines.append(f"{k}={v}")
|
|
550
756
|
env_content = "\n".join(env_lines) + "\n"
|
|
551
757
|
|
|
552
|
-
#
|
|
553
|
-
if env_file_path:
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
except Exception:
|
|
558
|
-
pass
|
|
758
|
+
# Stage & commit physical .gitignore and .env atomically BEFORE returning success
|
|
759
|
+
if not dry_run and (env_file_path or gitignore_path):
|
|
760
|
+
import tempfile
|
|
761
|
+
if env_file_path and gitignore_path is None:
|
|
762
|
+
gitignore_path = os.path.join(os.path.dirname(os.path.abspath(env_file_path)), ".gitignore")
|
|
559
763
|
|
|
560
|
-
|
|
764
|
+
gi_staged = None
|
|
765
|
+
env_staged = None
|
|
561
766
|
try:
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
767
|
+
if gitignore_path and env_file_path:
|
|
768
|
+
git_status = cls.check_env_git_status(env_file_path, gitignore_path)
|
|
769
|
+
if git_status.get("warning"):
|
|
770
|
+
report_lines.append(f"\n> {git_status['warning']}")
|
|
771
|
+
if not git_status.get("ignored"):
|
|
772
|
+
existing_gi = ""
|
|
773
|
+
if os.path.isfile(gitignore_path):
|
|
774
|
+
with open(gitignore_path, "r", encoding="utf-8") as gf:
|
|
775
|
+
existing_gi = gf.read()
|
|
776
|
+
env_base = os.path.basename(os.path.abspath(env_file_path))
|
|
777
|
+
sep = "\n" if existing_gi and not existing_gi.endswith("\n") else ""
|
|
778
|
+
new_gi = f"{existing_gi}{sep}{env_base}\n"
|
|
779
|
+
gi_dir = os.path.dirname(os.path.abspath(gitignore_path)) or "."
|
|
780
|
+
os.makedirs(gi_dir, exist_ok=True)
|
|
781
|
+
with tempfile.NamedTemporaryFile("w", dir=gi_dir, delete=False, encoding="utf-8", prefix=".tzero_gi_") as tf:
|
|
782
|
+
tf.write(new_gi)
|
|
783
|
+
gi_staged = tf.name
|
|
784
|
+
|
|
785
|
+
if env_file_path:
|
|
786
|
+
env_dir = os.path.dirname(os.path.abspath(env_file_path)) or "."
|
|
787
|
+
os.makedirs(env_dir, exist_ok=True)
|
|
788
|
+
with tempfile.NamedTemporaryFile("w", dir=env_dir, delete=False, encoding="utf-8", prefix=".tzero_env_") as tf:
|
|
789
|
+
tf.write(env_content)
|
|
790
|
+
env_staged = tf.name
|
|
791
|
+
|
|
792
|
+
if gi_staged:
|
|
793
|
+
os.replace(gi_staged, gitignore_path)
|
|
794
|
+
gi_staged = None
|
|
795
|
+
if env_staged:
|
|
796
|
+
os.replace(env_staged, env_file_path)
|
|
797
|
+
env_staged = None
|
|
798
|
+
except Exception as exc:
|
|
799
|
+
for p in (gi_staged, env_staged):
|
|
800
|
+
if p and os.path.exists(p):
|
|
801
|
+
try:
|
|
802
|
+
os.remove(p)
|
|
803
|
+
except OSError:
|
|
804
|
+
pass
|
|
805
|
+
raise RuntimeError(f"Auto-Vault failed to persist environment/gitignore safely: {exc}") from exc
|
|
571
806
|
|
|
572
807
|
return migrated_code, env_content, len(unique_findings), "\n".join(report_lines)
|
|
573
808
|
|
|
809
|
+
@classmethod
|
|
810
|
+
def migrate_files_atomically(
|
|
811
|
+
cls,
|
|
812
|
+
file_paths: List[str],
|
|
813
|
+
env_file_path: str,
|
|
814
|
+
gitignore_path: Optional[str] = None,
|
|
815
|
+
) -> Dict[str, Any]:
|
|
816
|
+
"""Atomically migrate multiple files using a shared env table with rollback on write errors."""
|
|
817
|
+
import tempfile
|
|
818
|
+
abs_env = os.path.abspath(env_file_path)
|
|
819
|
+
abs_gi = os.path.abspath(gitignore_path) if gitignore_path else os.path.join(os.path.dirname(abs_env), ".gitignore")
|
|
820
|
+
orig_sources: Dict[str, str] = {}
|
|
821
|
+
staged_sources: Dict[str, str] = {}
|
|
822
|
+
orig_env = None
|
|
823
|
+
if os.path.isfile(abs_env):
|
|
824
|
+
with open(abs_env, "r", encoding="utf-8") as _ef:
|
|
825
|
+
orig_env = _ef.read()
|
|
826
|
+
orig_gi = None
|
|
827
|
+
if os.path.isfile(abs_gi):
|
|
828
|
+
with open(abs_gi, "r", encoding="utf-8") as _gf:
|
|
829
|
+
orig_gi = _gf.read()
|
|
830
|
+
shared_env = cls._load_existing_env(abs_env)
|
|
831
|
+
total_migrated = 0
|
|
832
|
+
|
|
833
|
+
try:
|
|
834
|
+
for fp in file_paths:
|
|
835
|
+
abs_fp = os.path.abspath(fp)
|
|
836
|
+
with open(abs_fp, "r", encoding="utf-8", errors="ignore") as f:
|
|
837
|
+
raw = f.read()
|
|
838
|
+
migrated, _, cnt, _ = cls.auto_migrate_to_env(
|
|
839
|
+
raw,
|
|
840
|
+
env_file_path=abs_env,
|
|
841
|
+
gitignore_path=abs_gi,
|
|
842
|
+
shared_env_registry=shared_env,
|
|
843
|
+
dry_run=True,
|
|
844
|
+
)
|
|
845
|
+
if cnt > 0 and migrated != raw:
|
|
846
|
+
if abs_fp.endswith(".py"):
|
|
847
|
+
ast.parse(migrated, filename=abs_fp)
|
|
848
|
+
orig_sources[abs_fp] = raw
|
|
849
|
+
fdir = os.path.dirname(abs_fp) or "."
|
|
850
|
+
with tempfile.NamedTemporaryFile("w", dir=fdir, delete=False, encoding="utf-8", prefix=".tzero_src_") as tf:
|
|
851
|
+
tf.write(migrated)
|
|
852
|
+
staged_sources[abs_fp] = tf.name
|
|
853
|
+
total_migrated += cnt
|
|
854
|
+
|
|
855
|
+
if total_migrated == 0:
|
|
856
|
+
return {"success": True, "migrated_count": 0, "env_file": abs_env, "warning": ""}
|
|
857
|
+
|
|
858
|
+
# Write .gitignore and .env atomically BEFORE mutating any source files
|
|
859
|
+
git_status = cls.check_env_git_status(abs_env, abs_gi)
|
|
860
|
+
if not git_status.get("ignored"):
|
|
861
|
+
existing_gi = orig_gi or ""
|
|
862
|
+
env_base = os.path.basename(abs_env)
|
|
863
|
+
sep = "\n" if existing_gi and not existing_gi.endswith("\n") else ""
|
|
864
|
+
os.makedirs(os.path.dirname(abs_gi) or ".", exist_ok=True)
|
|
865
|
+
with tempfile.NamedTemporaryFile("w", dir=os.path.dirname(abs_gi) or ".", delete=False, encoding="utf-8", prefix=".tzero_gi_") as tf:
|
|
866
|
+
tf.write(f"{existing_gi}{sep}{env_base}\n")
|
|
867
|
+
gi_tmp = tf.name
|
|
868
|
+
os.replace(gi_tmp, abs_gi)
|
|
869
|
+
|
|
870
|
+
env_lines = ["# Auto-Vault Generated by T-Zero Zero-Leak Engine", "# DO NOT COMMIT THIS FILE TO PUBLIC REPOSITORIES", ""]
|
|
871
|
+
for k, v in shared_env.items():
|
|
872
|
+
env_lines.append(f"{k}={v}")
|
|
873
|
+
os.makedirs(os.path.dirname(abs_env) or ".", exist_ok=True)
|
|
874
|
+
with tempfile.NamedTemporaryFile("w", dir=os.path.dirname(abs_env) or ".", delete=False, encoding="utf-8", prefix=".tzero_env_") as tf:
|
|
875
|
+
tf.write("\n".join(env_lines) + "\n")
|
|
876
|
+
env_tmp = tf.name
|
|
877
|
+
os.replace(env_tmp, abs_env)
|
|
878
|
+
|
|
879
|
+
# Commit staged sources
|
|
880
|
+
for abs_fp, tmp_p in staged_sources.items():
|
|
881
|
+
os.replace(tmp_p, abs_fp)
|
|
882
|
+
staged_sources.clear()
|
|
883
|
+
|
|
884
|
+
return {
|
|
885
|
+
"success": True,
|
|
886
|
+
"migrated_count": total_migrated,
|
|
887
|
+
"env_file": abs_env,
|
|
888
|
+
"gitignore_file": abs_gi,
|
|
889
|
+
"warning": git_status.get("warning", ""),
|
|
890
|
+
}
|
|
891
|
+
except Exception as exc:
|
|
892
|
+
# Rollback .env / .gitignore / any partially touched sources
|
|
893
|
+
for tmp_p in staged_sources.values():
|
|
894
|
+
if os.path.exists(tmp_p):
|
|
895
|
+
try:
|
|
896
|
+
os.remove(tmp_p)
|
|
897
|
+
except OSError:
|
|
898
|
+
pass
|
|
899
|
+
if orig_env is not None:
|
|
900
|
+
try:
|
|
901
|
+
with open(abs_env, "w", encoding="utf-8") as ef:
|
|
902
|
+
ef.write(orig_env)
|
|
903
|
+
except OSError:
|
|
904
|
+
pass
|
|
905
|
+
elif os.path.exists(abs_env):
|
|
906
|
+
try:
|
|
907
|
+
os.remove(abs_env)
|
|
908
|
+
except OSError:
|
|
909
|
+
pass
|
|
910
|
+
if orig_gi is not None:
|
|
911
|
+
try:
|
|
912
|
+
with open(abs_gi, "w", encoding="utf-8") as gf:
|
|
913
|
+
gf.write(orig_gi)
|
|
914
|
+
except OSError:
|
|
915
|
+
pass
|
|
916
|
+
return {"success": False, "error": str(exc), "migrated_count": 0}
|
|
917
|
+
|
|
@@ -75,7 +75,7 @@ class TaskEvaluationResult:
|
|
|
75
75
|
|
|
76
76
|
@dataclass
|
|
77
77
|
class TaskBenchmarkReport:
|
|
78
|
-
version: str = "12.2
|
|
78
|
+
version: str = "12.3.2"
|
|
79
79
|
tokenizer: str = "tiktoken (cl100k_base)" if TIKTOKEN_AVAILABLE else "character-ratio fallback"
|
|
80
80
|
total_tasks: int = 0
|
|
81
81
|
passed_tasks: int = 0
|
|
@@ -465,7 +465,7 @@ def analyze_symbol_impact(symbol_path: str, table: SymbolTable, dag: CallGraphDA
|
|
|
465
465
|
"""Formats ANSI-styled benchmark summary table."""
|
|
466
466
|
lines = []
|
|
467
467
|
lines.append("=" * 78)
|
|
468
|
-
lines.append(" T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v12.2
|
|
468
|
+
lines.append(" T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v12.3.2)")
|
|
469
469
|
lines.append(f" Tokenizer: {report.tokenizer} | Tasks Evaluated: {report.total_tasks}")
|
|
470
470
|
lines.append("=" * 78)
|
|
471
471
|
lines.append(f"{'Task ID':<10} | {'Raw BPE':<8} | {'T-Zero':<8} | {'Saved %':<8} | {'Contract %':<10} | {'Status'}")
|