569 lines
19 KiB
Python
569 lines
19 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import hashlib
|
|
import os
|
|
import platform
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import tempfile
|
|
import urllib.request
|
|
import zipfile
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Any, Dict, Optional
|
|
|
|
from .chromium_injector import ChromiumFingerprintSession, start_fingerprint_session
|
|
from .schemas import BrowserInstance, KernelPackageConfig, LaunchRequest, ProxyConfig, RuntimeConfigUpdate
|
|
|
|
|
|
BASE_DIR = Path(__file__).resolve().parents[1]
|
|
REPO_DIR = BASE_DIR.parent
|
|
CORE_DIR = Path(os.environ.get("LOCAL_CONTROLLER_CORE_DIR", REPO_DIR / "core"))
|
|
DATA_DIR = Path(os.environ.get("LOCAL_CONTROLLER_DATA_DIR", BASE_DIR / "data"))
|
|
PROFILE_DIR = Path(os.environ.get("LOCAL_CONTROLLER_PROFILE_DIR", DATA_DIR / "profiles"))
|
|
STATE_FILE = Path(os.environ.get("LOCAL_CONTROLLER_STATE_FILE", DATA_DIR / "running.json"))
|
|
CONFIG_FILE = Path(os.environ.get("LOCAL_CONTROLLER_CONFIG_FILE", DATA_DIR / "runtime_config.json"))
|
|
|
|
RUNTIME_META = {
|
|
"chromium": {
|
|
"env": "CHROMIUM_RUNTIME_PATH",
|
|
"config_key": "chromium_runtime_path",
|
|
"exe_name": {
|
|
"windows": "chrome.exe",
|
|
"macos": "Chromium",
|
|
},
|
|
},
|
|
"firefox": {
|
|
"env": "CAMOUFOX_RUNTIME_PATH",
|
|
"config_key": "camoufox_runtime_path",
|
|
"exe_name": {
|
|
"windows": "camoufox.exe",
|
|
"macos": "camoufox",
|
|
},
|
|
},
|
|
}
|
|
|
|
|
|
def ensure_dirs() -> None:
|
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
PROFILE_DIR.mkdir(parents=True, exist_ok=True)
|
|
CORE_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
def _detect_os_type() -> str:
|
|
system = platform.system().lower()
|
|
if system == "darwin":
|
|
return "macos"
|
|
return "windows"
|
|
|
|
|
|
def _detect_arch_type() -> str:
|
|
machine = platform.machine().lower()
|
|
if machine in {"amd64", "x86_64"}:
|
|
return "x64"
|
|
if machine in {"i386", "i686", "x86"}:
|
|
return "x86"
|
|
if machine in {"arm64", "aarch64"}:
|
|
return "arm64"
|
|
return machine or "x64"
|
|
|
|
|
|
def _free_port() -> int:
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
|
sock.bind(("127.0.0.1", 0))
|
|
return int(sock.getsockname()[1])
|
|
|
|
|
|
def _proxy_to_arg(proxy: ProxyConfig) -> Optional[str]:
|
|
if not proxy.host or not proxy.port:
|
|
return None
|
|
scheme = (proxy.proxy_type or "http").lower()
|
|
if scheme not in {"http", "https", "socks5"}:
|
|
scheme = "http"
|
|
return f"{scheme}://{proxy.host}:{proxy.port}"
|
|
|
|
|
|
def _normalize_proxy(req: LaunchRequest) -> Optional[ProxyConfig]:
|
|
if req.proxy and req.proxy.host and req.proxy.port:
|
|
return req.proxy
|
|
if req.proxy_host and req.proxy_port:
|
|
return ProxyConfig(
|
|
proxy_type=req.proxy_type,
|
|
host=req.proxy_host,
|
|
port=req.proxy_port,
|
|
)
|
|
return None
|
|
|
|
|
|
def _normalize_path(value: Optional[str]) -> Optional[str]:
|
|
if value is None:
|
|
return None
|
|
text = value.strip()
|
|
if not text:
|
|
return None
|
|
return str(Path(text).expanduser())
|
|
|
|
|
|
def _load_runtime_config() -> dict:
|
|
ensure_dirs()
|
|
if not CONFIG_FILE.exists():
|
|
return {}
|
|
try:
|
|
content = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
|
return content if isinstance(content, dict) else {}
|
|
except (OSError, json.JSONDecodeError):
|
|
return {}
|
|
|
|
|
|
def _save_runtime_config(config: dict) -> dict:
|
|
ensure_dirs()
|
|
cleaned = {
|
|
"chromium_runtime_path": _normalize_path(config.get("chromium_runtime_path")),
|
|
"camoufox_runtime_path": _normalize_path(config.get("camoufox_runtime_path")),
|
|
}
|
|
CONFIG_FILE.write_text(json.dumps(cleaned, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
return cleaned
|
|
|
|
|
|
def _discover_runtime_path(engine: str) -> Optional[str]:
|
|
meta = RUNTIME_META[engine]
|
|
exe_name = meta["exe_name"].get(_detect_os_type())
|
|
if not exe_name:
|
|
return None
|
|
if not CORE_DIR.exists():
|
|
return None
|
|
matches = sorted(CORE_DIR.rglob(exe_name))
|
|
if not matches:
|
|
return None
|
|
return str(matches[0])
|
|
|
|
|
|
def _resolve_runtime_path(engine: str, runtime_path: Optional[str] = None) -> str:
|
|
meta = RUNTIME_META[engine]
|
|
config = _load_runtime_config()
|
|
candidates = [
|
|
_normalize_path(runtime_path),
|
|
_normalize_path(config.get(meta["config_key"])),
|
|
_normalize_path(os.environ.get(meta["env"])),
|
|
_discover_runtime_path(engine),
|
|
]
|
|
for candidate in candidates:
|
|
if candidate and Path(candidate).exists():
|
|
return candidate
|
|
raise FileNotFoundError(meta["exe_name"].get(_detect_os_type()) or engine)
|
|
|
|
|
|
def _normalize_relative_path(value: Optional[str]) -> Optional[str]:
|
|
if value is None:
|
|
return None
|
|
text = value.strip().replace("/", os.sep).replace("\\", os.sep)
|
|
return text or None
|
|
|
|
|
|
def _resolve_package_root(kernel: KernelPackageConfig) -> Path:
|
|
version = (kernel.full_version or kernel.browser_version or "unknown").strip()
|
|
os_type = (kernel.os_type or _detect_os_type()).strip().lower()
|
|
arch_type = (kernel.arch_type or _detect_arch_type()).strip().lower()
|
|
engine = (kernel.browser_engine or "chromium").strip().lower()
|
|
return CORE_DIR / f"{os_type}_{arch_type}" / f"{engine}_{version}"
|
|
|
|
|
|
def _resolve_runtime_from_package(kernel: KernelPackageConfig) -> str:
|
|
package_root = _resolve_package_root(kernel)
|
|
executable_path = _normalize_relative_path(kernel.executable_path)
|
|
if not executable_path:
|
|
raise FileNotFoundError("missing executable_path")
|
|
runtime_path = package_root / executable_path
|
|
if not runtime_path.exists():
|
|
raise FileNotFoundError(str(runtime_path))
|
|
return str(runtime_path)
|
|
|
|
|
|
def _download_file(url: str, target: Path) -> None:
|
|
request = urllib.request.Request(url, headers={"User-Agent": "local-controller/0.2.0"})
|
|
with urllib.request.urlopen(request, timeout=60) as response, target.open("wb") as handle:
|
|
while True:
|
|
chunk = response.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
handle.write(chunk)
|
|
|
|
|
|
def _sha256(path: Path) -> str:
|
|
digest = hashlib.sha256()
|
|
with path.open("rb") as handle:
|
|
while True:
|
|
chunk = handle.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
digest.update(chunk)
|
|
return digest.hexdigest()
|
|
|
|
|
|
def _strip_single_root_dir(source_dir: Path, root_name: str) -> Path:
|
|
normalized = _normalize_relative_path(root_name)
|
|
if not normalized:
|
|
return source_dir
|
|
candidate = source_dir / normalized
|
|
return candidate if candidate.exists() else source_dir
|
|
|
|
|
|
def _install_kernel_package(kernel: KernelPackageConfig) -> str:
|
|
if not kernel.package_url:
|
|
raise FileNotFoundError("missing package_url")
|
|
package_root = _resolve_package_root(kernel)
|
|
executable_path = _normalize_relative_path(kernel.executable_path)
|
|
if not executable_path:
|
|
raise FileNotFoundError("missing executable_path")
|
|
runtime_path = package_root / executable_path
|
|
if runtime_path.exists():
|
|
return str(runtime_path)
|
|
|
|
package_root.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.TemporaryDirectory(dir=str(DATA_DIR)) as temp_dir:
|
|
temp_path = Path(temp_dir)
|
|
archive_path = temp_path / "runtime.zip"
|
|
extract_path = temp_path / "extract"
|
|
extract_path.mkdir(parents=True, exist_ok=True)
|
|
_download_file(kernel.package_url, archive_path)
|
|
expected_sha = (kernel.package_sha256 or "").strip().lower()
|
|
if expected_sha:
|
|
actual_sha = _sha256(archive_path)
|
|
if actual_sha.lower() != expected_sha:
|
|
raise RuntimeError("kernel package sha256 mismatch")
|
|
with zipfile.ZipFile(archive_path, "r") as archive:
|
|
archive.extractall(extract_path)
|
|
source_root = _strip_single_root_dir(extract_path, kernel.archive_root_dir)
|
|
if package_root.exists():
|
|
shutil.rmtree(package_root, ignore_errors=True)
|
|
package_root.mkdir(parents=True, exist_ok=True)
|
|
for item in source_root.iterdir():
|
|
destination = package_root / item.name
|
|
if destination.exists():
|
|
if destination.is_dir():
|
|
shutil.rmtree(destination)
|
|
else:
|
|
destination.unlink()
|
|
shutil.move(str(item), str(destination))
|
|
if not runtime_path.exists():
|
|
raise FileNotFoundError(str(runtime_path))
|
|
return str(runtime_path)
|
|
|
|
|
|
def _ensure_runtime_path(req: LaunchRequest) -> str:
|
|
try:
|
|
return _resolve_runtime_path(req.browser_engine, req.runtime_path)
|
|
except FileNotFoundError:
|
|
if not req.kernel_package:
|
|
raise
|
|
return _install_kernel_package(req.kernel_package)
|
|
|
|
|
|
def _runtime_status_item(engine: str) -> dict:
|
|
meta = RUNTIME_META[engine]
|
|
config = _load_runtime_config()
|
|
configured_path = _normalize_path(config.get(meta["config_key"]))
|
|
env_path = _normalize_path(os.environ.get(meta["env"]))
|
|
auto_path = _discover_runtime_path(engine)
|
|
resolved_path = None
|
|
source = None
|
|
for candidate, candidate_source in (
|
|
(configured_path, "config"),
|
|
(env_path, "env"),
|
|
(auto_path, "core"),
|
|
):
|
|
if candidate and Path(candidate).exists():
|
|
resolved_path = candidate
|
|
source = candidate_source
|
|
break
|
|
return {
|
|
"installed": bool(resolved_path),
|
|
"path": resolved_path,
|
|
"configured_path": configured_path,
|
|
"env_path": env_path,
|
|
"auto_path": auto_path,
|
|
"source": source,
|
|
"os_type": _detect_os_type(),
|
|
"arch_type": _detect_arch_type(),
|
|
}
|
|
|
|
|
|
def resolve_profile_dir(req: LaunchRequest) -> Path:
|
|
if req.profile_dir:
|
|
return Path(req.profile_dir)
|
|
return PROFILE_DIR / req.profile_id / req.browser_engine
|
|
|
|
|
|
def build_command(req: LaunchRequest, profile_dir: Path, port: Optional[int]) -> list[str]:
|
|
runtime_path = _ensure_runtime_path(req)
|
|
runtime = Path(runtime_path)
|
|
command = [str(runtime)]
|
|
proxy = _normalize_proxy(req)
|
|
|
|
if req.browser_engine == "chromium":
|
|
command.extend(
|
|
[
|
|
f"--user-data-dir={profile_dir}",
|
|
"--no-first-run",
|
|
"--no-default-browser-check",
|
|
"--disable-popup-blocking",
|
|
]
|
|
)
|
|
if not req.headless:
|
|
command.append("--new-window")
|
|
if port is not None:
|
|
command.append(f"--remote-debugging-port={port}")
|
|
proxy_arg = _proxy_to_arg(proxy) if proxy else None
|
|
if proxy_arg:
|
|
command.append(f"--proxy-server={proxy_arg}")
|
|
else:
|
|
command.extend(
|
|
[
|
|
"-no-remote",
|
|
"-new-instance",
|
|
"-profile",
|
|
str(profile_dir),
|
|
]
|
|
)
|
|
if not req.headless:
|
|
command.append("-foreground")
|
|
|
|
for arg in req.browser_args:
|
|
command.append(arg)
|
|
|
|
if req.browser_engine == "chromium" and req.fingerprint:
|
|
command.append("about:blank")
|
|
else:
|
|
command.append(req.start_url or "about:blank")
|
|
return command
|
|
|
|
|
|
def persist_profile_metadata(profile_dir: Path, req: LaunchRequest) -> None:
|
|
profile_dir.mkdir(parents=True, exist_ok=True)
|
|
runtime_path = _ensure_runtime_path(req)
|
|
payload = {
|
|
"profile_id": req.profile_id,
|
|
"browser_engine": req.browser_engine,
|
|
"runtime_path": runtime_path,
|
|
"proxy": _normalize_proxy(req).model_dump() if _normalize_proxy(req) else None,
|
|
"fingerprint": req.fingerprint,
|
|
"kernel_package": req.kernel_package.model_dump() if req.kernel_package else None,
|
|
"start_url": req.start_url,
|
|
"created_at": time.time(),
|
|
}
|
|
(profile_dir / "launch.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
if req.fingerprint:
|
|
(profile_dir / "fingerprint.json").write_text(json.dumps(req.fingerprint, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
|
|
|
|
@dataclass
|
|
class BrowserProcess:
|
|
profile_id: str
|
|
browser_engine: str
|
|
runtime_path: str
|
|
profile_dir: str
|
|
pid: int
|
|
port: Optional[int]
|
|
start_url: str
|
|
status: str
|
|
command: list[str]
|
|
proxy: Optional[dict]
|
|
fingerprint: Optional[dict]
|
|
kernel_package: Optional[dict]
|
|
fingerprint_injection: Optional[dict]
|
|
fingerprint_session: Optional[ChromiumFingerprintSession]
|
|
started_at: float
|
|
process: subprocess.Popen
|
|
|
|
def to_instance(self) -> BrowserInstance:
|
|
return BrowserInstance(
|
|
profile_id=self.profile_id,
|
|
browser_engine=self.browser_engine, # type: ignore[arg-type]
|
|
runtime_path=self.runtime_path,
|
|
profile_dir=self.profile_dir,
|
|
pid=self.pid,
|
|
port=self.port,
|
|
start_url=self.start_url,
|
|
status=self.status,
|
|
command=self.command,
|
|
proxy=ProxyConfig(**self.proxy) if self.proxy else None,
|
|
fingerprint=self.fingerprint,
|
|
kernel_package=self.kernel_package,
|
|
fingerprint_injection=self.fingerprint_injection,
|
|
)
|
|
|
|
|
|
class ProcessRegistry:
|
|
def __init__(self) -> None:
|
|
self._lock = threading.Lock()
|
|
self._processes: Dict[str, BrowserProcess] = {}
|
|
|
|
def launch(self, req: LaunchRequest) -> BrowserInstance:
|
|
ensure_dirs()
|
|
with self._lock:
|
|
old = self._processes.get(req.profile_id)
|
|
if old and old.process.poll() is None:
|
|
raise RuntimeError(f"profile already running: {req.profile_id}")
|
|
|
|
runtime_path = _ensure_runtime_path(req)
|
|
profile_dir = resolve_profile_dir(req)
|
|
profile_dir.mkdir(parents=True, exist_ok=True)
|
|
runtime_request = req.model_copy(update={"runtime_path": runtime_path})
|
|
persist_profile_metadata(profile_dir, runtime_request)
|
|
|
|
port = _free_port() if req.browser_engine == "chromium" else None
|
|
command = build_command(runtime_request, profile_dir, port)
|
|
|
|
creationflags = 0
|
|
if hasattr(subprocess, "CREATE_NEW_PROCESS_GROUP"):
|
|
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
|
|
|
|
process = subprocess.Popen(
|
|
command,
|
|
cwd=str(Path(runtime_path).parent),
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
stdin=subprocess.DEVNULL,
|
|
creationflags=creationflags,
|
|
)
|
|
|
|
fingerprint_injection = None
|
|
fingerprint_session = None
|
|
if req.browser_engine == "chromium" and port is not None:
|
|
fingerprint_session = start_fingerprint_session(
|
|
port=port,
|
|
fingerprint=req.fingerprint,
|
|
start_url=req.start_url or "about:blank",
|
|
)
|
|
fingerprint_injection = fingerprint_session.status()
|
|
|
|
item = BrowserProcess(
|
|
profile_id=req.profile_id,
|
|
browser_engine=req.browser_engine,
|
|
runtime_path=runtime_path,
|
|
profile_dir=str(profile_dir),
|
|
pid=process.pid,
|
|
port=port,
|
|
start_url=req.start_url,
|
|
status="running",
|
|
command=command,
|
|
proxy=runtime_request.proxy.model_dump() if runtime_request.proxy else None,
|
|
fingerprint=req.fingerprint,
|
|
kernel_package=runtime_request.kernel_package.model_dump() if runtime_request.kernel_package else None,
|
|
fingerprint_injection=fingerprint_injection,
|
|
fingerprint_session=fingerprint_session,
|
|
started_at=time.time(),
|
|
process=process,
|
|
)
|
|
|
|
with self._lock:
|
|
self._processes[req.profile_id] = item
|
|
self._persist()
|
|
|
|
return item.to_instance()
|
|
|
|
def close(self, profile_id: str) -> bool:
|
|
with self._lock:
|
|
item = self._processes.get(profile_id)
|
|
if not item:
|
|
return False
|
|
proc = item.process
|
|
if item.fingerprint_session:
|
|
item.fingerprint_session.stop()
|
|
if proc.poll() is None:
|
|
proc.terminate()
|
|
try:
|
|
proc.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:
|
|
proc.kill()
|
|
item.status = "stopped"
|
|
self._processes.pop(profile_id, None)
|
|
self._persist()
|
|
return True
|
|
|
|
def running(self) -> list[BrowserInstance]:
|
|
items = []
|
|
with self._lock:
|
|
for profile_id, item in list(self._processes.items()):
|
|
if item.process.poll() is not None:
|
|
if item.fingerprint_session:
|
|
item.fingerprint_session.stop()
|
|
item.status = "exited"
|
|
self._processes.pop(profile_id, None)
|
|
continue
|
|
if item.fingerprint_session:
|
|
item.fingerprint_injection = item.fingerprint_session.status()
|
|
items.append(item.to_instance())
|
|
self._persist()
|
|
return items
|
|
|
|
def status(self, profile_id: str) -> Optional[BrowserInstance]:
|
|
with self._lock:
|
|
item = self._processes.get(profile_id)
|
|
if not item:
|
|
return None
|
|
if item.process.poll() is not None:
|
|
if item.fingerprint_session:
|
|
item.fingerprint_session.stop()
|
|
item.status = "exited"
|
|
self._processes.pop(profile_id, None)
|
|
self._persist()
|
|
return None
|
|
if item.fingerprint_session:
|
|
item.fingerprint_injection = item.fingerprint_session.status()
|
|
return item.to_instance()
|
|
|
|
def _persist(self) -> None:
|
|
ensure_dirs()
|
|
snapshot = []
|
|
for item in self._processes.values():
|
|
if item.fingerprint_session:
|
|
item.fingerprint_injection = item.fingerprint_session.status()
|
|
snapshot.append(
|
|
{
|
|
"profile_id": item.profile_id,
|
|
"browser_engine": item.browser_engine,
|
|
"runtime_path": item.runtime_path,
|
|
"profile_dir": item.profile_dir,
|
|
"pid": item.pid,
|
|
"port": item.port,
|
|
"start_url": item.start_url,
|
|
"status": item.status,
|
|
"command": item.command,
|
|
"proxy": item.proxy,
|
|
"fingerprint": item.fingerprint,
|
|
"kernel_package": item.kernel_package,
|
|
"fingerprint_injection": item.fingerprint_injection,
|
|
"started_at": item.started_at,
|
|
}
|
|
)
|
|
STATE_FILE.write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
|
|
def runtime_status(self) -> dict:
|
|
return {
|
|
"ok": True,
|
|
"core_dir": str(CORE_DIR),
|
|
"data_dir": str(DATA_DIR),
|
|
"profile_dir": str(PROFILE_DIR),
|
|
"runtimes": {
|
|
"chromium": _runtime_status_item("chromium"),
|
|
"camoufox": _runtime_status_item("firefox"),
|
|
},
|
|
}
|
|
|
|
def runtime_config(self) -> dict:
|
|
return _save_runtime_config(_load_runtime_config())
|
|
|
|
def save_runtime_config(self, update: RuntimeConfigUpdate) -> dict:
|
|
current = _load_runtime_config()
|
|
current["chromium_runtime_path"] = update.chromium_runtime_path
|
|
current["camoufox_runtime_path"] = update.camoufox_runtime_path
|
|
return _save_runtime_config(current)
|
|
|
|
|
|
registry = ProcessRegistry()
|