recovered from aaronjaworski710
CI / offline-tests (push) Has been cancelled
CI / web-unit-tests (push) Has been cancelled
CI / package-console10 (push) Has been cancelled

This commit is contained in:
reform
2026-10-23 20:02:14 +03:00
commit 8044e88be4
409 changed files with 104886 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
"""Project-owned Web control plane API."""
__all__ = ["create_app"]
def __getattr__(name: str):
if name == "create_app":
from apps.control_api.app import create_app
return create_app
raise AttributeError(name)
+22
View File
@@ -0,0 +1,22 @@
"""python -m apps.control_api"""
from __future__ import annotations
import uvicorn
from apps.control_api.settings import get_settings
def main() -> None:
s = get_settings()
uvicorn.run(
"apps.control_api.app:create_app",
factory=True,
host=s.host,
port=s.port,
log_level="info",
)
if __name__ == "__main__":
main()
+167
View File
@@ -0,0 +1,167 @@
"""List / inspect / delete product accounts under cpa_auths (disk-first pool)."""
from __future__ import annotations
import json
import time
from pathlib import Path
from typing import Any
# Per-process mtime cache so paginated UI polls don't re-parse every auth JSON.
_SUMMARY_CACHE: dict[str, tuple[int, int, dict[str, Any]]] = {}
def _auth_dir(root: Path) -> Path:
return root / "cpa_auths"
def _safe_name(name: str) -> str:
base = Path(str(name or "")).name
if not base or base in {".", ".."} or "/" in str(name) or "\\" in str(name):
raise ValueError("invalid account name")
if not (base.startswith("xai-") and base.endswith(".json")):
raise ValueError("account file must be xai-*.json")
return base
def _summarize(path: Path) -> dict[str, Any]:
st = path.stat()
mtime_ns = int(getattr(st, "st_mtime_ns", int(st.st_mtime * 1_000_000_000)))
size = int(st.st_size)
cache_key = str(path)
hit = _SUMMARY_CACHE.get(cache_key)
if hit and hit[0] == mtime_ns and hit[1] == size:
return hit[2]
email = ""
complete = False
has_access = False
has_refresh = False
disabled = False
expired = False
priority = None
auth_kind = None
last_refresh = None
err = None
try:
data = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
err = "not_object"
else:
email = str(data.get("email") or "")
at = data.get("access_token")
rt = data.get("refresh_token")
has_access = isinstance(at, str) and bool(at)
has_refresh = isinstance(rt, str) and bool(rt)
complete = has_access and has_refresh
disabled = bool(data.get("disabled"))
expired = bool(data.get("expired"))
priority = data.get("priority")
auth_kind = data.get("auth_kind") or data.get("type")
last_refresh = data.get("last_refresh")
except Exception as exc:
err = str(exc)[:200]
summary = {
"name": path.name,
"email": email or path.name.removeprefix("xai-").removesuffix(".json"),
"complete": complete,
"has_access": has_access,
"has_refresh": has_refresh,
"disabled": disabled,
"expired": expired,
"priority": priority,
"auth_kind": auth_kind,
"last_refresh": last_refresh,
"size": size,
"mtime": int(st.st_mtime),
"mtime_iso": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st.st_mtime)),
"error": err,
}
_SUMMARY_CACHE[cache_key] = (mtime_ns, size, summary)
return summary
def list_accounts(
root: Path,
*,
q: str = "",
complete: str = "",
page: int = 1,
page_size: int = 50,
) -> dict[str, Any]:
d = _auth_dir(root)
if not d.is_dir():
return {
"path": str(d),
"total": 0,
"complete": 0,
"page": 1,
"page_size": page_size,
"pages": 0,
"items": [],
}
paths = sorted(d.glob("xai-*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
items = [_summarize(p) for p in paths]
# Drop cache entries for files that disappeared (bounded leak guard).
live = {str(p) for p in paths}
for k in list(_SUMMARY_CACHE.keys()):
if k.startswith(str(d)) and k not in live:
_SUMMARY_CACHE.pop(k, None)
complete_n = sum(1 for it in items if it.get("complete"))
qq = (q or "").strip().lower()
if qq:
items = [
it
for it in items
if qq in (it.get("email") or "").lower() or qq in (it.get("name") or "").lower()
]
c = (complete or "").strip().lower()
if c in {"1", "true", "yes", "ok", "complete"}:
items = [it for it in items if it.get("complete")]
elif c in {"0", "false", "no", "incomplete"}:
items = [it for it in items if not it.get("complete")]
total = len(items)
if page_size <= 0:
page = 1
page_size = total or 1
page_items = items
pages = 1 if total else 0
else:
page = max(1, int(page or 1))
page_size = max(1, min(500, int(page_size)))
pages = (total + page_size - 1) // page_size if total else 0
if pages and page > pages:
page = pages
start = (page - 1) * page_size
page_items = items[start : start + page_size]
return {
"path": str(d),
"total": total,
"complete": complete_n if not qq and not c else sum(1 for it in items if it.get("complete")),
"disk_complete": complete_n,
"page": page,
"page_size": page_size,
"pages": pages,
"items": page_items,
}
def delete_account(root: Path, name: str) -> dict[str, Any]:
"""Soft-delete: rename into cpa_auths/.trash/ with timestamp suffix (audit/backup)."""
base = _safe_name(name)
auth_dir = _auth_dir(root)
path = auth_dir / base
if not path.is_file():
raise FileNotFoundError(base)
trash = auth_dir / ".trash"
trash.mkdir(parents=True, exist_ok=True)
stamp = time.strftime("%Y%m%dT%H%M%S")
dest = trash / f"{base}.{stamp}"
# Avoid clobber if two deletes land in the same second.
if dest.exists():
dest = trash / f"{base}.{stamp}.{int(time.time() * 1000) % 1000}"
path.rename(dest)
_SUMMARY_CACHE.pop(str(path), None)
return {"ok": True, "deleted": base, "archived": dest.name, "archived_path": str(dest)}
+115
View File
@@ -0,0 +1,115 @@
"""FastAPI application factory for the project control plane."""
from __future__ import annotations
from pathlib import Path
from fastapi import Depends, FastAPI
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from apps.control_api.auth import auth_is_required, require_auth
from apps.control_api.schemas import HealthOut, OverviewOut
from apps.control_api.settings import get_settings, log_auth_startup
from apps.control_api.users import ensure_bootstrap_user, has_any_user
def create_app() -> FastAPI:
app = FastAPI(title="ai-register-machine control API", version="1.1.0")
@app.on_event("startup")
def _bootstrap_user() -> None:
s = get_settings()
# Always print ops-safe auth readiness (sources only, never secret values).
log_auth_startup(s)
if not s.password_login_enabled:
return
created = ensure_bootstrap_user(
s.project_root,
username=s.bootstrap_user,
password=s.bootstrap_password,
)
if created:
# Do not log password; username only.
print(f"[control_api] bootstrap operator created: {created}", flush=True)
@app.get("/api/health", response_model=HealthOut)
def health() -> HealthOut:
s = get_settings()
return HealthOut(
ok=True,
project_root=str(s.project_root),
token_required=bool(s.token),
password_login_enabled=s.password_login_enabled,
users_configured=has_any_user(s.project_root),
auth_required=auth_is_required(s.project_root),
)
@app.get("/api/overview", response_model=OverviewOut, dependencies=[Depends(require_auth)])
def overview() -> OverviewOut:
from apps.control_api.overview import build_overview
s = get_settings()
return OverviewOut(**build_overview(s.project_root))
try:
from apps.control_api.routes_auth import router as auth_router
app.include_router(auth_router)
except ImportError:
pass
try:
from apps.control_api.routes_config import router as config_router
app.include_router(config_router, dependencies=[Depends(require_auth)])
except ImportError:
pass
try:
from apps.control_api.routes_runs import router as runs_router
app.include_router(runs_router, dependencies=[Depends(require_auth)])
except ImportError:
pass
try:
from apps.control_api.routes_import import router as import_router
app.include_router(import_router, dependencies=[Depends(require_auth)])
except ImportError:
pass
try:
from apps.control_api.routes_nodes import router as nodes_router
app.include_router(nodes_router, dependencies=[Depends(require_auth)])
except ImportError:
pass
try:
from apps.control_api.routes_accounts import router as accounts_router
app.include_router(accounts_router, dependencies=[Depends(require_auth)])
except ImportError:
pass
try:
from apps.control_api.routes_ops import router as ops_router
app.include_router(ops_router, dependencies=[Depends(require_auth)])
except ImportError:
pass
try:
from apps.control_api.routes_mail import router as mail_router
app.include_router(mail_router, dependencies=[Depends(require_auth)])
except ImportError:
pass
web_root = Path(__file__).resolve().parents[1] / "web"
web_dist = web_root / "dist"
# Prefer Vite build (console10); fall back to flat static root / legacy.
web_dir = web_dist if (web_dist / "index.html").is_file() else web_root
if web_dir.is_dir() and (web_dir / "index.html").is_file():
app.mount("/", StaticFiles(directory=str(web_dir), html=True), name="web")
@app.exception_handler(ValueError)
async def _value_error(_request, exc: ValueError):
return JSONResponse(status_code=400, content={"detail": str(exc)})
return app
+95
View File
@@ -0,0 +1,95 @@
"""Auth for control API: session cookie and/or bearer token."""
from __future__ import annotations
import hmac
from fastapi import Header, HTTPException, Request, status
from apps.control_api.sessions import COOKIE_NAME, read_session_token
from apps.control_api.settings import get_settings
from apps.control_api.users import has_any_user
def session_username(request: Request) -> str | None:
settings = get_settings()
if not settings.session_secret:
return None
raw = request.cookies.get(COOKIE_NAME)
if not raw:
return None
payload = read_session_token(
raw,
secret=settings.session_secret,
max_age=settings.session_ttl_seconds,
)
if not payload:
return None
user = payload.get("u")
return str(user) if user else None
def auth_is_required(project_root=None) -> bool:
"""Gate API when bearer token is set OR password login mode is on."""
settings = get_settings()
if settings.token:
return True
# Password mode: require session (even before first user — login returns 503).
return bool(settings.password_login_enabled)
def _bearer_ok(
authorization: str | None,
x_control_token: str | None,
) -> bool:
settings = get_settings()
if not settings.token:
return False
presented: str | None = None
if authorization and authorization.lower().startswith("bearer "):
presented = authorization[7:].strip()
elif x_control_token:
presented = x_control_token.strip()
if not presented:
return False
return hmac.compare_digest(presented, settings.token)
def require_token(
authorization: str | None = Header(default=None),
x_control_token: str | None = Header(default=None, alias="X-Control-Token"),
) -> None:
"""Legacy dependency: bearer/X-Control-Token only."""
settings = get_settings()
if not settings.token:
return
if _bearer_ok(authorization, x_control_token):
return
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid or missing token",
)
def require_auth(
request: Request,
authorization: str | None = Header(default=None),
x_control_token: str | None = Header(default=None, alias="X-Control-Token"),
) -> str | None:
"""Accept valid session cookie OR bearer token. Returns username or 'token'."""
settings = get_settings()
if settings.token and _bearer_ok(authorization, x_control_token):
return "token"
user = session_username(request)
if user:
return user
if not auth_is_required(settings.project_root):
return None
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="login required",
)
+409
View File
@@ -0,0 +1,409 @@
"""Load / redact / save project config.json with backup-before-write.
Console is the control plane: saving config also mirrors operational keys into
``.env`` so batch supervisors (which load ``.env``) follow the UI.
"""
from __future__ import annotations
import json
import re
import shutil
import time
from pathlib import Path
from typing import Any
SECRET_KEY_SUBSTR = (
"password",
"api_key",
"apikey",
"token",
"jwt",
"secret",
"credential",
)
def _is_comment_key(key: str) -> bool:
return key.startswith("//") or key.startswith("#")
def _is_secret_key(key: str) -> bool:
low = key.lower()
return any(s in low for s in SECRET_KEY_SUBSTR)
def load_config(root: Path) -> dict[str, Any]:
path = root / "config.json"
if not path.is_file():
return {}
raw = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict):
raise ValueError("config.json must be a JSON object")
return {k: v for k, v in raw.items() if not _is_comment_key(str(k))}
def redact_config(data: dict[str, Any]) -> dict[str, Any]:
out: dict[str, Any] = {}
for k, v in data.items():
if _is_secret_key(str(k)) and isinstance(v, str) and v:
if len(v) <= 4:
out[k] = "***"
else:
out[k] = f"***{v[-4:]}"
else:
out[k] = v
return out
def _looks_masked(value: Any) -> bool:
return isinstance(value, str) and value.startswith("***")
# config.json key → .env / process env key (non-secret operational controls only).
# Secrets (api keys, passwords, tokens) stay out of console→.env sync.
CONFIG_TO_ENV: dict[str, str] = {
"email_provider": "EMAIL_PROVIDER",
"email_providers": "EMAIL_PROVIDERS",
"email_provider_strategy": "EMAIL_PROVIDER_STRATEGY",
"defaultDomains": "DEFAULT_DOMAINS",
"cloudflare_api_base": "CLOUDFLARE_API_BASE",
"cloudflare_auth_mode": "CLOUDFLARE_AUTH_MODE",
"hotmail_accounts_file": "HOTMAIL_ACCOUNTS_FILE",
"mail_timeout": "MAIL_TIMEOUT",
"mail_poll_interval": "MAIL_POLL_INTERVAL",
"proxy": "PROXY",
"cpa_proxy": "CPA_PROXY",
"cpa_probe_chat": "CPA_PROBE_CHAT",
"cpa_remote_inject": "CPA_REMOTE_INJECT",
"cpa_export_enabled": "CPA_EXPORT_ENABLED",
"proxy_rotate_mode": "PROXY_ROTATE_MODE",
"proxy_rotate_every": "PROXY_ROTATE_EVERY",
"proxy_list": "PROXY_LIST",
}
ENV_TO_CONFIG: dict[str, str] = {v: k for k, v in CONFIG_TO_ENV.items()}
# Empty string is a real "clear" for multi-select / free-form lists only.
# All other operational keys treat "" as "omit / keep existing" so a partial
# Register save cannot wipe PROXY (etc.) from .env or config.json.
# defaultDomains is clearable so Resources can intentionally empty the domain pool
# (Register never posts this key — omit keeps prior).
CLEARABLE_EMPTY_CONFIG_KEYS = frozenset(
{
"email_providers",
"proxy_list",
"defaultDomains",
}
)
_SAFE_ENV_KEY = re.compile(r"^[A-Z][A-Z0-9_]*$")
# Allowlisted .env keys the control plane may write (sync + start_run inject).
ENV_ALLOWLIST = frozenset(CONFIG_TO_ENV.values()) | frozenset(
{
"CPA_BATCH_END_INJECT",
"CPA_BATCH_IMPORT_EVERY",
"CPA_BATCH_IMPORT_SIZE",
"CPA_BATCH_IMPORT_PAUSE",
"SKIP_CLASH_PREFLIGHT",
"NODE_SCORE",
"SUPERVISOR_CHUNK",
# Outlook live gate — the operator-controlled flag that turns on
# browser orchestration for the Outlook provider. A *name*, never a
# secret value; allowlisting lets the control plane pass it through
# start_run extra_env / .env sync so the gate can be turned on
# out-of-band without exposing proxy/email/token env vars (those are
# never allowlisted).
"GROK_REGISTER_OUTLOOK_LIVE",
}
)
def _format_env_value(value: Any) -> str | None:
"""Serialize a config value for .env. None = clear/omit key."""
if value is None:
return None
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (list, tuple, set)):
parts = [str(x).strip() for x in value if str(x).strip()]
return ",".join(parts) if parts else ""
if isinstance(value, (int, float)) and not isinstance(value, bool):
return str(value)
text = str(value).strip()
return text
def _is_blank_config_value(value: Any) -> bool:
"""True when a payload value should not overwrite sticky operational state."""
if value is None:
return True
if isinstance(value, str) and not value.strip():
return True
if isinstance(value, (list, tuple, set)) and not any(str(x).strip() for x in value):
return True
return False
def parse_env_file(env_path: Path) -> dict[str, str]:
"""Parse simple KEY=value .env lines (no export/quotes expansion)."""
out: dict[str, str] = {}
if not env_path.is_file():
return out
try:
text = env_path.read_text(encoding="utf-8")
except OSError:
return out
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, val = line.partition("=")
key = key.strip()
if not key or not _SAFE_ENV_KEY.match(key):
continue
out[key] = val
return out
def enrich_config_from_env(root: Path, cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Fill blank non-secret operational config fields from project ``.env``.
Response-only helper for GET /api/config so the console shows the values
the batch actually runs with when config.json still has empty proxy/domains.
Does not write disk.
"""
data = dict(cfg if isinstance(cfg, dict) else load_config(root))
env_map = parse_env_file(root / ".env")
if not env_map:
return data
for env_key, cfg_key in ENV_TO_CONFIG.items():
if _is_secret_key(cfg_key):
continue
if env_key not in env_map:
continue
env_val = str(env_map.get(env_key) or "").strip()
if not env_val:
continue
cur = data.get(cfg_key)
if not _is_blank_config_value(cur):
continue
# Bool-ish env for known bool config keys.
if cfg_key in ("cpa_probe_chat", "cpa_remote_inject", "cpa_export_enabled"):
low = env_val.lower()
if low in ("1", "true", "yes", "on"):
data[cfg_key] = True
elif low in ("0", "false", "no", "off"):
data[cfg_key] = False
else:
data[cfg_key] = env_val
elif cfg_key in ("mail_timeout", "mail_poll_interval", "proxy_rotate_every"):
try:
data[cfg_key] = int(env_val)
except ValueError:
data[cfg_key] = env_val
elif cfg_key == "email_providers":
data[cfg_key] = [p.strip() for p in env_val.split(",") if p.strip()]
elif cfg_key == "proxy_list":
# PROXY_LIST may be comma or newline separated in env; keep string.
data[cfg_key] = env_val
else:
data[cfg_key] = env_val
return data
def config_to_env_map(
cfg: dict[str, Any] | None,
*,
only_keys: set[str] | list[str] | None = None,
skip_empty: bool = False,
) -> dict[str, str]:
"""Map operational config keys → env strings.
``only_keys``: if set, only these config.json keys are considered (used on
save so a hotmail switch does not wipe unrelated PROXY/DEFAULT_DOMAINS).
``skip_empty``: omit empty-string values (start_run inject must not clobber
a healthy process/env PROXY with config proxy=\"\").
Sticky keys (everything except CLEARABLE_EMPTY_CONFIG_KEYS) never emit an
empty string even when skip_empty is False — only multi-select/list fields
may intentionally clear with ``KEY=``.
"""
out: dict[str, str] = {}
if not isinstance(cfg, dict):
return out
allow_cfg = set(only_keys) if only_keys is not None else None
for cfg_key, env_key in CONFIG_TO_ENV.items():
if allow_cfg is not None and cfg_key not in allow_cfg:
continue
if env_key not in ENV_ALLOWLIST or not _SAFE_ENV_KEY.match(env_key):
continue
if cfg_key not in cfg:
continue
if _is_secret_key(cfg_key):
continue
formatted = _format_env_value(cfg.get(cfg_key))
if formatted is None:
continue
if formatted == "":
# Intentional clear only for multi-select / free-form lists.
if skip_empty or cfg_key not in CLEARABLE_EMPTY_CONFIG_KEYS:
continue
out[env_key] = formatted
return out
def update_env_file(
env_path: Path,
updates: dict[str, str],
*,
backup: bool = True,
) -> dict[str, Any]:
"""Upsert allowlisted KEY=value lines in ``.env``; preserve comments/unknown keys.
Empty string values write ``KEY=`` (clears multi-select pools). Keys not in
ENV_ALLOWLIST are ignored. Returns changed env keys + optional backup path.
"""
clean: dict[str, str] = {}
for k, v in (updates or {}).items():
key = str(k).strip()
if key not in ENV_ALLOWLIST or not _SAFE_ENV_KEY.match(key):
continue
clean[key] = str(v)
if not clean:
return {"changed_env_keys": [], "backup": None, "path": str(env_path)}
existing_text = ""
if env_path.is_file():
existing_text = env_path.read_text(encoding="utf-8")
lines = existing_text.splitlines(keepends=True) if existing_text else []
# Normalize to list of lines with newline for rewrite.
if lines and not lines[-1].endswith("\n"):
lines[-1] = lines[-1] + "\n"
seen: set[str] = set()
changed: list[str] = []
new_lines: list[str] = []
for line in lines:
raw = line.rstrip("\n")
stripped = raw.strip()
if not stripped or stripped.startswith("#") or "=" not in stripped:
new_lines.append(line if line.endswith("\n") else line + "\n")
continue
key, _, old_val = stripped.partition("=")
key = key.strip()
if key not in clean:
new_lines.append(line if line.endswith("\n") else line + "\n")
continue
seen.add(key)
new_val = clean[key]
if old_val != new_val:
changed.append(key)
new_lines.append(f"{key}={new_val}\n")
for key, new_val in clean.items():
if key in seen:
continue
changed.append(key)
new_lines.append(f"{key}={new_val}\n")
bak_path: str | None = None
if changed:
env_path.parent.mkdir(parents=True, exist_ok=True)
if backup and env_path.is_file():
ts = time.strftime("%Y%m%d_%H%M%S")
bak = env_path.with_name(f".env.bak-web-{ts}")
shutil.copy2(env_path, bak)
bak_path = str(bak)
tmp = env_path.with_name(".env.tmp-web")
tmp.write_text("".join(new_lines), encoding="utf-8")
tmp.replace(env_path)
return {
"changed_env_keys": changed,
"backup": bak_path,
"path": str(env_path),
}
def sync_config_to_env(
root: Path,
cfg: dict[str, Any] | None = None,
*,
only_keys: set[str] | list[str] | None = None,
skip_empty: bool = False,
) -> dict[str, Any]:
"""Mirror operational config fields into project ``.env`` (console control plane)."""
data = cfg if isinstance(cfg, dict) else load_config(root)
return update_env_file(
root / ".env",
config_to_env_map(data, only_keys=only_keys, skip_empty=skip_empty),
)
def save_config(root: Path, data: dict[str, Any]) -> dict[str, Any]:
"""Write config.json and mirror **changed** operational keys into ``.env``.
Empty or masked secret fields keep previous values. Only keys present in
the put payload that are operational (CONFIG_TO_ENV) are written to .env,
so saving email_provider does not blank PROXY/DEFAULT_DOMAINS.
Sticky empty: for operational keys outside CLEARABLE_EMPTY_CONFIG_KEYS,
a blank payload value is ignored for both config.json merge and .env sync
(keeps prior non-empty). Multi-select fields like email_providers may still
clear with "".
"""
path = root / "config.json"
existing = load_config(root) if path.is_file() else {}
merged: dict[str, Any] = dict(existing)
changed: list[str] = []
payload_keys: list[str] = []
for key, value in data.items():
if _is_comment_key(str(key)):
continue
if _is_secret_key(str(key)):
if value in ("", None) or _looks_masked(value):
continue
key_s = str(key)
# Sticky operational fields: blank payload must not wipe prior value.
if (
key_s in CONFIG_TO_ENV
and key_s not in CLEARABLE_EMPTY_CONFIG_KEYS
and _is_blank_config_value(value)
):
continue
payload_keys.append(key_s)
old = existing.get(key)
if old != value:
changed.append(key_s)
merged[key] = value
backup: str | None = None
if path.is_file():
ts = time.strftime("%Y%m%d_%H%M%S")
bak = path.with_name(f"config.json.bak-web-{ts}")
shutil.copy2(path, bak)
backup = str(bak)
tmp = path.with_suffix(".json.tmp-web")
tmp.write_text(json.dumps(merged, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
tmp.replace(path)
# Sync only operational keys that were part of this save payload.
# config_to_env_map also refuses sticky empty → double protection if caller
# ever passes merged-with-blank.
env_keys = [k for k in payload_keys if k in CONFIG_TO_ENV]
env_sync: dict[str, Any] = {"changed_env_keys": [], "backup": None}
if env_keys:
env_sync = sync_config_to_env(root, merged, only_keys=env_keys)
return {
"backup": backup,
"changed_keys": changed,
"changed_env_keys": list(env_sync.get("changed_env_keys") or []),
"env_backup": env_sync.get("backup"),
"config": redact_config(merged),
}
+428
View File
@@ -0,0 +1,428 @@
"""Import helpers: nodes, mail, auths, config packs."""
from __future__ import annotations
import json
import shutil
import stat
import subprocess
import sys
import time
import zipfile
from pathlib import Path
from typing import Any, Literal
from apps.control_api.config_io import load_config
# Cap on the *uncompressed* bytes an upload zip may emit. save_upload caps the
# compressed upload at max_upload_bytes, but a zip bomb (quadratic/quine) can
# explode to many GB from a tiny payload — so the extraction path needs its own
# ceiling independent of the upload size.
DEFAULT_MAX_ZIP_EXTRACT_BYTES = 256 * 1024 * 1024
def staging_dir(root: Path) -> Path:
d = root / "output" / "web_uploads"
d.mkdir(parents=True, exist_ok=True)
return d
def ensure_under(root: Path, path: Path) -> Path:
resolved = path.resolve()
root_r = root.resolve()
staging = staging_dir(root).resolve()
if resolved == root_r or root_r in resolved.parents:
return resolved
if resolved == staging or staging in resolved.parents:
return resolved
raise ValueError(f"path escapes project root: {path}")
def save_upload(root: Path, filename: str, data: bytes, max_bytes: int) -> Path:
if len(data) > max_bytes:
raise ValueError(f"upload exceeds max_upload_bytes={max_bytes}")
safe = Path(filename).name
if not safe or safe in {".", ".."}:
raise ValueError("invalid filename")
dest = staging_dir(root) / f"{int(time.time())}_{safe}"
dest.write_bytes(data)
return ensure_under(root, dest)
def safe_extract_zip(
zf: zipfile.ZipFile,
dest: Path,
*,
max_bytes: int = DEFAULT_MAX_ZIP_EXTRACT_BYTES,
) -> int:
"""Extract ``zf`` into ``dest`` with three upload-zip defenses:
1. path traversal — reject absolute / drive-prefixed names and any ".."
segment (zip-slip), and re-verify each resolved path stays under dest.
2. symlink/hardlink entries — skip. A link inside an uploaded zip can
point anywhere on disk; a later import walking the tree would follow it
out of the staging dir. Only regular files and dirs are written.
3. decompression bomb — cap total uncompressed bytes at ``max_bytes``,
counting real bytes read from the stream (not the declared header size,
which a crafted archive can underreport).
Returns the number of entries written (files + dirs). Raises ValueError on
the first unsafe entry or overflow.
"""
dest = dest.resolve()
dest.mkdir(parents=True, exist_ok=True)
total = 0
written = 0
for info in zf.infolist():
name = info.filename
# Zip-slip: absolute, drive-prefixed ("C:\\x"), or parent-escaping.
if (
name.startswith("/")
or name.startswith("\\")
or (len(name) > 1 and name[1] == ":")
or ".." in Path(name).parts
):
raise ValueError(f"unsafe zip entry: {name!r}")
# Symlink/hardlink: unix mode lives in the high 16 bits of
# external_attr. S_IFLNK = 0xA000 — drop, never materialize.
mode = (info.external_attr >> 16) & 0xFFFF
if (mode & 0xF000) == stat.S_IFLNK:
continue
target = (dest / name).resolve()
if target != dest and dest not in target.parents:
raise ValueError(f"zip entry escapes dest: {name!r}")
if info.is_dir():
target.mkdir(parents=True, exist_ok=True)
written += 1
continue
# Regular file: stream through ourselves so the cumulative cap counts
# REAL decompressed bytes, defeating a header that lies about its size.
target.parent.mkdir(parents=True, exist_ok=True)
with zf.open(info, "r") as src, open(target, "wb") as out:
while True:
chunk = src.read(1024 * 1024)
if not chunk:
break
total += len(chunk)
if total > max_bytes:
out.close()
target.unlink(missing_ok=True)
raise ValueError(
f"zip exceeds max uncompressed bytes ({max_bytes}): {name!r}"
)
out.write(chunk)
written += 1
return written
def import_nodes(
root: Path,
file_path: Path,
*,
dry_run: bool = False,
replace: bool = False,
) -> dict[str, Any]:
path = ensure_under(root, file_path)
script = root / "scripts" / "import_nodes.py"
if not script.is_file():
raise FileNotFoundError(str(script))
argv = [sys.executable, str(script), str(path)]
if dry_run:
argv.append("--dry-run")
if replace:
argv.append("--replace")
proc = subprocess.run(
argv,
cwd=str(root),
capture_output=True,
text=True,
timeout=600,
)
return {
"exit": proc.returncode,
"stdout": (proc.stdout or "")[-4000:],
"stderr": (proc.stderr or "")[-2000:],
"path": str(path),
"dry_run": dry_run,
"replace": replace,
"ok": proc.returncode == 0,
}
def _mail_pool_email_set(path: Path) -> set[str]:
"""Lowercased emails currently in the pool file (deduped). No secrets returned."""
from mail_pool_probe import parse_credential_line
out: set[str] = set()
if not path.is_file():
return out
try:
text = path.read_text(encoding="utf-8-sig", errors="replace")
except OSError:
return out
for raw in text.splitlines():
item = parse_credential_line(raw)
if not item:
continue
out.add(item.email.strip().lower())
return out
def _summarize_mail_import(
*,
mode: str,
parsed: int,
new: int,
duplicate: int,
skipped: int,
pool_before: int,
pool_after: int,
sample_new: list[str],
formats: dict[str, int],
) -> str:
"""Human-readable Chinese summary for UI toast/banner (no secrets)."""
bits: list[str] = []
if mode == "replace":
bits.append(f"替换写入 {new} 条")
else:
bits.append(f"新增 {new}")
if duplicate:
bits.append(f"重复跳过 {duplicate}")
if skipped:
bits.append(f"格式无效 {skipped}")
fmt_bits = []
if formats.get("json_objects"):
fmt_bits.append(f"JSON {formats['json_objects']}")
if formats.get("csv_rows"):
fmt_bits.append(f"CSV {formats['csv_rows']}")
if fmt_bits:
bits.append("来源 " + "+".join(fmt_bits))
bits.append(f"池 {pool_before}→{pool_after}")
if sample_new:
show = "、".join(sample_new[:3])
if len(sample_new) > 3:
show += f" 等{len(sample_new)}个"
bits.append(f"新号 {show}")
if new == 0 and duplicate > 0 and skipped == 0:
return "未新增(全部已在池中)· " + " · ".join(bits)
if new == 0 and skipped > 0 and duplicate == 0:
return "未导入(格式无效)· " + " · ".join(bits)
if new == 0 and parsed == 0:
return "未导入(无有效凭证)· " + " · ".join(bits)
if new > 0 and (duplicate or skipped):
return "部分成功 · " + " · ".join(bits)
if new > 0:
return "导入成功 · " + " · ".join(bits)
return "导入完成 · " + " · ".join(bits)
def import_mail(
root: Path,
content: str,
*,
mode: Literal["append", "replace"] = "append",
) -> dict[str, Any]:
"""Import mail credentials; normalize vendor formats → dash form before write.
Accepts classic ``email----password----clientId----refreshToken`` lines,
vendor JSON (objects/arrays/wrappers), CSV headers, and ``|``/``;``/tab/``:``
4-field lines. Invalid lines are skipped (not written raw).
Append mode skips emails already present in the pool (dedupe) and reports
new vs duplicate counts so the UI can show honest feedback.
"""
from mail_pool_probe import normalize_credential_text, parse_credential_line
cfg = load_config(root)
rel = str(cfg.get("hotmail_accounts_file") or "mail_credentials.txt")
target = ensure_under(root, (root / rel).resolve() if not Path(rel).is_absolute() else Path(rel))
# Force under root even if absolute path outside
if root.resolve() not in target.parents and target != root.resolve():
target = root / "mail_credentials.txt"
text, norm_stats = normalize_credential_text(content)
parsed_lines = [ln for ln in text.splitlines() if ln.strip() and not ln.strip().startswith(("#", "//"))]
existing = _mail_pool_email_set(target) if target.is_file() else set()
pool_before = len(existing)
to_write: list[str] = []
new_emails: list[str] = []
dup_emails: list[str] = []
seen_batch: set[str] = set()
for ln in parsed_lines:
item = parse_credential_line(ln)
if not item:
continue
key = item.email.strip().lower()
if key in seen_batch:
dup_emails.append(item.email)
continue
seen_batch.add(key)
if mode == "append" and key in existing:
dup_emails.append(item.email)
continue
to_write.append(ln)
new_emails.append(item.email)
write_body = ""
if to_write:
write_body = "\n".join(to_write)
if not write_body.endswith("\n"):
write_body += "\n"
# replace + zero valid credentials would truncate the pool to empty. A .bak is
# taken below, but the UI only reports "未导入(格式无效)" — the user would not
# know the pool was wiped. Refuse instead; append never truncates so it is exempt.
if mode == "replace" and not write_body and target.is_file():
raise ValueError(
f"replace 模式解析出 0 条有效凭证,将清空邮箱池(当前 {pool_before} 个)——已拒绝。"
f"请检查格式(四段 ---- / JSON / CSV / 管道分隔),或改用 append。"
)
backup = None
if target.is_file() and (mode == "replace" or write_body):
bak = target.with_name(target.name + f".bak-web-{time.strftime('%Y%m%d_%H%M%S')}")
shutil.copy2(target, bak)
backup = str(bak)
if mode == "replace" or not target.is_file():
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(write_body, encoding="utf-8")
elif write_body:
with target.open("a", encoding="utf-8") as f:
f.write(write_body)
pool_after = len(_mail_pool_email_set(target)) if target.is_file() else 0
lines_written = len(to_write)
skipped = int(norm_stats.get("skipped") or 0)
# batch-internal dups counted in duplicate
duplicate = len(dup_emails)
formats = {
"json_objects": int(norm_stats.get("json_objects") or 0),
"csv_rows": int(norm_stats.get("csv_rows") or 0),
}
summary = _summarize_mail_import(
mode=mode,
parsed=len(parsed_lines),
new=lines_written,
duplicate=duplicate,
skipped=skipped,
pool_before=pool_before,
pool_after=pool_after,
sample_new=new_emails,
formats=formats,
)
# status for UI: success | partial | empty
if lines_written > 0 and (duplicate or skipped):
status = "partial"
elif lines_written > 0:
status = "success"
else:
status = "empty"
return {
"ok": True,
"status": status,
"summary": summary,
"path": str(target),
"backup": backup,
"mode": mode,
"lines_written": lines_written,
"parsed": len(parsed_lines),
"new": lines_written,
"duplicate": duplicate,
"skipped": skipped,
"pool_before": pool_before,
"pool_after": pool_after,
"new_emails": new_emails[:20],
"duplicate_emails": dup_emails[:20],
"normalized": norm_stats,
"formats": formats,
}
def import_auths(
root: Path,
src_dir: Path,
*,
no_remote: bool = True,
) -> dict[str, Any]:
src = ensure_under(root, src_dir)
if not src.is_dir():
raise ValueError(f"auth src is not a directory: {src}")
script = root / "scripts" / "import_cpa_auth_dir.py"
if not script.is_file():
raise FileNotFoundError(str(script))
argv = [sys.executable, str(script), "--src", str(src)]
if no_remote:
argv.append("--no-remote")
proc = subprocess.run(
argv,
cwd=str(root),
capture_output=True,
text=True,
timeout=3600,
)
return {
"exit": proc.returncode,
"stdout": (proc.stdout or "")[-4000:],
"stderr": (proc.stderr or "")[-2000:],
"src": str(src),
"no_remote": no_remote,
"ok": proc.returncode == 0,
}
def import_pack(root: Path, zip_path: Path, *, apply: bool = False) -> dict[str, Any]:
zpath = ensure_under(root, zip_path)
extract_to = staging_dir(root) / f"pack_{int(time.time())}"
extract_to.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(zpath, "r") as zf:
safe_extract_zip(zf, extract_to)
found = {
"config": next(extract_to.rglob("config.json"), None),
"nodes": next(extract_to.rglob("nodes.json"), None),
"mail": next(
(
p
for p in extract_to.rglob("*")
if p.is_file() and p.name in {"mail_credentials.txt", "mail_credentials.example.txt"}
),
None,
),
}
plan = {k: str(v) if v else None for k, v in found.items()}
applied: dict[str, str] = {}
if apply:
if found["config"]:
dest = root / "config.json"
if dest.is_file():
shutil.copy2(dest, dest.with_name(f"config.json.bak-web-pack-{time.strftime('%Y%m%d_%H%M%S')}"))
shutil.copy2(found["config"], dest)
applied["config"] = str(dest)
if found["nodes"]:
dest = root / "nodes.json"
if dest.is_file():
shutil.copy2(dest, dest.with_name(f"nodes.json.bak-web-pack-{time.strftime('%Y%m%d_%H%M%S')}"))
shutil.copy2(found["nodes"], dest)
applied["nodes"] = str(dest)
if found["mail"]:
dest = root / "mail_credentials.txt"
if dest.is_file():
shutil.copy2(dest, dest.with_name(f"mail_credentials.txt.bak-web-pack-{time.strftime('%Y%m%d_%H%M%S')}"))
shutil.copy2(found["mail"], dest)
applied["mail"] = str(dest)
return {
"ok": True,
"extract_to": str(extract_to),
"plan": plan,
"applied": applied,
"apply": apply,
}
+339
View File
@@ -0,0 +1,339 @@
"""Mail pool probe/quarantine ops for the control plane UI."""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from apps.control_api.config_io import enrich_config_from_env, load_config
from mail_pool_probe import (
QUARANTINABLE_STATUSES,
compact_pool,
dead_archive_path,
is_quarantinable,
pool_stats,
probe_sample,
quarantine,
resolve_pool_path,
)
def _live_path(root: Path) -> Path:
"""Resolve pool path; confine writes under project root (match import_mail).
Env ``HOTMAIL_ACCOUNTS_FILE`` absolute path outside root is allowed only if
the file already exists (ops override). Relative paths that escape root are
forced back to ``root/mail_credentials.txt``.
"""
root_r = root.resolve()
cfg = load_config(root)
cfg_path = str(cfg.get("hotmail_accounts_file") or "").strip() or None
path = resolve_pool_path(root, config_path=cfg_path)
try:
path.resolve().relative_to(root_r)
return path.resolve()
except ValueError:
# Outside root
if path.is_absolute() and path.is_file():
# Explicit existing absolute (env) — allow read/probe/quarantine there
return path.resolve()
return root_r / "mail_credentials.txt"
def get_pool_stats(root: Path) -> dict[str, Any]:
live = _live_path(root)
dead = dead_archive_path(live)
return pool_stats(live, dead_path=dead)
def probe_mail(
root: Path,
*,
domains: list[str] | None = None,
limit: int = 30,
seed: int | None = None,
offset: int | None = None,
concurrency: int = 4,
wall_seconds: float = 90.0,
) -> dict[str, Any]:
live = _live_path(root)
if not live.is_file():
raise FileNotFoundError(f"mail credentials file not found: {live}")
return probe_sample(
live,
domains=domains,
limit=limit,
seed=seed,
offset=offset,
concurrency=concurrency,
writeback_rotated=True,
wall_seconds=wall_seconds,
)
def compact_mail(
root: Path,
*,
dry_run: bool = False,
drop_invalid: bool = True,
drop_comments: bool = False,
) -> dict[str, Any]:
"""Dedupe + optional junk strip for the live mail pool (backup first)."""
live = _live_path(root)
if not live.is_file():
raise FileNotFoundError(f"mail credentials file not found: {live}")
return compact_pool(
live,
dry_run=dry_run,
drop_invalid=drop_invalid,
drop_comments=drop_comments,
)
def quarantine_mail(
root: Path,
emails: list[str],
*,
reason: str = "quarantine",
require_quarantinable_from: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Quarantine explicit emails.
If ``require_quarantinable_from`` is provided (last probe rows), only emails
whose status is in QUARANTINABLE_STATUSES are accepted; others are reported
in ``skipped_not_quarantinable``. Default (API path) still accepts the
explicit list — UI only sends quarantinable rows.
"""
if not emails:
raise ValueError("emails must be a non-empty list")
live = _live_path(root)
if not live.is_file():
raise FileNotFoundError(f"mail credentials file not found: {live}")
clean = [e.strip() for e in emails if e and str(e).strip()]
if not clean:
raise ValueError("emails must be a non-empty list")
skipped: list[str] = []
if require_quarantinable_from is not None:
allowed = {
str(r.get("email") or "").strip().lower()
for r in require_quarantinable_from
if is_quarantinable(str(r.get("status") or ""))
}
kept = []
for e in clean:
if e.lower() in allowed:
kept.append(e)
else:
skipped.append(e)
clean = kept
if not clean:
raise ValueError(
"no quarantinable emails in selection "
f"(allowed statuses: {sorted(QUARANTINABLE_STATUSES)})"
)
out = quarantine(live, clean, reason=reason or "quarantine")
if skipped:
out["skipped_not_quarantinable"] = skipped
return out
# Browser-like UA: bare urllib / Python-urllib/* is blocked by Cloudflare Error 1010
# on temp-mail Workers (edge bot signature). Keep a stable Chrome desktop string.
_CF_DOMAINS_USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/149.0.0.0 Safari/537.36"
)
# cloudflare_temp_email public settings (no address JWT). ``/api/domains`` is
# address-authed and returns 401 "Invalid address credential" without a JWT.
_CF_OPEN_SETTINGS_PATH = "/open_api/settings"
def _pick_list_payload(data: Any) -> list[Any]:
if isinstance(data, list):
return data
if isinstance(data, dict):
for key in (
"results",
"hydra:member",
"data",
"domains",
"defaultDomains",
"messages",
):
val = data.get(key)
if isinstance(val, list):
return val
nested = data.get("data")
if isinstance(nested, dict):
for key in ("results", "domains", "defaultDomains", "messages"):
val = nested.get(key)
if isinstance(val, list):
return val
return []
def _one_domain_name(item: Any) -> str:
if isinstance(item, str):
name = item.strip()
elif isinstance(item, dict):
name = ""
for key in ("domain", "name", "address"):
raw = item.get(key)
if not raw:
continue
name = str(raw).strip()
break
else:
name = ""
if not name:
return ""
if "@" in name:
name = name.rsplit("@", 1)[-1].strip()
return name
def _normalize_domain_names(items: list[Any]) -> list[str]:
out: list[str] = []
seen: set[str] = set()
for item in items:
name = _one_domain_name(item)
if not name:
continue
low = name.lower()
if low in seen:
continue
seen.add(low)
out.append(name)
return out
def _cf_get_json(url: str, headers: dict[str, str], *, timeout: float = 15) -> tuple[int, Any]:
"""GET JSON; raise RuntimeError with short body on HTTP/URL failure."""
req = Request(url, headers=headers, method="GET")
try:
with urlopen(req, timeout=timeout) as resp:
raw = resp.read().decode("utf-8", errors="replace")
status = int(getattr(resp, "status", 200) or 200)
except HTTPError as exc:
body = ""
try:
body = exc.read().decode("utf-8", errors="replace")[:200]
except Exception:
body = str(exc.reason or exc)
raise RuntimeError(f"Cloudflare domains HTTP {exc.code}: {body}") from exc
except URLError as exc:
raise RuntimeError(f"Cloudflare domains 请求失败: {exc.reason}") from exc
try:
data = json.loads(raw) if raw else []
except json.JSONDecodeError as exc:
raise RuntimeError("Cloudflare domains 返回非 JSON") from exc
return status, data
def list_cloudflare_domains(root: Path) -> dict[str, Any]:
"""Fetch domain list from the configured Cloudflare temp-mail Worker.
Uses saved ``cloudflare_api_base`` / ``cloudflare_api_key`` /
``cloudflare_auth_mode`` / ``cloudflare_path_domains`` from config (+ .env
enrich for non-secret base). Never returns the API key.
Always sends a browser User-Agent (CF Error 1010 otherwise). When the
configured domains path returns 401/403 (typical for cloudflare_temp_email
``/api/domains`` without an address JWT), falls back to public
``/open_api/settings`` which exposes ``domains`` / ``defaultDomains``.
"""
cfg = enrich_config_from_env(root, load_config(root))
api_base = str(cfg.get("cloudflare_api_base") or os.environ.get("CLOUDFLARE_API_BASE") or "").strip().rstrip("/")
if not api_base:
raise ValueError("cloudflare_api_base 未配置(资源页 Cloudflare 面板填写后保存)")
api_key = str(cfg.get("cloudflare_api_key") or os.environ.get("CLOUDFLARE_API_KEY") or "").strip()
mode = str(
cfg.get("cloudflare_auth_mode")
or os.environ.get("CLOUDFLARE_AUTH_MODE")
or "bearer"
).strip().lower() or "bearer"
path = str(cfg.get("cloudflare_path_domains") or "/domains").strip() or "/domains"
if not path.startswith("/"):
path = "/" + path
headers: dict[str, str] = {
"Accept": "application/json",
"User-Agent": _CF_DOMAINS_USER_AGENT,
}
params: dict[str, str] = {}
if api_key:
if mode == "x-api-key":
headers["X-API-Key"] = api_key
elif mode == "query-key":
params["key"] = api_key
elif mode != "none":
headers["Authorization"] = f"Bearer {api_key}"
url = f"{api_base}{path}"
if params:
url = f"{url}?{urlencode(params)}"
primary_err: Exception | None = None
status = 0
data: Any = []
used_path = path
try:
status, data = _cf_get_json(url, headers)
except RuntimeError as exc:
primary_err = exc
msg = str(exc)
# 401 address-auth / 403 edge or app deny → public open settings
if "HTTP 401" not in msg and "HTTP 403" not in msg:
raise
domains = _normalize_domain_names(_pick_list_payload(data)) if not primary_err else []
# Fallback: cloudflare_temp_email public settings (no JWT).
need_fallback = primary_err is not None or not domains
if need_fallback and path.rstrip("/") != _CF_OPEN_SETTINGS_PATH.rstrip("/"):
open_url = f"{api_base}{_CF_OPEN_SETTINGS_PATH}"
# Public endpoint: drop address/admin auth headers; keep UA + Accept.
open_headers = {
"Accept": "application/json",
"User-Agent": _CF_DOMAINS_USER_AGENT,
}
try:
status, data = _cf_get_json(open_url, open_headers)
domains = _normalize_domain_names(_pick_list_payload(data))
used_path = _CF_OPEN_SETTINGS_PATH
primary_err = None
except RuntimeError as fallback_exc:
if primary_err is not None:
raise primary_err from fallback_exc
raise
if primary_err is not None:
raise primary_err
if not domains:
raise RuntimeError(
f"Cloudflare domains 为空(path={used_path})。"
"检查 Worker 是否暴露 /open_api/settings 或配置正确的 domains 路径/凭证"
)
selected_raw = str(cfg.get("defaultDomains") or "")
selected = [x.strip() for x in selected_raw.replace(",", ",").split(",") if x.strip()]
return {
"ok": True,
"api_base": api_base,
"path": used_path,
"status": status,
"count": len(domains),
"domains": domains,
"selected": selected,
"has_api_key": bool(api_key),
}
File diff suppressed because it is too large Load Diff
+57
View File
@@ -0,0 +1,57 @@
"""Overview aggregates for the control plane."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
def count_product_ok(root: Path) -> int:
"""Count xai-*.json under cpa_auths with both access_token and refresh_token."""
d = root / "cpa_auths"
if not d.is_dir():
return 0
n = 0
for f in d.glob("xai-*.json"):
try:
data = json.loads(f.read_text(encoding="utf-8"))
except Exception:
continue
if not isinstance(data, dict):
continue
at = data.get("access_token")
rt = data.get("refresh_token")
if isinstance(at, str) and at and isinstance(rt, str) and rt:
n += 1
return n
def build_overview(root: Path, run_summary: dict[str, Any] | None = None) -> dict[str, Any]:
run = run_summary
if run is None:
try:
from apps.control_api.runs import run_status
run = run_status(root)
except Exception:
run = None
nodes_summary: dict[str, Any] | None = None
try:
from apps.control_api.nodes_ops import list_catalog
cat = list_catalog(root)
nodes_summary = {
"total": cat.get("total"),
"enabled": cat.get("enabled"),
"healthy": cat.get("healthy"),
"path": cat.get("path"),
}
except Exception:
nodes_summary = None
return {
"project_root": str(root),
"product_ok": count_product_ok(root),
"run": run,
"nodes": nodes_summary,
}
+67
View File
@@ -0,0 +1,67 @@
"""Password hashing (stdlib scrypt) for control-plane operators."""
from __future__ import annotations
import base64
import hashlib
import hmac
import secrets
_SCRYPT_N = 2**14
_SCRYPT_R = 8
_SCRYPT_P = 1
_DKLEN = 32
def hash_password(password: str) -> str:
if not password:
raise ValueError("password must be non-empty")
salt = secrets.token_bytes(16)
digest = hashlib.scrypt(
password.encode("utf-8"),
salt=salt,
n=_SCRYPT_N,
r=_SCRYPT_R,
p=_SCRYPT_P,
dklen=_DKLEN,
)
return "scrypt${}${}${}".format(
base64.urlsafe_b64encode(salt).decode("ascii").rstrip("="),
f"n={_SCRYPT_N},r={_SCRYPT_R},p={_SCRYPT_P}",
base64.urlsafe_b64encode(digest).decode("ascii").rstrip("="),
)
def _b64decode(data: str) -> bytes:
pad = "=" * (-len(data) % 4)
return base64.urlsafe_b64decode(data + pad)
def verify_password(password: str, encoded: str) -> bool:
if not password or not encoded:
return False
try:
scheme, salt_b64, params, dig_b64 = encoded.split("$", 3)
except ValueError:
return False
if scheme != "scrypt":
return False
try:
parts = dict(p.split("=", 1) for p in params.split(","))
n = int(parts.get("n", _SCRYPT_N))
r = int(parts.get("r", _SCRYPT_R))
p = int(parts.get("p", _SCRYPT_P))
salt = _b64decode(salt_b64)
expected = _b64decode(dig_b64)
digest = hashlib.scrypt(
password.encode("utf-8"),
salt=salt,
n=n,
r=r,
p=p,
dklen=len(expected) or _DKLEN,
)
except Exception:
return False
return hmac.compare_digest(digest, expected)
+235
View File
@@ -0,0 +1,235 @@
"""In-memory + on-disk registry of control-plane started runs."""
from __future__ import annotations
import fcntl
import json
import os
import signal
import time
from pathlib import Path
from typing import Any
_LOCK = Path("/tmp/grok_batch_supervisor.lock")
_LOCK_PID = Path("/tmp/grok_batch_supervisor.lock.pid")
class ProcessRegistry:
def __init__(self, root: Path) -> None:
self.root = root
self.path = root / "logs" / "control_api_runs.json"
self._current: dict[str, Any] | None = None
self._load()
def _load(self) -> None:
if not self.path.is_file():
return
try:
data = json.loads(self.path.read_text(encoding="utf-8"))
except Exception:
return
if isinstance(data, dict) and data.get("current"):
self._current = data["current"]
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
payload = {"current": self._current, "updated_at": time.time()}
tmp = self.path.with_suffix(".json.tmp")
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
tmp.replace(self.path)
def register(self, run_id: str, pid: int, kind: str, meta: dict[str, Any]) -> None:
self._current = {
"run_id": run_id,
"pid": int(pid),
"kind": kind,
"meta": meta,
"started_at": time.time(),
}
self._save()
def current(self) -> dict[str, Any] | None:
self.clear_if_dead()
return self._current
def clear(self) -> None:
self._current = None
self._save()
@staticmethod
def _reap_children() -> None:
"""Non-blocking reap of any exited children (zombies from Popen).
control_api starts supervisors with Popen and never waits; when the
child exits immediately (e.g. lock held), it becomes a zombie still
owned by control_api. kill(pid, 0) returns True for zombies, so the
registry would stay stuck forever unless we reap + treat Z as dead.
"""
try:
while True:
wpid, _st = os.waitpid(-1, os.WNOHANG)
if wpid <= 0:
break
except ChildProcessError:
# No children — normal when registry pid is not ours.
pass
except OSError:
pass
@staticmethod
def _pid_is_zombie(pid: int) -> bool:
"""Linux /proc: state 'Z' means zombie (still in table, not runnable)."""
try:
raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")
except (FileNotFoundError, PermissionError, OSError):
return False
# comm may contain spaces/parens; state is the first token after last ')'
rparen = raw.rfind(")")
if rparen < 0:
return False
fields = raw[rparen + 2 :].split()
return bool(fields) and fields[0] == "Z"
@staticmethod
def pid_alive(pid: int) -> bool:
if pid <= 0:
return False
# Best-effort: if this is our zombie child, reap it so the pid vanishes.
ProcessRegistry._reap_children()
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
# Exists but not signalable — treat as alive (not our zombie).
return True
# Zombies still pass kill(0); they are not a live supervisor.
if ProcessRegistry._pid_is_zombie(pid):
return False
return True
def clear_if_dead(self) -> None:
if not self._current:
return
pid = int(self._current.get("pid") or 0)
if not self.pid_alive(pid):
self._current = None
self._save()
def supervisor_lock_pid() -> int | None:
if not _LOCK_PID.is_file():
return None
try:
raw = _LOCK_PID.read_text(encoding="utf-8").strip()
pid = int(raw)
except Exception:
return None
if ProcessRegistry.pid_alive(pid):
return pid
return None
def supervisor_flock_busy() -> bool:
"""True if another process currently holds the exclusive flock on the lock file.
Complements ``supervisor_lock_pid``: after a batch exits, ``.lock.pid`` is often
stale while a *leaked* holder (e.g. mihomo inheriting fd 9 from preflight restart)
still keeps the flock. Probing the flock itself catches that case.
"""
try:
fd = os.open(str(_LOCK), os.O_RDWR | os.O_CREAT, 0o644)
except OSError:
return False
try:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
except OSError:
return False
try:
fcntl.flock(fd, fcntl.LOCK_UN)
except OSError:
pass
return False
finally:
try:
os.close(fd)
except OSError:
pass
def supervisor_lock_held() -> bool:
"""True if a live supervisor is indicated by lock.pid **or** the flock is busy."""
if supervisor_lock_pid() is not None:
return True
return supervisor_flock_busy()
def _signal_tree(pid: int, sig: int, *, process_group: bool) -> str:
"""Deliver *sig* to the process group when possible, else the single pid.
Control-started runs use ``start_new_session=True``, so the registered pid is
the session/group leader and ``killpg`` reaps chrome/xvfb/register children.
External flock supervisors (``batch_dc1k_ns``) are often **not** the group
leader: their pid != pgid. On Linux ``killpg(non_leader_pid, …)`` raises
``ProcessLookupError`` (ESRCH) even while that pid is still alive. Treating
that as "already dead" makes ``/api/runs/stop`` report success while the
batch keeps running. Resolve the real pgid via ``getpgid`` first; if group
delivery still fails and the pid is alive, fall back to single-pid signal.
"""
if process_group and pid > 0:
pgid = pid
try:
pgid = int(os.getpgid(pid))
except (ProcessLookupError, PermissionError, OSError):
pgid = pid
try:
os.killpg(pgid, sig)
return "pg"
except ProcessLookupError:
# ESRCH on killpg is ambiguous: real missing group OR bad pgid.
# Only re-raise (→ already dead) when the target pid itself is gone.
if not ProcessRegistry.pid_alive(pid):
raise
# fall through to single-pid
except (PermissionError, OSError):
pass
os.kill(pid, sig)
return "pid"
def stop_pid(
pid: int,
grace_sec: float = 10.0,
*,
process_group: bool = True,
) -> dict[str, Any]:
"""SIGTERM then optional SIGKILL.
Prefer process-group delivery (``killpg``) so supervisor children started under
a new session are not left orphaned. Falls back to the single pid when the
target is not a group leader (common for external lock-only runs).
"""
if pid <= 0:
return {"ok": False, "detail": "invalid pid"}
if not ProcessRegistry.pid_alive(pid):
return {"ok": True, "detail": "already dead", "pid": pid, "mode": "none"}
try:
mode = _signal_tree(pid, signal.SIGTERM, process_group=process_group)
except ProcessLookupError:
return {"ok": True, "detail": "already dead", "pid": pid, "mode": "none"}
deadline = time.time() + grace_sec
while time.time() < deadline:
if not ProcessRegistry.pid_alive(pid):
return {"ok": True, "detail": "terminated", "pid": pid, "mode": mode}
time.sleep(0.2)
if ProcessRegistry.pid_alive(pid):
try:
mode = _signal_tree(pid, signal.SIGKILL, process_group=process_group)
except ProcessLookupError:
pass
return {"ok": True, "detail": "killed", "pid": pid, "mode": mode}
return {"ok": True, "detail": "terminated", "pid": pid, "mode": mode}
+654
View File
@@ -0,0 +1,654 @@
"""Parse supervisor / register_cli logs into human-readable run progress."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
# Avoid matching gained_complete=N (must not start mid-token).
_COMPLETE_RE = re.compile(r"(?<![A-Za-z0-9_])complete=(\d+)")
_ZERO_RE = re.compile(r"consecutive_zero=(\d+)")
_ZERO_SHORT_RE = re.compile(r"\bzero=(\d+)")
_SUB_RE = re.compile(r"sub=(\d+)")
_CHUNK_RE = re.compile(r"chunk=(\d+)")
_ATTEMPT_RE = re.compile(r"attempt=(\d+)")
_GAINED_RE = re.compile(r"gained_complete=(\d+)")
_PLUS_RE = re.compile(r"\+\s*(\d+)/(\d+)")
_ACCOUNTS_RE = re.compile(r"accounts=(\d+)")
_EXIT_RE = re.compile(r"exit=(\d+)")
_MODE_RE = re.compile(r"mode=(ordinary|residential)")
_GOAL_RE = re.compile(r"goal_complete=(\d+)")
_TARGET_NEW_RE = re.compile(r"target_new=(\d+)")
_BASELINE_RE = re.compile(
r"baseline\s+(?:total=(\d+)\s+)?complete=(\d+)(?:\s+accounts=(\d+))?(?:\s+goal_complete=(\d+))?"
)
_SUB_LOG_RE = re.compile(r"log=(logs/\S+\.log)")
_SUMMARY_RE = re.compile(r"SUMMARY_JSON\s+(\{.*\})\s*$")
_WROTE_RE = re.compile(r"wrote\s+(\S+xai-\S+\.json)", re.I)
_EMAIL_RE = re.compile(r"[\w.+-]+@[\w.-]+\.\w+")
# Ordered from late → early so first match on reversed lines wins.
_PHASE_RULES: list[tuple[str, str, str]] = [
# Batch-end inject only — do NOT match SUMMARY_JSON keys like remote_inject_ok.
(
r"batch-end import|batch_end_inject|CPA import start|tebi注入开始|\[batch-end\]",
"batch_end_inject",
"批末 CPA 注入 / 归档",
),
(
r"supervisor done|hit_target|goal reached|goal_complete reached",
"done",
"批次结束",
),
(
r"SUMMARY_JSON|=== 完成",
"sub_summary",
"子批汇总(reg/mint 统计)",
),
(
r"mint.*ok|token_ok|CPA token|access_token|refresh_token|browser mint|mint_success|"
r"open device url|oauth poll|cookie inject|mint_method|\[cpa\].*device",
"mint",
"Mint:写 access+refresh 到 cpa_auths",
),
(
r"OTP|验证码|mail_code|extract_otp|邮箱验证",
"otp",
"邮箱 OTP 验证",
),
(
r"Turnstile|cf-turnstile|token_len=0|卡住 fail-fast|pre-submit",
"turnstile",
"Cloudflare Turnstile 人机验证",
),
(
r"完成注册|sign-up|signup|create_account|profile|givenName|familyName|您正在登录",
"register_form",
"填写/提交注册表单",
),
(
r"browser_boot|Chromium|xvfb|create_browser|ERR_CONNECTION",
"browser_boot",
"启动浏览器 / 代理连通",
),
(
r"clash_preflight|preflight|probe_clash|force_clash|rotate|switch.*node|NODE_SCORE",
"node_rotate",
"节点测活 / 换路 / 打分",
),
(
r"\[supervisor\].*chunk=|sub=\d+ chunk=",
"sub_start",
"启动子批 register_cli",
),
(
r"baseline|goal_complete|CPA_PROBE_CHAT",
"batch_start",
"批次启动 / 基线统计",
),
]
def _tail_text(path: Path | None, max_bytes: int = 120_000) -> str:
if path is None or not path.is_file():
return ""
try:
size = path.stat().st_size
with path.open("rb") as f:
if size > max_bytes:
f.seek(-max_bytes, 2)
data = f.read()
return data.decode("utf-8", errors="replace")
except Exception:
return ""
def _head_text(path: Path | None, max_bytes: int = 16_384) -> str:
"""Read start of supervisor log (baseline/goal_complete live only in header)."""
if path is None or not path.is_file():
return ""
try:
with path.open("rb") as f:
data = f.read(max_bytes)
return data.decode("utf-8", errors="replace")
except Exception:
return ""
def _run_tag_from_sup(sup_log: Path | None, sup_text: str) -> str | None:
"""Derive batch run tag so we only consider this run's sub logs.
Supervisor files are `{tag}.supervisor.log`; sub logs are `{tag}.subN_TS.log`.
"""
if sup_log is not None:
name = sup_log.name
if name.endswith(".supervisor.log"):
return name[: -len(".supervisor.log")]
for line in reversed(sup_text.splitlines()):
m = _SUB_LOG_RE.search(line)
if not m:
continue
leaf = Path(m.group(1)).name
m2 = re.match(r"(.+)\.sub\d+", leaf)
if m2:
return m2.group(1)
return None
def _mtime(path: Path) -> float:
try:
return path.stat().st_mtime
except OSError:
return 0.0
def _latest_sub_log(
root: Path, sup_text: str, *, sup_log: Path | None = None
) -> Path | None:
"""Pick the worker log for the *currently running* sub-batch.
Supervisor only emits `log=` **after** a sub exits. Preferring that path
during the next sub pins the UI on the finished SUMMARY_JSON (子批汇总)
while the live sub keeps writing a newer `*.subN_*.log`. Always prefer the
newest mtime sub log for this run tag; fall back to explicit log= only when
no newer candidate exists.
"""
logs = root / "logs"
if not logs.is_dir():
return None
tag = _run_tag_from_sup(sup_log, sup_text)
cands: list[Path] = []
if tag:
cands = list(logs.glob(f"{tag}.sub*.log"))
if not cands:
# Cross-run fallback (smoke / ad-hoc): any sub log by mtime.
cands = list(logs.glob("*.sub*_*.log")) or list(logs.glob("*.sub*.log"))
# De-dupe by resolved path.
uniq: dict[str, Path] = {}
for p in cands:
try:
uniq[str(p.resolve())] = p
except OSError:
uniq[str(p)] = p
cands = list(uniq.values())
if not cands:
for line in reversed(sup_text.splitlines()):
m = _SUB_LOG_RE.search(line)
if m:
p = root / m.group(1)
if p.is_file():
return p
return None
newest = max(cands, key=_mtime)
# If supervisor names an explicit log= that is still the newest (or only)
# finished artifact, keep it — otherwise the in-flight newer file wins.
for line in reversed(sup_text.splitlines()):
m = _SUB_LOG_RE.search(line)
if not m:
continue
p = root / m.group(1)
if p.is_file() and _mtime(p) >= _mtime(newest) - 0.001:
return p
break
return newest
def detect_phase(text: str) -> dict[str, str]:
"""Infer current phase from the most recent matching log lines."""
if not text:
return {
"phase": "idle",
"title": "空闲",
"detail": "无活动日志",
}
lines = [ln for ln in text.splitlines() if ln.strip()]
# Prefer structured fatal_reason inside recent SUMMARY_JSON (more precise than
# matching the whole JSON blob as sub_summary only).
for line in reversed(lines[-80:]):
if "SUMMARY_JSON" not in line or "fatal" not in line:
continue
if re.search(r'"fatal"\s*:\s*true', line) and re.search(
r"Turnstile|token_len=0|pre-submit", line, re.I
):
detail = line.strip()
if len(detail) > 220:
detail = detail[:217] + "…"
return {
"phase": "turnstile",
"title": "Cloudflare Turnstile 人机验证",
"detail": detail,
}
for line in reversed(lines[-400:]):
for pattern, phase, title in _PHASE_RULES:
if re.search(pattern, line, re.I):
detail = line.strip()
if len(detail) > 220:
detail = detail[:217] + "…"
return {"phase": phase, "title": title, "detail": detail}
last = lines[-1].strip() if lines else ""
return {
"phase": "running",
"title": "运行中",
"detail": last[:220] if last else "有日志但未识别步骤",
}
def _parse_summary_json(text: str) -> dict[str, Any] | None:
for line in reversed(text.splitlines()):
if "SUMMARY_JSON" not in line:
continue
m = _SUMMARY_RE.search(line.strip())
if not m:
# tolerate "SUMMARY_JSON {...}" mid-line
idx = line.find("{")
if idx < 0:
continue
try:
return json.loads(line[idx:])
except Exception:
continue
try:
return json.loads(m.group(1))
except Exception:
continue
return None
def _iter_summary_json(text: str) -> list[dict[str, Any]]:
"""Every SUMMARY_JSON object in `text`, in file order.
The supervisor log accumulates one SUMMARY_JSON line per finished sub
(register_cli copies its summary on exit). Aggregating them gives real
batch-level failure stats rather than a single sub snapshot.
"""
out: list[dict[str, Any]] = []
for line in text.splitlines():
if "SUMMARY_JSON" not in line:
continue
s = line.strip()
m = _SUMMARY_RE.search(s)
blob = None
if m:
blob = m.group(1)
else:
idx = s.find("{")
if idx >= 0:
blob = s[idx:]
if not blob:
continue
try:
obj = json.loads(blob)
except Exception:
continue
if isinstance(obj, dict) and obj.get("event") == "register_cli_summary":
out.append(obj)
return out
def _int(v: Any) -> int:
try:
return int(v or 0)
except Exception:
return 0
def build_batch_failures(sup_text: str, sub_text: str) -> dict[str, Any] | None:
"""Aggregate per-sub SUMMARY_JSON into batch-level failure stats.
Returns None when no summaries are present yet (batch just started), so
the UI can hide the card instead of showing an all-zero panel.
"""
subs = _iter_summary_json(sup_text)
# The live worker's own summary is only in the worker tail until it exits
# and the supervisor copies it. Include it so the freshest sub counts too.
worker = _iter_summary_json(sub_text)
if worker:
subs = subs + worker[-1:]
if not subs:
return None
agg = {
"subs": len(subs),
"reg_success": 0,
"reg_fail": 0,
"mint_fail": 0,
"mint_skip": 0,
"chat_denied": 0,
"chat_fail": 0,
"remote_inject_fail": 0,
"remote_live_fail": 0,
"fatal_subs": 0,
}
# Failure taxonomy buckets for the breakdown chart.
mint_reasons: dict[str, int] = {}
fatal_reasons: dict[str, int] = {}
for s in subs:
agg["reg_success"] += _int(s.get("reg_success"))
agg["reg_fail"] += _int(s.get("reg_fail"))
agg["mint_fail"] += _int(s.get("mint_fail"))
agg["mint_skip"] += _int(s.get("mint_skip"))
agg["chat_denied"] += _int(s.get("chat_denied"))
agg["chat_fail"] += _int(s.get("chat_fail"))
agg["remote_inject_fail"] += _int(s.get("remote_inject_fail"))
agg["remote_live_fail"] += _int(s.get("remote_live_fail"))
if s.get("fatal"):
agg["fatal_subs"] += 1
fr = str(s.get("fatal_reason") or "fatal").strip()[:80]
if fr:
fatal_reasons[fr] = fatal_reasons.get(fr, 0) + 1
mr = str(s.get("mint_fail_reason") or "").strip()[:80]
if mr and _int(s.get("mint_fail")):
mint_reasons[mr] = mint_reasons.get(mr, 0) + _int(s.get("mint_fail"))
attempts = agg["reg_success"] + agg["reg_fail"]
total_fail = (
agg["reg_fail"]
+ agg["mint_fail"]
+ agg["chat_fail"]
+ agg["remote_inject_fail"]
+ agg["remote_live_fail"]
)
agg["attempts"] = attempts
agg["total_fail"] = total_fail
agg["fail_rate"] = round(agg["reg_fail"] / attempts, 4) if attempts else 0.0
# Top-N breakdowns as sorted [label, count] lists for the UI.
def _top(d: dict[str, int], n: int = 5) -> list[list[Any]]:
return [[k, v] for k, v in sorted(d.items(), key=lambda kv: -kv[1])[:n]]
agg["mint_fail_reasons"] = _top(mint_reasons)
agg["fatal_reasons"] = _top(fatal_reasons)
# Per-sub reg_fail series for a trend sparkline.
agg["reg_fail_series"] = [_int(s.get("reg_fail")) for s in subs][-30:]
agg["reg_success_series"] = [_int(s.get("reg_success")) for s in subs][-30:]
return agg
def _parse_counters(text: str) -> dict[str, Any]:
complete = None
zero = None
sub = None
chunk = None
attempt = None
gained = None
target = None
gained_total = None
accounts = None
mode = None
exit_code = None
goal_complete = None
baseline_complete = None
target_new = None
for line in reversed(text.splitlines()):
if complete is None:
m = _COMPLETE_RE.search(line)
if m and "[supervisor]" in line:
complete = int(m.group(1))
if zero is None and "[supervisor]" in line:
m2 = _ZERO_RE.search(line)
if m2:
zero = int(m2.group(1))
else:
m3 = _ZERO_SHORT_RE.search(line)
if m3:
zero = int(m3.group(1))
if sub is None:
m = _SUB_RE.search(line)
if m and "[supervisor]" in line:
sub = int(m.group(1))
if chunk is None:
m = _CHUNK_RE.search(line)
if m:
chunk = int(m.group(1))
if attempt is None:
m = _ATTEMPT_RE.search(line)
if m and "[supervisor]" in line:
attempt = int(m.group(1))
if gained is None:
m = _GAINED_RE.search(line)
if m:
gained = int(m.group(1))
if target is None or gained_total is None:
m = _PLUS_RE.search(line)
if m:
gained_total = int(m.group(1))
target = int(m.group(2))
if accounts is None:
m = _ACCOUNTS_RE.search(line)
if m and "[supervisor]" in line:
accounts = int(m.group(1))
if mode is None:
m = _MODE_RE.search(line)
if m:
mode = m.group(1)
if exit_code is None and "sub=" in line and "exit=" in line:
m = _EXIT_RE.search(line)
if m:
exit_code = int(m.group(1))
if goal_complete is None:
m = _GOAL_RE.search(line)
if m:
goal_complete = int(m.group(1))
if target_new is None:
m = _TARGET_NEW_RE.search(line)
if m:
target_new = int(m.group(1))
if baseline_complete is None:
m = _BASELINE_RE.search(line)
if m:
baseline_complete = int(m.group(2))
if goal_complete is None and m.group(4):
goal_complete = int(m.group(4))
if all(
x is not None
for x in (complete, zero, sub, chunk, accounts, goal_complete, target)
):
break
# Prefer explicit target_new when +N/M not yet seen; keep +N/M as batch target.
if target is None and target_new is not None:
target = target_new
remain = None
if isinstance(complete, int) and isinstance(goal_complete, int):
remain = max(0, goal_complete - complete)
batch_remain = None
if isinstance(gained_total, int) and isinstance(target, int):
batch_remain = max(0, target - gained_total)
elif isinstance(target, int) and gained_total is None:
batch_remain = target
return {
"complete": complete,
"consecutive_zero": zero,
"sub": sub,
"chunk": chunk,
"attempt": attempt if attempt is not None else sub,
"gained_last_sub": gained,
"batch_gained": gained_total,
"target": target,
"target_new": target_new if target_new is not None else target,
"goal_complete": goal_complete,
"baseline_complete": baseline_complete,
"remain": remain,
"batch_remain": batch_remain,
"accounts": accounts,
"mode": mode,
"last_sub_exit": exit_code,
}
def build_timeline(sup_text: str, sub_text: str, *, limit: int = 24) -> list[dict[str, str]]:
"""Build a short human timeline from recent supervisor + sub lines."""
interesting = re.compile(
r"\[supervisor\]|SUMMARY_JSON|=== 完成|Fatal|FAIL-FAST|Turnstile|"
r"注册成功|token_ok|wrote |OTP|mint|preflight|clash|batch-end|"
r"gained_complete|browser_boot|FATAL",
re.I,
)
items: list[dict[str, str]] = []
for src, text in (("supervisor", sup_text), ("worker", sub_text)):
for line in text.splitlines():
if not interesting.search(line):
continue
phase = detect_phase(line)
items.append(
{
"source": src,
"phase": phase["phase"],
"title": phase["title"],
"line": line.strip()[:300],
}
)
return items[-limit:]
def build_progress(root: Path, *, sup_log: Path | None) -> dict[str, Any]:
"""Full progress payload for UI."""
sup_text = _tail_text(sup_log)
# Header has goal_complete / baseline / target_new; tail has live counters.
# Merge so reversed-line parse still prefers latest complete= while
# still seeing one-shot baseline fields from the start of the run.
head_text = _head_text(sup_log)
counters = _parse_counters((head_text + "\n" + sup_text).strip() if head_text else sup_text)
sub_path = _latest_sub_log(root, sup_text, sup_log=sup_log)
sub_text = _tail_text(sub_path)
# Phase must reflect the live worker. Supervisor tail often ends with the
# previous sub's SUMMARY_JSON (copied on exit) plus `sub=N chunk=` start —
# those late rules (sub_summary) would otherwise pin the UI on 子批汇总 for
# the entire next sub. Prefer worker-only when it has content; fall back to
# combined only when worker is empty / missing.
if sub_text.strip():
phase = detect_phase(sub_text)
# If worker is mid-flight but only has boot noise, allow supervisor
# batch-level phases (sub_start / batch_start / done / inject) when
# worker has no stronger in-account phase.
if phase["phase"] in ("idle", "running"):
sup_phase = detect_phase(sup_text)
if sup_phase["phase"] not in ("sub_summary", "idle"):
phase = sup_phase
else:
combined = (sup_text + "\n" + sub_text).strip()
phase = detect_phase(combined if combined else sup_text)
# SUMMARY_JSON is per finished sub. Prefer the active worker's own summary;
# supervisor copy is previous-sub history while a newer worker is mid-flight.
worker_summary = _parse_summary_json(sub_text)
sup_summary = _parse_summary_json(sup_text)
summary = worker_summary or sup_summary
# Stuck heuristics
stuck = False
stuck_reason = ""
zero = counters.get("consecutive_zero")
if isinstance(zero, int) and zero >= 4:
stuck = True
stuck_reason = f"连续 {zero} 个子批零产出"
if phase["phase"] == "turnstile":
stuck = True
stuck_reason = stuck_reason or "Turnstile 卡住 / 无 token"
# Only treat fatal from the current worker (or when we are still on
# sub_summary of that finished worker). A previous sub's fatal in the
# supervisor tail must not freeze the next live sub as stuck.
fatal_src = worker_summary
if fatal_src is None and phase["phase"] in ("sub_summary", "done", "batch_end_inject"):
fatal_src = sup_summary
if fatal_src and fatal_src.get("fatal"):
stuck = True
stuck_reason = str(fatal_src.get("fatal_reason") or "fatal")[:200]
recent_writes: list[str] = []
for line in (sub_text + "\n" + sup_text).splitlines():
m = _WROTE_RE.search(line)
if m:
recent_writes.append(m.group(1))
recent_writes = recent_writes[-5:]
steps = [
{
"id": "batch_start",
"title": "批次启动",
"desc": "基线 complete / goal / flock",
},
{
"id": "node_rotate",
"title": "节点测活/换路",
"desc": "Clash preflight 或 force next node",
},
{
"id": "sub_start",
"title": "子批启动",
"desc": "xvfb + register_cli chunk",
},
{
"id": "browser_boot",
"title": "浏览器启动",
"desc": "Chromium + 代理",
},
{
"id": "register_form",
"title": "注册表单",
"desc": "邮箱/密码/资料提交",
},
{
"id": "turnstile",
"title": "Turnstile",
"desc": "人机验证 token",
},
{
"id": "otp",
"title": "邮箱 OTP",
"desc": "收信解码验证码",
},
{
"id": "mint",
"title": "Mint 落盘",
"desc": "access+refresh → cpa_auths",
},
{
"id": "sub_summary",
"title": "子批汇总",
"desc": "SUMMARY_JSON / gained",
},
{
"id": "batch_end_inject",
"title": "批末注入",
"desc": "goal 达成后 CPA import",
},
]
phase_order = [s["id"] for s in steps]
cur = phase["phase"]
if cur in ("done", "idle", "running"):
active_idx = -1 if cur in ("done", "idle") else 2
else:
active_idx = phase_order.index(cur) if cur in phase_order else 2
for i, s in enumerate(steps):
if cur in ("done",):
s["state"] = "done"
elif active_idx < 0:
s["state"] = "pending"
elif i < active_idx:
s["state"] = "done"
elif i == active_idx:
s["state"] = "active"
else:
s["state"] = "pending"
return {
**counters,
"phase": phase["phase"],
"phase_title": phase["title"],
"phase_detail": phase["detail"],
"stuck": stuck,
"stuck_reason": stuck_reason,
"summary": summary,
"batch_failures": build_batch_failures(sup_text, sub_text),
"steps": steps,
"timeline": build_timeline(sup_text, sub_text),
"supervisor_log": str(sup_log) if sup_log else None,
"worker_log": str(sub_path) if sub_path else None,
"recent_writes": recent_writes,
"last_lines": (sup_text.splitlines()[-8:] if sup_text else []),
"worker_last_lines": (sub_text.splitlines()[-12:] if sub_text else []),
}
+47
View File
@@ -0,0 +1,47 @@
"""Simple in-process rate limiter for login attempts."""
from __future__ import annotations
import threading
import time
from collections import defaultdict
class LoginRateLimiter:
def __init__(self, *, max_failures: int = 8, window_seconds: int = 300) -> None:
self.max_failures = max_failures
self.window_seconds = window_seconds
self._lock = threading.Lock()
self._failures: dict[str, list[float]] = defaultdict(list)
def _prune(self, key: str, now: float) -> None:
cutoff = now - self.window_seconds
self._failures[key] = [t for t in self._failures[key] if t >= cutoff]
def is_blocked(self, key: str) -> bool:
now = time.time()
with self._lock:
self._prune(key, now)
return len(self._failures[key]) >= self.max_failures
def record_failure(self, key: str) -> None:
now = time.time()
with self._lock:
self._prune(key, now)
self._failures[key].append(now)
def clear(self, key: str) -> None:
with self._lock:
self._failures.pop(key, None)
def remaining_seconds(self, key: str) -> int:
now = time.time()
with self._lock:
self._prune(key, now)
if len(self._failures[key]) < self.max_failures:
return 0
oldest = min(self._failures[key])
return max(0, int(self.window_seconds - (now - oldest)) + 1)
login_limiter = LoginRateLimiter()
+32
View File
@@ -0,0 +1,32 @@
"""Account pool (cpa_auths product files) routes."""
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Query, status
from apps.control_api.accounts_ops import delete_account, list_accounts
from apps.control_api.settings import get_settings
router = APIRouter(tags=["accounts"])
@router.get("/api/accounts")
def get_accounts(
q: str = Query(default=""),
complete: str = Query(default=""),
page: int = Query(default=1, ge=1),
page_size: int = Query(default=50, ge=0, le=500),
) -> dict:
root = get_settings().project_root
return list_accounts(root, q=q, complete=complete, page=page, page_size=page_size)
@router.delete("/api/accounts/{name}")
def remove_account(name: str) -> dict:
root = get_settings().project_root
try:
return delete_account(root, name)
except FileNotFoundError:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="not found") from None
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
+106
View File
@@ -0,0 +1,106 @@
"""Login / logout / session me endpoints."""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
from apps.control_api.auth import auth_is_required, require_auth, session_username
from apps.control_api.rate_limit import login_limiter
from apps.control_api.schemas import LoginIn, LoginOut, MeOut
from apps.control_api.sessions import (
COOKIE_NAME,
mint_session_token,
session_cookie_kwargs,
)
from apps.control_api.settings import get_settings
from apps.control_api.users import authenticate, has_any_user, list_usernames
router = APIRouter(prefix="/api/auth", tags=["auth"])
def _client_key(request: Request, username: str) -> str:
host = request.client.host if request.client else "unknown"
return f"{host}|{(username or '').strip().lower()}"
@router.get("/me", response_model=MeOut)
def me(request: Request) -> MeOut:
s = get_settings()
user = session_username(request)
return MeOut(
authenticated=bool(user),
username=user,
auth_required=auth_is_required(s.project_root),
password_login_enabled=s.password_login_enabled,
token_auth_enabled=bool(s.token),
users_configured=has_any_user(s.project_root),
)
@router.post("/login", response_model=LoginOut)
def login(body: LoginIn, request: Request, response: Response) -> LoginOut:
s = get_settings()
if not s.password_login_enabled:
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="password login disabled")
if not s.session_secret:
# Ops-facing: tell operator how to fix without leaking secrets.
print(
"[control_api] login blocked: session secret missing "
f"(source={s.session_secret_source}); "
"set CONTROL_API_SESSION_SECRET or .control_api_session_secret",
flush=True,
)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=(
"session secret not configured — set CONTROL_API_SESSION_SECRET "
"or create .control_api_session_secret under project root "
"(or restart via scripts/run_control_api.sh)"
),
)
if not has_any_user(s.project_root):
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="no operators configured; set CONTROL_API_BOOTSTRAP_USER/PASSWORD once",
)
key = _client_key(request, body.username)
if login_limiter.is_blocked(key):
wait = login_limiter.remaining_seconds(key)
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"too many failed logins; retry in {wait}s",
headers={"Retry-After": str(max(1, wait))},
)
ok = authenticate(s.project_root, body.username, body.password)
if not ok:
login_limiter.record_failure(key)
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="invalid username or password")
login_limiter.clear(key)
username = body.username.strip()
token = mint_session_token(
secret=s.session_secret,
username=username,
ttl_seconds=s.session_ttl_seconds,
)
kw = session_cookie_kwargs(secure=s.cookie_secure, max_age=s.session_ttl_seconds)
response.set_cookie(value=token, **kw)
return LoginOut(ok=True, username=username)
@router.post("/logout", response_model=LoginOut)
def logout(response: Response) -> LoginOut:
s = get_settings()
response.delete_cookie(COOKIE_NAME, path="/")
# also clear with secure flag variants
response.delete_cookie(COOKIE_NAME, path="/", secure=s.cookie_secure)
return LoginOut(ok=True, username=None)
@router.get("/users", response_model=dict, dependencies=[Depends(require_auth)])
def users_list() -> dict:
"""List operator usernames (no hashes). Auth required."""
s = get_settings()
return {"users": list_usernames(s.project_root)}
+56
View File
@@ -0,0 +1,56 @@
"""Config GET/PUT routes."""
from __future__ import annotations
from fastapi import APIRouter
from apps.control_api.config_io import (
enrich_config_from_env,
load_config,
redact_config,
save_config,
)
from apps.control_api.schemas import ConfigOut, ConfigPutIn, ConfigPutOut
from apps.control_api.settings import get_settings
router = APIRouter(tags=["config"])
@router.get("/api/config", response_model=ConfigOut)
def get_config() -> ConfigOut:
"""Return config with blank operational fields filled from ``.env``.
Disk ``config.json`` stays as-is; response enrichment makes the console
show proxy/domains the batch actually uses when only ``.env`` has them.
"""
root = get_settings().project_root
data = enrich_config_from_env(root, load_config(root))
return ConfigOut(config=redact_config(data), path=str(root / "config.json"))
@router.put("/api/config", response_model=ConfigPutOut)
def put_config(body: ConfigPutIn) -> ConfigPutOut:
"""Persist config.json and mirror operational keys into ``.env``.
Batch supervisors load ``.env``; without this sync the console UI could
show hotmail while live register_cli still used a stale EMAIL_PROVIDER.
Sticky-empty (omit / keep prior): blank ``proxy`` and most other ops keys.
Clearable empty (intentional wipe): ``email_providers``, ``proxy_list``,
``defaultDomains`` — empty string or empty list writes through to config
and ``.env`` (e.g. ``DEFAULT_DOMAINS=``). Callers that must not clear
(Register page) simply omit those keys from the put payload.
"""
root = get_settings().project_root
result = save_config(root, body.config)
# Re-read disk after save, then enrich once and redact once (same as GET).
# Do not enrich from save_config's already-redacted payload.
enriched = enrich_config_from_env(root, load_config(root))
return ConfigPutOut(
ok=True,
backup=result.get("backup"),
changed_keys=list(result.get("changed_keys") or []),
changed_env_keys=list(result.get("changed_env_keys") or []),
env_backup=result.get("env_backup"),
config=redact_config(enriched),
)
+90
View File
@@ -0,0 +1,90 @@
"""Import multipart routes."""
from __future__ import annotations
import shutil
import zipfile
from pathlib import Path
from fastapi import APIRouter, File, Form, UploadFile
from apps.control_api.imports_ops import (
import_auths,
import_mail,
import_nodes,
import_pack,
safe_extract_zip,
save_upload,
staging_dir,
)
from apps.control_api.schemas import ImportResultOut
from apps.control_api.settings import get_settings
router = APIRouter(tags=["import"])
@router.post("/api/import/nodes", response_model=ImportResultOut)
async def post_import_nodes(
file: UploadFile = File(...),
dry_run: bool = Form(default=False),
replace: bool = Form(default=False),
) -> ImportResultOut:
s = get_settings()
data = await file.read()
path = save_upload(s.project_root, file.filename or "nodes.yaml", data, s.max_upload_bytes)
result = import_nodes(s.project_root, path, dry_run=dry_run, replace=replace)
return ImportResultOut(ok=bool(result.get("ok")), detail="nodes import", result=result)
@router.post("/api/import/mail", response_model=ImportResultOut)
async def post_import_mail(
content: str = Form(...),
mode: str = Form(default="append"),
) -> ImportResultOut:
if mode not in {"append", "replace"}:
raise ValueError("mode must be append or replace")
s = get_settings()
result = import_mail(s.project_root, content, mode=mode) # type: ignore[arg-type]
summary = str(result.get("summary") or "").strip() or "mail import"
# ok stays True for HTTP 200 so UI can render structured result; status field
# (success|partial|empty) drives toast kind.
return ImportResultOut(ok=True, detail=summary, result=result)
@router.post("/api/import/auths", response_model=ImportResultOut)
async def post_import_auths(
file: UploadFile = File(...),
no_remote: bool = Form(default=True),
) -> ImportResultOut:
"""Accept a zip of xai-*.json or a single json; extract to staging dir."""
s = get_settings()
data = await file.read()
path = save_upload(s.project_root, file.filename or "auths.zip", data, s.max_upload_bytes)
src_dir: Path
if path.suffix.lower() == ".zip" or zipfile.is_zipfile(path):
extract = staging_dir(s.project_root) / f"auths_{path.stem}"
if extract.exists():
shutil.rmtree(extract)
extract.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(path, "r") as zf:
safe_extract_zip(zf, extract)
src_dir = extract
else:
# single file → put in a dir
src_dir = staging_dir(s.project_root) / f"auths_one_{path.stem}"
src_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, src_dir / path.name)
result = import_auths(s.project_root, src_dir, no_remote=no_remote)
return ImportResultOut(ok=bool(result.get("ok")), detail="auths import", result=result)
@router.post("/api/import/pack", response_model=ImportResultOut)
async def post_import_pack(
file: UploadFile = File(...),
apply: bool = Form(default=False),
) -> ImportResultOut:
s = get_settings()
data = await file.read()
path = save_upload(s.project_root, file.filename or "pack.zip", data, s.max_upload_bytes)
result = import_pack(s.project_root, path, apply=apply)
return ImportResultOut(ok=True, detail="pack import", result=result)
+116
View File
@@ -0,0 +1,116 @@
"""Mail pool stats / probe / quarantine routes."""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from apps.control_api import mail_ops
from apps.control_api.settings import get_settings
router = APIRouter(tags=["mail"])
class MailProbeIn(BaseModel):
domains: list[str] = Field(default_factory=list)
# Per-wave cap (full pool = multi-wave via offset). 500 keeps one request
# under control_api request time without a job queue.
limit: int = Field(default=30, ge=1, le=500)
seed: int | None = None
# Sequential full-pool paging. When set, order is stable (no shuffle) and
# response carries next_offset/done for the UI/CLI to loop.
offset: int | None = Field(default=None, ge=0)
concurrency: int = Field(default=4, ge=1, le=8)
wall_seconds: float = Field(default=90.0, ge=5.0, le=600.0)
class MailQuarantineIn(BaseModel):
emails: list[str] = Field(min_length=1)
reason: str = Field(default="quarantine", max_length=128)
class MailCompactIn(BaseModel):
dry_run: bool = False
drop_invalid: bool = True
drop_comments: bool = False
def _http_from_exc(exc: Exception) -> HTTPException:
if isinstance(exc, FileNotFoundError):
return HTTPException(status_code=404, detail=str(exc))
if isinstance(exc, ValueError):
return HTTPException(status_code=400, detail=str(exc))
if isinstance(exc, RuntimeError):
return HTTPException(status_code=409, detail=str(exc))
return HTTPException(status_code=500, detail=str(exc))
@router.get("/api/mail/pool")
def api_mail_pool() -> dict[str, Any]:
root = get_settings().project_root
try:
return mail_ops.get_pool_stats(root)
except FileNotFoundError as exc:
raise _http_from_exc(exc) from exc
@router.post("/api/mail/probe")
def api_mail_probe(body: MailProbeIn) -> dict[str, Any]:
root = get_settings().project_root
domains = [d for d in (body.domains or []) if str(d).strip()] or None
try:
return mail_ops.probe_mail(
root,
domains=domains,
limit=body.limit,
seed=body.seed,
offset=body.offset,
concurrency=body.concurrency,
wall_seconds=body.wall_seconds,
)
except (FileNotFoundError, ValueError, RuntimeError) as exc:
raise _http_from_exc(exc) from exc
@router.post("/api/mail/quarantine")
def api_mail_quarantine(body: MailQuarantineIn) -> dict[str, Any]:
root = get_settings().project_root
emails = [e.strip() for e in body.emails if e and str(e).strip()]
if not emails:
raise HTTPException(status_code=400, detail="emails must be a non-empty list")
try:
return mail_ops.quarantine_mail(
root,
emails,
reason=(body.reason or "quarantine").strip() or "quarantine",
)
except (FileNotFoundError, ValueError) as exc:
raise _http_from_exc(exc) from exc
@router.post("/api/mail/compact")
def api_mail_compact(body: MailCompactIn | None = None) -> dict[str, Any]:
"""Dedupe live pool by email (first wins); optional drop invalid/comments."""
root = get_settings().project_root
body = body or MailCompactIn()
try:
return mail_ops.compact_mail(
root,
dry_run=bool(body.dry_run),
drop_invalid=bool(body.drop_invalid),
drop_comments=bool(body.drop_comments),
)
except (FileNotFoundError, ValueError) as exc:
raise _http_from_exc(exc) from exc
@router.get("/api/mail/cloudflare/domains")
def api_mail_cloudflare_domains() -> dict[str, Any]:
"""List domains from the configured Cloudflare temp-mail Worker."""
root = get_settings().project_root
try:
return mail_ops.list_cloudflare_domains(root)
except (ValueError, RuntimeError) as exc:
raise _http_from_exc(exc) from exc
+192
View File
@@ -0,0 +1,192 @@
"""Node catalog + Clash routes."""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Body, Query
from pydantic import BaseModel, Field
from apps.control_api import nodes_ops
from apps.control_api.settings import get_settings
router = APIRouter(tags=["nodes"])
class NodeAddIn(BaseModel):
url: str = Field(min_length=3, max_length=2000)
label: str = Field(default="", max_length=128)
tags: list[str] = Field(default_factory=list)
tier: int = Field(default=0, ge=0, le=1)
enabled: bool = True
class NodeTestIn(BaseModel):
ids: list[str] = Field(default_factory=list)
timeout: float = Field(default=12.0, ge=1.0, le=60.0)
limit: int = Field(default=50, ge=1, le=500)
class ClashTestIn(BaseModel):
names: list[str] = Field(default_factory=list)
timeout_ms: int = Field(default=5000, ge=500, le=30000)
limit: int = Field(default=40, ge=1, le=500)
class ClashSubImportIn(BaseModel):
url: str = Field(min_length=8, max_length=2000)
group: str = Field(default="🎯Grok注册", max_length=128)
groups: list[str] = Field(default_factory=list)
prefix: str = Field(default="SUB", max_length=32)
mode: str = Field(default="merge", max_length=32) # merge | replace_prefix
dry_run: bool = False
reload: bool = True
timeout: float = Field(default=25.0, ge=3.0, le=120.0)
max_proxies: int = Field(default=400, ge=1, le=2000)
class ClashDeletePrefixIn(BaseModel):
prefix: str = Field(min_length=1, max_length=32)
dry_run: bool = False
reload: bool = True
force: bool = False # required for protected prefixes (e.g. GVPS)
class ClashPruneUnhealthyIn(BaseModel):
prefix: str = Field(default="", max_length=32)
group: str = Field(default="🎯Grok注册", max_length=128)
timeout_ms: int = Field(default=4000, ge=500, le=30000)
# keep wall-clock under Cloudflare ~100s when console is proxied
limit: int = Field(default=120, ge=1, le=300)
dry_run: bool = False
reload: bool = True
delete_defs: bool = True # False = only strip from groups
class EnabledIn(BaseModel):
enabled: bool = True
@router.get("/api/nodes")
def get_nodes(
q: str = Query(default=""),
health: str = Query(default=""),
tier: str = Query(default=""),
enabled: str = Query(default=""),
page: int = Query(default=1, ge=1),
page_size: int = Query(default=50, ge=0, le=500),
sort: str = Query(default="priority"),
) -> dict[str, Any]:
root = get_settings().project_root
return nodes_ops.list_catalog(
root,
q=q,
health=health,
tier=tier if tier != "" else None,
enabled=enabled if enabled != "" else None,
page=page,
page_size=page_size,
sort=sort,
)
@router.post("/api/nodes")
def post_node(body: NodeAddIn) -> dict[str, Any]:
root = get_settings().project_root
return nodes_ops.add_catalog_node(
root,
url=body.url,
label=body.label,
tags=body.tags,
tier=body.tier,
enabled=body.enabled,
)
@router.delete("/api/nodes/{node_id}")
def delete_node(node_id: str) -> dict[str, Any]:
root = get_settings().project_root
return nodes_ops.delete_catalog_node(root, node_id)
@router.patch("/api/nodes/{node_id}")
def patch_node(node_id: str, body: EnabledIn) -> dict[str, Any]:
root = get_settings().project_root
return nodes_ops.set_catalog_enabled(root, node_id, body.enabled)
@router.post("/api/nodes/test")
def post_test_nodes(body: NodeTestIn | None = Body(default=None)) -> dict[str, Any]:
root = get_settings().project_root
body = body or NodeTestIn()
return nodes_ops.test_catalog_nodes(
root,
ids=body.ids or None,
timeout=body.timeout,
limit=body.limit,
)
@router.get("/api/nodes/clash")
def get_clash_nodes() -> dict[str, Any]:
root = get_settings().project_root
return nodes_ops.list_clash_nodes(root)
@router.post("/api/nodes/clash/test")
def post_clash_test(body: ClashTestIn | None = Body(default=None)) -> dict[str, Any]:
root = get_settings().project_root
body = body or ClashTestIn()
return nodes_ops.test_clash_nodes(
root,
names=body.names or None,
timeout_ms=body.timeout_ms,
limit=body.limit,
)
@router.post("/api/nodes/clash/import-url")
def post_clash_import_url(body: ClashSubImportIn) -> dict[str, Any]:
"""Fetch a Clash/airport subscription URL and merge into selected pool."""
root = get_settings().project_root
return nodes_ops.import_clash_subscription(
root,
url=body.url,
group=body.group,
groups=body.groups or None,
prefix=body.prefix,
mode=body.mode,
dry_run=body.dry_run,
reload=body.reload,
timeout=body.timeout,
max_proxies=body.max_proxies,
)
@router.post("/api/nodes/clash/delete-prefix")
def post_clash_delete_prefix(body: ClashDeletePrefixIn) -> dict[str, Any]:
"""Delete Clash proxies whose name is ``prefix`` or starts with ``prefix-``."""
root = get_settings().project_root
return nodes_ops.delete_clash_prefix(
root,
prefix=body.prefix,
dry_run=body.dry_run,
reload=body.reload,
force=body.force,
)
@router.post("/api/nodes/clash/prune-unhealthy")
def post_clash_prune_unhealthy(body: ClashPruneUnhealthyIn) -> dict[str, Any]:
"""Delay-test candidates and remove failing proxies from Clash configs."""
root = get_settings().project_root
return nodes_ops.prune_clash_unhealthy(
root,
prefix=body.prefix,
group=body.group,
timeout_ms=body.timeout_ms,
limit=body.limit,
dry_run=body.dry_run,
reload=body.reload,
delete_defs=body.delete_defs,
)
+105
View File
@@ -0,0 +1,105 @@
"""Self-check and maintenance ops."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from fastapi import APIRouter, Query
from apps.control_api.settings import get_settings
from apps.control_api.system_ops import cleanup_orphans, selfcheck
router = APIRouter(tags=["ops"])
@router.get("/api/ops/selfcheck")
def api_selfcheck() -> dict:
root = get_settings().project_root
return selfcheck(root)
@router.post("/api/ops/cleanup-orphans")
def api_cleanup_orphans(dry_run: bool = Query(default=False)) -> dict:
return cleanup_orphans(dry_run=dry_run)
# ---------------------------------------------------------------------------
# Outlook auth import/export helpers
#
# Outlook accounts persist as private 0600 per-account JSON files under a
# dedicated ``outlook_auths/`` directory (see OutlookProvider._write_outlook_artifact).
# These helpers expose a strict glob and a redacted public record shape so the
# control API can list/import/export Outlook accounts without ever returning a
# password or refresh_token in a response. They are deliberately separate from
# the ``xai-*.json`` glob in ``accounts_ops``: the two products must not share
# a glob or a directory.
# ---------------------------------------------------------------------------
# A path is a valid Outlook auth file only when its full name starts with
# ``outlook-`` and ends with ``.json``; the collision suffix
# ``outlook-<email>-<ts>-<n>.json`` keeps matching.
def _is_outlook_auth_file(path: Path) -> bool:
name = path.name
return name.startswith("outlook-") and name.endswith(".json")
def _outlook_auth_files(root: Path) -> list[Path]:
"""Sorted list of Outlook auth JSON files under ``root`` (no xai overlap)."""
if not root.exists():
return []
return sorted(p for p in root.iterdir() if p.is_file() and _is_outlook_auth_file(p))
_OUTLOOK_REQUIRED_FIELDS = ("email", "password", "client_id", "refresh_token")
def _public_outlook_record(payload: dict[str, Any]) -> dict[str, Any]:
"""Redacted view of one Outlook auth record (never secret values)."""
missing = [k for k in _OUTLOOK_REQUIRED_FIELDS if not payload.get(k)]
if missing:
raise ValueError(f"missing outlook fields: {','.join(sorted(missing))}")
return {
"email": str(payload["email"]),
"client_id": str(payload["client_id"]),
"bound": bool(payload.get("bound", False)),
"recovery_email": str(payload.get("recovery_email", "")),
"has_password": bool(payload.get("password")),
"has_refresh_token": bool(payload.get("refresh_token")),
}
@router.get("/api/outlook-accounts")
def api_list_outlook_accounts() -> dict:
"""List Outlook auth records as a redacted public view.
Strict ``outlook-*.json`` glob over the ``outlook_auths/`` directory; the
xai ``cpa_auths`` pool is never touched. Response records never carry the
password or refresh_token value — only ``has_password``/``has_refresh_token``
flags. Records that fail the required-fields contract are skipped with a
``skipped`` count rather than 500ing the whole list (an operator can then
repair the partial file).
"""
import json
import os
root = get_settings().project_root
# Honor the same OUTLOOK_AUTHS_DIR env the supervisor count block and the
# adapter config use, so listing/counting stays aligned with where the
# adapter writes artifacts. Defaults to "outlook_auths" everywhere.
auth_dir_name = os.environ.get("OUTLOOK_AUTHS_DIR") or "outlook_auths"
auth_dir = root / auth_dir_name
records: list[dict[str, Any]] = []
skipped = 0
for path in _outlook_auth_files(auth_dir):
try:
payload = json.loads(path.read_text(encoding="utf-8"))
records.append(_public_outlook_record(payload))
except (ValueError, OSError, json.JSONDecodeError):
skipped += 1
return {
"accounts": records,
"count": len(records),
"skipped": skipped,
"dir": auth_dir_name,
}
+58
View File
@@ -0,0 +1,58 @@
"""Run control routes."""
from __future__ import annotations
from fastapi import APIRouter, Query
from apps.control_api.runs import list_runs, run_status, start_run, stop_run, tail_log
from apps.control_api.schemas import LogsOut, RunActionOut, StartRunRequest
from apps.control_api.settings import get_settings
router = APIRouter(tags=["runs"])
@router.get("/api/runs")
def get_runs() -> dict:
root = get_settings().project_root
return {"runs": list_runs(root), "current": run_status(root)}
@router.get("/api/runs/current")
def get_current() -> dict:
root = get_settings().project_root
return {"run": run_status(root)}
@router.get("/api/runs/current/logs", response_model=LogsOut)
def get_current_logs(
tail: int = Query(default=200, ge=1, le=5000),
which: str = Query(default="auto", pattern="^(auto|supervisor|worker|both)$"),
) -> LogsOut:
root = get_settings().project_root
data = tail_log(root, n=tail, which=which)
return LogsOut(path=data.get("path"), text=data.get("text") or "")
@router.post("/api/runs/start", response_model=RunActionOut)
def post_start(body: StartRunRequest) -> RunActionOut:
root = get_settings().project_root
result = start_run(root, body)
return RunActionOut(ok=True, run=result.get("run"), detail=result.get("detail", ""))
@router.post("/api/runs/stop", response_model=RunActionOut)
def post_stop() -> RunActionOut:
root = get_settings().project_root
result = stop_run(root)
# Surface pid/source/mode in detail so UI never looks like a silent no-op.
detail = str(result.get("detail") or "")
extra = []
if result.get("pid") is not None:
extra.append(f"pid={result.get('pid')}")
if result.get("source"):
extra.append(f"source={result.get('source')}")
if result.get("mode"):
extra.append(f"mode={result.get('mode')}")
if extra:
detail = f"{detail} ({', '.join(extra)})" if detail else ", ".join(extra)
return RunActionOut(ok=bool(result.get("ok")), run=result.get("run"), detail=detail)
+387
View File
@@ -0,0 +1,387 @@
"""Start/stop/status/logs for supervised and one-shot register runs."""
from __future__ import annotations
import os
import subprocess
import time
import uuid
from pathlib import Path
from typing import Any
from fastapi import HTTPException, status
from apps.control_api.config_io import ENV_ALLOWLIST, config_to_env_map, load_config
from apps.control_api.process_registry import (
ProcessRegistry,
stop_pid,
supervisor_lock_held,
supervisor_lock_pid,
)
from apps.control_api.progress import build_progress
from apps.control_api.schemas import StartRunRequest
# Request extra_env may only set allowlisted operational keys (same set as .env sync).
EXTRA_ENV_ALLOWLIST = frozenset(ENV_ALLOWLIST)
# Max length and accepted charset for an extra_env VALUE. Values flow into the
# supervisor subprocess env (and from there can be re-serialized into .env lines
# or glued into log/config strings), so reject control characters — especially
# LF/CR, which would let a single value inject or corrupt a following line — and
# cap total length to bound log/stack growth. Keys are already allowlisted.
EXTRA_ENV_VALUE_MAX_LEN = 4096
def _sanitize_extra_env_value(key: str, value: str) -> str:
"""Validate a single extra_env value; raise ValueError on anything unsafe.
Keeps printable ASCII + common printable Unicode (letters/digits/punct and
whitespace OTHER than the line terminators NUL/CR/LF). NUL/CR/LF/vtab/FF and
the DEL byte are refused outright — these are the characters that break
line-oriented .env parsing and shell sourcing, the actual injection vector.
"""
v = str(value)
if len(v) > EXTRA_ENV_VALUE_MAX_LEN:
raise ValueError(
f"extra_env value too long for {key!r} "
f"({len(v)} > {EXTRA_ENV_VALUE_MAX_LEN})"
)
for ch in v:
o = ord(ch)
if o == 0 or o in (0x0A, 0x0D, 0x0B, 0x0C) or o == 0x7F:
raise ValueError(f"extra_env value for {key!r} contains control char")
return v
def filter_extra_env(extra: dict[str, str] | None) -> dict[str, str]:
out: dict[str, str] = {}
for k, v in (extra or {}).items():
key = str(k)
if key not in EXTRA_ENV_ALLOWLIST:
raise ValueError(f"extra_env key not allowed: {key}")
out[key] = _sanitize_extra_env_value(key, v)
return out
def env_from_config(root: Path) -> dict[str, str]:
"""Build process env overlays from config.json (console source of truth).
Empty strings are skipped so a blank config ``proxy`` does not wipe a
working process/PROXY inherited by the supervisor.
"""
return config_to_env_map(load_config(root), skip_empty=True)
def _latest_supervisor_log(root: Path) -> Path | None:
logs = root / "logs"
if not logs.is_dir():
return None
cands = sorted(logs.glob("*supervisor.log"), key=lambda p: p.stat().st_mtime, reverse=True)
return cands[0] if cands else None
def run_status(root: Path) -> dict[str, Any] | None:
reg = ProcessRegistry(root)
cur = reg.current()
lock_pid = supervisor_lock_pid()
sup_log = _latest_supervisor_log(root)
progress = build_progress(root, sup_log=sup_log)
base: dict[str, Any] = {
"lock_pid": lock_pid,
"progress": progress,
# flatten common counters for backward-compatible UI/overview
"complete": progress.get("complete"),
"consecutive_zero": progress.get("consecutive_zero"),
"phase": progress.get("phase"),
"phase_title": progress.get("phase_title"),
"phase_detail": progress.get("phase_detail"),
"stuck": progress.get("stuck"),
"stuck_reason": progress.get("stuck_reason"),
"supervisor_log": progress.get("supervisor_log"),
"worker_log": progress.get("worker_log"),
"last_lines": progress.get("last_lines") or [],
"steps": progress.get("steps") or [],
"timeline": progress.get("timeline") or [],
"summary": progress.get("summary"),
"batch_failures": progress.get("batch_failures"),
"sub": progress.get("sub"),
"chunk": progress.get("chunk"),
"target": progress.get("target"),
"target_new": progress.get("target_new"),
"batch_gained": progress.get("batch_gained"),
"batch_remain": progress.get("batch_remain"),
"goal_complete": progress.get("goal_complete"),
"baseline_complete": progress.get("baseline_complete"),
"remain": progress.get("remain"),
"accounts": progress.get("accounts"),
"mode": progress.get("mode"),
# UI: surface recent xai-*.json writes at top level so front-end
# doesn't need to reach into `progress.recent_writes`.
"recent_writes": progress.get("recent_writes") or [],
}
if cur:
return {
"source": "registry",
"alive": True,
"run_id": cur.get("run_id"),
"pid": cur.get("pid"),
"kind": cur.get("kind"),
"meta": cur.get("meta") or {},
**base,
}
if lock_pid is not None:
return {
"source": "lock",
"alive": True,
"run_id": None,
"pid": lock_pid,
"kind": "grok_supervisor",
"meta": {},
**base,
}
if progress.get("complete") is not None or base["last_lines"]:
return {
"source": "log",
"alive": False,
"run_id": None,
"pid": None,
"kind": None,
"meta": {},
**base,
}
return None
def tail_log(
root: Path,
n: int = 200,
*,
which: str = "auto",
) -> dict[str, str | None]:
"""Tail supervisor and/or worker logs.
which: auto|supervisor|worker|both
"""
reg = ProcessRegistry(root)
cur = reg.current()
sup = _latest_supervisor_log(root)
progress = build_progress(root, sup_log=sup)
worker = Path(progress["worker_log"]) if progress.get("worker_log") else None
# Prefer registry meta log for control-api-started runs
meta_log: Path | None = None
if cur and cur.get("meta", {}).get("log_path"):
meta_log = Path(cur["meta"]["log_path"])
def _read(path: Path | None) -> tuple[str | None, str]:
if path is None or not path.is_file():
return None, ""
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
return str(path), "\n".join(lines[-n:])
if which == "worker":
p, t = _read(worker)
return {"path": p, "text": t, "which": "worker"}
if which == "supervisor":
p, t = _read(sup or meta_log)
return {"path": p, "text": t, "which": "supervisor"}
if which == "both":
sp, st = _read(sup or meta_log)
wp, wt = _read(worker)
parts = []
if sp:
parts.append(f"===== supervisor: {sp} =====\n{st}")
if wp:
parts.append(f"===== worker: {wp} =====\n{wt}")
return {
"path": sp or wp,
"text": "\n\n".join(parts),
"which": "both",
"supervisor_path": sp,
"worker_path": wp,
}
# auto: worker if alive-ish else supervisor
if worker and worker.is_file():
p, t = _read(worker)
# append a bit of supervisor footer for context
sp, st = _read(sup)
if st:
t = t + "\n\n----- supervisor tail -----\n" + "\n".join(st.splitlines()[-30:])
return {"path": p, "text": t, "which": "auto", "supervisor_path": sp}
p, t = _read(meta_log or sup)
return {"path": p, "text": t, "which": "auto"}
def start_run(root: Path, req: StartRunRequest) -> dict[str, Any]:
extra = filter_extra_env(req.extra_env)
reg = ProcessRegistry(root)
existing = reg.current()
if existing:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"run already active pid={existing.get('pid')} kind={existing.get('kind')}",
)
if req.kind == "grok_supervisor" and supervisor_lock_held():
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"supervisor lock held pid={supervisor_lock_pid()}",
)
run_id = uuid.uuid4().hex[:12]
logs_dir = root / "logs"
logs_dir.mkdir(parents=True, exist_ok=True)
log_path = logs_dir / f"control_api_{run_id}.log"
if req.kind == "grok_supervisor":
argv = [
"bash",
str(root / "scripts" / "launch_batch_supervisor.sh"),
req.mode,
str(req.target),
str(req.threads),
req.tag,
]
script = root / "scripts" / "launch_batch_supervisor.sh"
if not script.is_file():
raise HTTPException(status_code=500, detail=f"missing {script}")
else:
_ORIG_PRODUCTS = {"grok", "mimo", "chatgpt", "outlook", "typesafe"}
universal = root / "register_universal.py"
if req.product not in _ORIG_PRODUCTS and universal.is_file():
# universal registrar: route to combat autoreg scripts
_PY311 = r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe"
argv = [_PY311, str(universal), req.product, str(req.target), str(req.threads)]
else:
register_sh = root / "register.sh"
if not register_sh.is_file():
raise HTTPException(status_code=500, detail=f"missing {register_sh}")
argv = ["bash", str(register_sh), req.product, str(req.target), str(req.threads)]
# Precedence for operational controls:
# 1) process env inherited from control_api (weakest for UI intent)
# 2) config.json mirrored via config_to_env_map (console source of truth)
# 3) request extra_env (explicit one-shot override)
# launch_batch_supervisor loads .env without clobbering already-set keys,
# so injecting config here makes the batch follow the console even when
# a stale .env still has EMAIL_PROVIDER=cloudflare.
env = os.environ.copy()
env.update(env_from_config(root))
env.update(extra)
env["REGISTER_PROJECT_ROOT"] = str(root)
log_f = open(log_path, "a", encoding="utf-8")
try:
proc = subprocess.Popen(
argv,
cwd=str(root),
env=env,
stdout=log_f,
stderr=subprocess.STDOUT,
# New session ⇒ pid is process-group leader; stop_run uses killpg.
start_new_session=True,
)
except Exception:
log_f.close()
raise
else:
# Child inherited the fd; close the parent handle so we don't leak.
log_f.close()
meta = {
"argv": argv,
"log_path": str(log_path),
"product": req.product,
"mode": req.mode,
"target": req.target,
"threads": req.threads,
"tag": req.tag,
# start_new_session=True ⇒ session/group leader == pid
"process_group": True,
"pgid": int(proc.pid),
}
reg.register(run_id, proc.pid, req.kind, meta)
# Fail-fast: launch_batch_supervisor exits immediately when flock is held
# (or script missing). Without this poll the registry sticks on a zombie
# bash and the UI shows ALIVE + stale progress forever.
for _ in range(10):
ret = proc.poll()
if ret is not None:
reg.clear()
try:
proc.wait(timeout=0.2)
except Exception:
pass
tail = ""
try:
lines = Path(log_path).read_text(encoding="utf-8", errors="replace").splitlines()
tail = "\n".join(lines[-20:]).strip()
except Exception:
pass
detail = f"process exited immediately code={ret}"
if tail:
detail = f"{detail}: {tail[:500]}"
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=detail,
)
time.sleep(0.1)
return {"ok": True, "run": reg.current(), "detail": "started"}
def stop_run(root: Path) -> dict[str, Any]:
"""Stop control-started run (process group) or fall back to lock pid.
Control-plane starts always use a new session, so we kill the whole group.
Lock-only (externally launched) supervisors still try process-group delivery
first and fall back to single-pid inside ``stop_pid``.
"""
reg = ProcessRegistry(root)
cur = reg.current()
pid: int | None = None
process_group = True
source = "none"
if cur:
pid = int(cur.get("pid") or 0)
meta = cur.get("meta") if isinstance(cur.get("meta"), dict) else {}
# Default True for control-started; honor explicit false if ever stored.
process_group = bool(meta.get("process_group", True))
source = "registry"
if not pid:
pid = supervisor_lock_pid()
process_group = True # best-effort; stop_pid falls back if not leader
source = "lock"
if not pid:
return {"ok": False, "run": None, "detail": "no active run"}
result = stop_pid(pid, grace_sec=10.0, process_group=process_group)
reg.clear()
return {
"ok": bool(result.get("ok")),
"run": None,
"detail": result.get("detail", ""),
"pid": pid,
"source": source,
"mode": result.get("mode"),
}
def list_runs(root: Path) -> list[dict[str, Any]]:
"""Recent supervisor logs index (lightweight)."""
logs = root / "logs"
if not logs.is_dir():
return []
out: list[dict[str, Any]] = []
for p in sorted(logs.glob("*supervisor.log"), key=lambda x: x.stat().st_mtime, reverse=True)[:20]:
out.append(
{
"path": str(p),
"name": p.name,
"mtime": p.stat().st_mtime,
}
)
return out
+87
View File
@@ -0,0 +1,87 @@
"""Pydantic models for control API."""
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, Field
class HealthOut(BaseModel):
ok: bool = True
project_root: str
token_required: bool
password_login_enabled: bool = False
users_configured: bool = False
auth_required: bool = False
class OverviewOut(BaseModel):
project_root: str
product_ok: int
run: dict[str, Any] | None = None
nodes: dict[str, Any] | None = None
class ConfigOut(BaseModel):
config: dict[str, Any]
path: str
class ConfigPutIn(BaseModel):
config: dict[str, Any]
class ConfigPutOut(BaseModel):
ok: bool
backup: str | None = None
changed_keys: list[str] = Field(default_factory=list)
changed_env_keys: list[str] = Field(default_factory=list)
env_backup: str | None = None
config: dict[str, Any]
class StartRunRequest(BaseModel):
kind: Literal["grok_supervisor", "register_sh"] = "grok_supervisor"
product: str = "grok"
mode: Literal["ordinary", "residential"] = "ordinary"
target: int = Field(default=100, ge=1, le=100_000)
threads: int = Field(default=1, ge=1, le=32)
tag: str = Field(default="batch_web", min_length=1, max_length=64)
extra_env: dict[str, str] = Field(default_factory=dict)
class RunActionOut(BaseModel):
ok: bool
run: dict[str, Any] | None = None
detail: str = ""
class LogsOut(BaseModel):
path: str | None = None
text: str = ""
class ImportResultOut(BaseModel):
ok: bool
detail: str = ""
result: dict[str, Any] = Field(default_factory=dict)
class LoginIn(BaseModel):
username: str = Field(min_length=1, max_length=64)
password: str = Field(min_length=1, max_length=256)
class LoginOut(BaseModel):
ok: bool
username: str | None = None
class MeOut(BaseModel):
authenticated: bool
username: str | None = None
auth_required: bool = True
password_login_enabled: bool = True
token_auth_enabled: bool = False
users_configured: bool = False
+84
View File
@@ -0,0 +1,84 @@
"""Signed HttpOnly session cookies for browser login."""
from __future__ import annotations
import time
from typing import Any
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
from apps.control_api.settings import MAX_SESSION_TTL_SECONDS
COOKIE_NAME = "control_session"
def _serializer(secret: str) -> URLSafeTimedSerializer:
return URLSafeTimedSerializer(secret, salt="control-api-session-v1")
def mint_session_token(*, secret: str, username: str, ttl_seconds: int) -> str:
if not secret:
raise ValueError("session secret required")
# Bake the ttl into the payload, clamped to the hard ceiling so a token
# whose ttl was somehow raised past the cap (older build, or a caller that
# bypassed get_settings) still verifies within the bound at read time.
ttl = max(0, min(int(ttl_seconds), MAX_SESSION_TTL_SECONDS))
payload = {
"u": username,
"iat": int(time.time()),
"ttl": ttl,
}
return _serializer(secret).dumps(payload)
def read_session_token(
token: str,
*,
secret: str,
max_age: int,
max_ttl: int = MAX_SESSION_TTL_SECONDS,
) -> dict[str, Any] | None:
"""Return the decoded session payload, or None for any invalid/expired token.
Two independent guards bound a token's lifetime:
- ``max_age``: itsdangerous rejects any token whose ``iat`` is older than
``max_age`` seconds (the server-side ceiling, normally
settings.session_ttl_seconds).
- ``max_ttl``: the payload's baked-in ``ttl`` field is re-checked against
this hard ceiling (MAX_SESSION_TTL_SECONDS). A token minted by an older
build that did NOT clamp the ttl, or whose ttl was raised past the cap,
is refused even if it is still within ``max_age`` — so the lifetime can
only ever shrink, never grow past the constant.
"""
if not token or not secret:
return None
try:
payload = _serializer(secret).loads(token, max_age=max_age)
except (BadSignature, SignatureExpired):
return None
if not isinstance(payload, dict):
return None
user = payload.get("u")
if not isinstance(user, str) or not user:
return None
# Re-validate the baked-in ttl against the hard ceiling. A token carrying a
# ttl above max_ttl is untrustworthy (older build / tampered) — refuse it.
ttl = payload.get("ttl")
if not isinstance(ttl, int) or ttl > max_ttl or ttl < 0:
return None
return payload
def session_cookie_kwargs(*, secure: bool, max_age: int) -> dict[str, Any]:
# Cookie max_age is also clamped to the hard ceiling so a runaway TTL env
# can't ask the browser to keep an effectively-immortal cookie either.
capped = max(0, min(int(max_age), MAX_SESSION_TTL_SECONDS))
return {
"key": COOKIE_NAME,
"httponly": True,
"samesite": "strict",
"secure": secure,
"path": "/",
"max_age": capped,
}
+195
View File
@@ -0,0 +1,195 @@
"""Environment settings for the control API."""
from __future__ import annotations
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
import os
import secrets
# Durable secret files under project root (mode 0600 recommended).
SESSION_SECRET_FILENAME = ".control_api_session_secret"
TOKEN_FILENAME = ".control_api_token"
# Hard ceiling on session cookie / token lifetime, independent of the
# operator-tunable CONTROL_API_SESSION_TTL. Even if an operator raises the TTL
# env (it is clamped to [MIN_SESSION_TTL_SECONDS, MAX_SESSION_TTL_SECONDS] in
# get_settings), a signed token can never outlive this bound: read_session_token
# re-validates the ttl baked into the payload against this constant.
MIN_SESSION_TTL_SECONDS = 300
MAX_SESSION_TTL_SECONDS = 7 * 24 * 3600
@dataclass(frozen=True)
class Settings:
project_root: Path
host: str
port: int
token: str | None
max_upload_bytes: int = 20 * 1024 * 1024
# Password / session auth
session_secret: str | None = None
session_ttl_seconds: int = 12 * 3600
cookie_secure: bool = False
password_login_enabled: bool = True
bootstrap_user: str | None = None
bootstrap_password: str | None = None
# Where session_secret / token came from (for ops logs only; never the value)
session_secret_source: str = "missing"
token_source: str = "missing"
@property
def auth_required(self) -> bool:
"""True when bearer token is set. Password users checked via auth_is_required()."""
return bool(self.token)
def _read_secret_file(path: Path) -> str | None:
"""Read one-line secret file; return stripped text or None. Never log contents."""
try:
if not path.is_file():
return None
text = path.read_text(encoding="utf-8", errors="replace").strip()
# first non-empty line only
for line in text.splitlines():
line = line.strip()
if line and not line.startswith("#"):
return line
return text or None
except Exception:
return None
def _resolve_project_root() -> Path:
root = os.environ.get("REGISTER_PROJECT_ROOT")
return Path(root).resolve() if root else Path.cwd().resolve()
@lru_cache(maxsize=1)
def get_settings() -> Settings:
project_root = _resolve_project_root()
host = os.environ.get("CONTROL_API_HOST", "127.0.0.1")
port = int(os.environ.get("CONTROL_API_PORT", "8787"))
max_upload = int(os.environ.get("CONTROL_API_MAX_UPLOAD_BYTES", str(20 * 1024 * 1024)))
# ── bearer token: env → file ────────────────────────────────────────────
token = os.environ.get("CONTROL_API_TOKEN")
token_source = "env"
if token is not None and token.strip() == "":
token = None
if not token:
file_token = _read_secret_file(project_root / TOKEN_FILENAME)
if file_token:
token = file_token
token_source = f"file:{TOKEN_FILENAME}"
else:
token_source = "missing"
# ── session secret: env → file → token → dev env → ephemeral ────────────
session_secret = os.environ.get("CONTROL_API_SESSION_SECRET")
session_secret_source = "env"
if session_secret is not None and session_secret.strip() == "":
session_secret = None
if not session_secret:
file_secret = _read_secret_file(project_root / SESSION_SECRET_FILENAME)
if file_secret:
session_secret = file_secret
session_secret_source = f"file:{SESSION_SECRET_FILENAME}"
if not session_secret and token:
session_secret = token
session_secret_source = "token"
if not session_secret:
dev = os.environ.get("CONTROL_API_DEV_SESSION_SECRET")
if dev and dev.strip():
session_secret = dev.strip()
session_secret_source = "env:CONTROL_API_DEV_SESSION_SECRET"
if not session_secret and os.environ.get("CONTROL_API_ALLOW_EPHEMERAL_SESSION") == "1":
session_secret = secrets.token_hex(32)
session_secret_source = "ephemeral"
if not session_secret:
session_secret_source = "missing"
ttl = int(os.environ.get("CONTROL_API_SESSION_TTL", str(12 * 3600)))
# Clamp to a safe band: never below the min floor (5 min) and never above the
# hard ceiling (7 days). The cookie max_age AND the signed-token ttl both
# derive from this, so a runaway TTL env can't mint effectively-immortal
# sessions. read_session_token additionally re-validates the ttl in the
# payload against MAX_SESSION_TTL_SECONDS, so a token minted before a
# re-clamp can't slip a longer-lived ttl through either.
ttl = max(MIN_SESSION_TTL_SECONDS, min(MAX_SESSION_TTL_SECONDS, ttl))
cookie_secure = os.environ.get("CONTROL_API_COOKIE_SECURE", "").strip().lower() in {
"1",
"true",
"yes",
"on",
}
# Password login on by default; set CONTROL_API_PASSWORD_LOGIN=0 to disable
pw_flag = os.environ.get("CONTROL_API_PASSWORD_LOGIN", "1").strip().lower()
password_login_enabled = pw_flag not in {"0", "false", "no", "off"}
# Empty user store only: first-start default operator. Override via env.
# Production hosts that already have .control_api_users.json are untouched
# (ensure_bootstrap_user is a no-op when any user exists).
bootstrap_user = os.environ.get("CONTROL_API_BOOTSTRAP_USER")
bootstrap_password = os.environ.get("CONTROL_API_BOOTSTRAP_PASSWORD")
if bootstrap_user is not None and bootstrap_user.strip() == "":
bootstrap_user = None
if bootstrap_password is not None and bootstrap_password.strip() == "":
bootstrap_password = None
if bootstrap_user is None and "CONTROL_API_BOOTSTRAP_USER" not in os.environ:
bootstrap_user = "admin"
if bootstrap_password is None and "CONTROL_API_BOOTSTRAP_PASSWORD" not in os.environ:
bootstrap_password = "admin123"
return Settings(
project_root=project_root,
host=host,
port=port,
token=token,
max_upload_bytes=max_upload,
session_secret=session_secret,
session_ttl_seconds=ttl,
cookie_secure=cookie_secure,
password_login_enabled=password_login_enabled,
bootstrap_user=bootstrap_user,
bootstrap_password=bootstrap_password,
session_secret_source=session_secret_source,
token_source=token_source,
)
def clear_settings_cache() -> None:
get_settings.cache_clear()
def log_auth_startup(settings: Settings | None = None) -> None:
"""Ops-safe startup line: sources + readiness, never secret values."""
s = settings or get_settings()
secret_ok = bool(s.session_secret)
token_ok = bool(s.token)
users = "yes" if (s.project_root / ".control_api_users.json").is_file() else "no"
print(
"[control_api] auth "
f"session_secret={s.session_secret_source} "
f"token={s.token_source} "
f"password_login={'on' if s.password_login_enabled else 'off'} "
f"users_file={users} "
f"ready={'yes' if (secret_ok and s.password_login_enabled) or token_ok else 'NO'}",
flush=True,
)
if s.password_login_enabled and not secret_ok:
print(
"[control_api] WARN password login will fail: session secret missing. "
f"Set CONTROL_API_SESSION_SECRET or create {s.project_root / SESSION_SECRET_FILENAME} "
f"(or set CONTROL_API_TOKEN / {TOKEN_FILENAME}). "
"Bare `python -m apps.control_api` without secrets is unsupported on production.",
flush=True,
)
if s.session_secret_source == "ephemeral":
print(
"[control_api] WARN session secret is ephemeral — logins invalidate on restart. "
f"Persist via {SESSION_SECRET_FILENAME} or CONTROL_API_SESSION_SECRET.",
flush=True,
)
+177
View File
@@ -0,0 +1,177 @@
"""Self-check + orphan browser/Xvfb cleanup for the control plane."""
from __future__ import annotations
import json
import os
import shutil
import socket
import time
from pathlib import Path
from typing import Any
from urllib.error import URLError
from urllib.request import ProxyHandler, Request, build_opener
def _ok(name: str, ok: bool, detail: str = "", **extra: Any) -> dict[str, Any]:
out = {"name": name, "ok": bool(ok), "detail": detail}
out.update(extra)
return out
def _tcp_open(host: str, port: int, timeout: float = 1.5) -> bool:
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except OSError:
return False
def _http_probe(url: str, proxy: str | None = None, timeout: float = 8.0) -> tuple[bool, str]:
try:
handlers = []
if proxy:
handlers.append(ProxyHandler({"http": proxy, "https": proxy}))
opener = build_opener(*handlers)
req = Request(url, method="GET", headers={"User-Agent": "control-api-selfcheck/1"})
with opener.open(req, timeout=timeout) as resp:
code = getattr(resp, "status", None) or resp.getcode()
return True, f"HTTP {code}"
except Exception as exc:
return False, f"{type(exc).__name__}: {exc}"[:200]
def selfcheck(root: Path) -> dict[str, Any]:
checks: list[dict[str, Any]] = []
cfg_path = root / "config.json"
cfg: dict[str, Any] = {}
if cfg_path.is_file():
try:
raw = json.loads(cfg_path.read_text(encoding="utf-8"))
cfg = {k: v for k, v in raw.items() if not str(k).startswith("//")}
checks.append(_ok("config.json", True, f"keys={len(cfg)}"))
except Exception as exc:
checks.append(_ok("config.json", False, str(exc)[:200]))
else:
checks.append(_ok("config.json", False, "missing"))
venv_py = root / ".venv" / "bin" / "python"
checks.append(_ok("venv_python", venv_py.is_file(), str(venv_py)))
reg_cli = root / "register_cli.py"
checks.append(_ok("register_cli.py", reg_cli.is_file(), str(reg_cli)))
sup = root / "scripts" / "launch_batch_supervisor.sh"
checks.append(_ok("launch_batch_supervisor.sh", sup.is_file(), str(sup)))
auths = root / "cpa_auths"
if auths.is_dir():
n = sum(1 for _ in auths.glob("xai-*.json"))
checks.append(_ok("cpa_auths", True, f"files={n}", path=str(auths)))
else:
checks.append(_ok("cpa_auths", False, "missing dir", path=str(auths)))
# Clash mixed-port default
clash_port = 7897
clash_up = _tcp_open("127.0.0.1", clash_port)
checks.append(
_ok(
"clash_mixed_7897",
clash_up,
"up" if clash_up else "down (ordinary batch needs mihomo mixed-port)",
)
)
clash_api = _tcp_open("127.0.0.1", 9090) or _tcp_open("127.0.0.1", 9097)
checks.append(_ok("clash_api", clash_api, "9090/9097 reachable" if clash_api else "api port closed"))
# Display / browsers for headed mint
display = os.environ.get("DISPLAY") or ""
checks.append(_ok("DISPLAY", bool(display) or shutil.which("Xvfb") is not None, display or "no DISPLAY; Xvfb available" if shutil.which("Xvfb") else "no DISPLAY/Xvfb"))
checks.append(_ok("xvfb-run", shutil.which("xvfb-run") is not None, shutil.which("xvfb-run") or "missing"))
proxy = str(cfg.get("proxy") or cfg.get("cpa_proxy") or "http://127.0.0.1:7897")
if clash_up:
ok, detail = _http_probe("https://accounts.x.ai/", proxy=proxy, timeout=10)
checks.append(_ok("egress_accounts_xai", ok, detail, proxy=proxy))
else:
checks.append(_ok("egress_accounts_xai", False, "skipped: clash down", proxy=proxy))
# Mail provider hint (singleton + multi pool)
provider = str(cfg.get("email_provider") or os.environ.get("EMAIL_PROVIDER") or "")
raw_multi = cfg.get("email_providers")
if raw_multi is None or raw_multi == "":
raw_multi = os.environ.get("EMAIL_PROVIDERS") or ""
if isinstance(raw_multi, (list, tuple, set)):
multi = [str(x).strip() for x in raw_multi if str(x).strip()]
else:
multi = [p.strip() for p in str(raw_multi).replace(",", ",").split(",") if p.strip()]
multi_s = ",".join(multi) if multi else ""
domains = str(cfg.get("defaultDomains") or os.environ.get("DEFAULT_DOMAINS") or "")
checks.append(
_ok(
"email_config",
bool(provider or multi),
(
f"provider={provider or '?'} "
f"providers={multi_s or '(empty)'} "
f"domains={domains or '(empty)'}"
),
)
)
# Live run lock
lock_pid = None
lock_alive = False
pid_path = Path("/tmp/grok_batch_supervisor.lock.pid")
if pid_path.is_file():
try:
lock_pid = int(pid_path.read_text().strip())
os.kill(lock_pid, 0)
lock_alive = True
except Exception:
lock_alive = False
checks.append(
_ok(
"supervisor_lock",
True,
f"pid={lock_pid} alive={lock_alive}" if lock_pid is not None else "no lock",
pid=lock_pid,
alive=lock_alive,
)
)
failed = [c for c in checks if not c.get("ok")]
return {
"ok": len(failed) == 0,
"ts": int(time.time()),
"failed": len(failed),
"checks": checks,
"summary": "all green" if not failed else f"{len(failed)} check(s) failed",
}
def cleanup_orphans(*, dry_run: bool = False) -> dict[str, Any]:
"""Kill PPID=1 leftover Drission Chromes + empty Xvfb (safe for live register_cli children)."""
try:
from tab_pool import cleanup_orphan_drission_chromes, cleanup_orphan_xvfb
except Exception as exc:
return {"ok": False, "detail": f"import tab_pool failed: {exc}", "dry_run": dry_run}
chrome = cleanup_orphan_drission_chromes(
dry_run=dry_run,
only_ppid_init=True,
include_self_children=False,
kill_related_helpers=True,
clean_tmp_dirs=True,
tmp_dir_max_age_sec=0 if not dry_run else 0,
)
xvfb = cleanup_orphan_xvfb(dry_run=dry_run, only_ppid_init=True, require_no_children=True)
return {
"ok": True,
"dry_run": dry_run,
"chrome": chrome,
"xvfb": xvfb,
"detail": (
f"chrome_killed={chrome.get('killed', 0)} xvfb_killed={xvfb.get('killed', 0)}"
if not dry_run
else f"chrome_would={chrome.get('would_kill', chrome.get('matched', 0))} "
f"xvfb_would={xvfb.get('would_kill', xvfb.get('matched', 0))}"
),
}
+122
View File
@@ -0,0 +1,122 @@
"""Operator credentials store for control-plane login.
File: {project_root}/.control_api_users.json (gitignored)
Schema:
{
"version": 1,
"users": {
"admin": {"password_hash": "scrypt$...", "disabled": false}
}
}
"""
from __future__ import annotations
import json
import os
import threading
from pathlib import Path
from typing import Any
from apps.control_api.passwords import hash_password, verify_password
USERS_FILENAME = ".control_api_users.json"
_lock = threading.Lock()
def users_path(project_root: Path) -> Path:
return project_root / USERS_FILENAME
def _default_doc() -> dict[str, Any]:
return {"version": 1, "users": {}}
def load_users_doc(path: Path) -> dict[str, Any]:
if not path.is_file():
return _default_doc()
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception:
return _default_doc()
if not isinstance(data, dict):
return _default_doc()
users = data.get("users")
if not isinstance(users, dict):
data = _default_doc()
else:
data.setdefault("version", 1)
data["users"] = users
return data
def save_users_doc(path: Path, doc: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
text = json.dumps(doc, ensure_ascii=False, indent=2) + "\n"
tmp.write_text(text, encoding="utf-8")
os.chmod(tmp, 0o600)
tmp.replace(path)
try:
os.chmod(path, 0o600)
except OSError:
pass
def list_usernames(project_root: Path) -> list[str]:
doc = load_users_doc(users_path(project_root))
return sorted(str(u) for u in (doc.get("users") or {}) if str(u))
def has_any_user(project_root: Path) -> bool:
return bool(list_usernames(project_root))
def authenticate(project_root: Path, username: str, password: str) -> bool:
username = (username or "").strip()
if not username or not password:
return False
path = users_path(project_root)
with _lock:
doc = load_users_doc(path)
rec = (doc.get("users") or {}).get(username)
if not isinstance(rec, dict):
return False
if rec.get("disabled"):
return False
hashed = rec.get("password_hash") or ""
return verify_password(password, str(hashed))
def upsert_user(project_root: Path, username: str, password: str, *, disabled: bool = False) -> None:
username = (username or "").strip()
if not username:
raise ValueError("username required")
if len(username) > 64 or any(c in username for c in " \t\n\r/\\"):
raise ValueError("invalid username")
if not password or len(password) < 8:
raise ValueError("password must be at least 8 characters")
path = users_path(project_root)
with _lock:
doc = load_users_doc(path)
users = doc.setdefault("users", {})
users[username] = {
"password_hash": hash_password(password),
"disabled": bool(disabled),
}
save_users_doc(path, doc)
def ensure_bootstrap_user(
project_root: Path,
*,
username: str | None,
password: str | None,
) -> str | None:
"""Create first user from env if store empty. Returns created username or None."""
if has_any_user(project_root):
return None
if not username or not password:
return None
upsert_user(project_root, username, password, disabled=False)
return username.strip()