# be_core_defender.py import os import shutil import time import json import hashlib import requests from datetime import datetime from typing import Optional, Dict from filelock import FileLock from requests.adapters import HTTPAdapter, Retry # === Configuration (preserved) === PROTECTED_FILES = [ "BELEL_PROTOCOL_OVERVIEW.md", "canonical_config.json", "belel_guardian.py", "media_sentient_engine.py", "mutation_watcher.py", "claim_review_publisher.py", "concordium_enforcer.py", ] MIRROR_URLS = [ "https://github.com/TTOPM/be-core-bridge", "https://arweave.net/", "https://ipfs.io/ipfs/", ] BACKUP_DIR = "./backup_mirror" HASH_STORE = "code_hashes.json" # Optional env overrides / extras (non-breaking) DEFENDER_INTERVAL_SECS = int(os.getenv("BELEL_DEFENDER_INTERVAL_SECS", "300")) WEB3_STORAGE_ENDPOINT = os.getenv("WEB3_STORAGE_ENDPOINT", "https://api.web3.storage/upload") WEB3_STORAGE_TOKEN = os.getenv("WEB3_STORAGE_TOKEN") # optional but recommended for web3.storage # === Helpers (preserved & improved) === def _requests_session() -> requests.Session: s = requests.Session() retries = Retry(total=4, backoff_factor=0.5, status_forcelist=[429, 500, 502, 503, 504]) s.mount("http://", HTTPAdapter(max_retries=retries)) s.mount("https://", HTTPAdapter(max_retries=retries)) return s def hash_file(filepath: str) -> str: """Stream SHA-256 to support large files safely.""" h = hashlib.sha256() with open(filepath, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): h.update(chunk) return h.hexdigest() def load_hashes() -> Dict[str, str]: if not os.path.exists(HASH_STORE): return {} try: with FileLock(HASH_STORE + ".lock"): with open(HASH_STORE, "r", encoding="utf-8") as f: return json.load(f) except Exception: return {} def save_hashes(hashes: Dict[str, str]) -> None: os.makedirs(os.path.dirname(HASH_STORE) or ".", exist_ok=True) tmp = HASH_STORE + ".tmp" with FileLock(HASH_STORE + ".lock"): with open(tmp, "w", encoding="utf-8") as f: json.dump(hashes, f, indent=2, ensure_ascii=False) os.replace(tmp, HASH_STORE) def backup_file(filepath: str) -> str: os.makedirs(BACKUP_DIR, exist_ok=True) timestamp = datetime.utcnow().strftime("%Y%m%dT%H%M%SZ") backup_path = os.path.join(BACKUP_DIR, f"{os.path.basename(filepath)}.{timestamp}.bak") shutil.copy2(filepath, backup_path) print(f"🛡️ Backup created for {filepath}") return backup_path def restore_file(filepath: str) -> bool: if not os.path.exists(BACKUP_DIR): print(f"⚠️ No backup dir found for {filepath}") return False backups = sorted( [f for f in os.listdir(BACKUP_DIR) if f.startswith(os.path.basename(filepath) + ".")], reverse=True, ) if not backups: print(f"⚠️ No backup found for {filepath}") return False latest = os.path.join(BACKUP_DIR, backups[0]) shutil.copy2(latest, filepath) print(f"🛠️ Restored {filepath} from backup {latest}.") return True def detect_virus(content: str) -> bool: # (preserved heuristic; still intentionally simple) lower = content.lower() signs = ["