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
+53
View File
@@ -0,0 +1,53 @@
# Apps (entrypoints)
Thin map of user-facing entrypoints. Implementation may still live at repo root.
| App | How to run | Notes |
|-----|------------|--------|
| **Hub** | `./register.sh help` | Multi-provider |
| **Grok CLI** | `./register.sh grok 1 1` | Production |
| **Web control plane** | `./scripts/run_control_api.sh` | Config / Import / Runs UI at `http://127.0.0.1:8787` |
| **MiMo** | `./register.sh mimo` | Node runtime |
| **Core** | `./register.sh core list` | Layered orchestration |
## Web control plane
```bash
export REGISTER_PROJECT_ROOT="$(pwd)" # optional; defaults to cwd
export CONTROL_API_HOST=127.0.0.1
export CONTROL_API_PORT=8787
# Recommended: stable session secret + optional script bearer
export CONTROL_API_SESSION_SECRET="$(openssl rand -hex 32)"
export CONTROL_API_TOKEN="$(openssl rand -hex 32)" # optional; for curl/scripts
# First start with empty user store auto-creates:
# username: admin
# password: admin123
# Override: CONTROL_API_BOOTSTRAP_USER / CONTROL_API_BOOTSTRAP_PASSWORD
# Or set/change later:
# uv run python scripts/control_api_user.py set admin
./scripts/run_control_api.sh
```
Open `http://127.0.0.1:8787` → **login form**. Default credentials **`admin` / `admin123`** when `.control_api_users.json` does not exist yet. Session is HttpOnly cookie.
- API: `/api/health`, `/api/auth/*`, `/api/overview`, `/api/config`, `/api/import/*`, `/api/runs/*`, `/api/nodes/*`, `/api/accounts/*`, `/api/ops/*`
- UI: **console10** Preact SPA — `cd apps/web && npm run build` (or `./scripts/build_web_console.sh`) writes `apps/web/dist`; FastAPI prefers `apps/web/dist` then falls back to flat `apps/web/`.
- **Packaging:** GitHub Actions `CI` job `package-console10` runs on **main push** only (after green tests) → artifact `console10-web` (14d). PR CI tests without packaging.
- **Deploy (auto + manual):** workflow **Deploy console10** (Environment `pxed`).
- **Auto:** after successful `CI` on `main` **push** (`workflow_run`), deploys that run’s artifact.
- **Manual:** Actions → Deploy console10 (`workflow_dispatch`); `dry_run` / rebuild / artifact options.
- Secrets: `PXED_SSH_PRIVATE_KEY` + `PXED_HOST` + `PXED_KNOWN_HOSTS` (optional `PXED_WEB`, `PXED_SSH_PORT`). Prefer direct host (not cloudflared alias).
- Path sanitized under `/data/grok-register`; stale Vite `assets/*` pruned; **single script** `scripts/deploy_web_console10.sh`.
- **Boundary (I5):** **static SPA only** under `PXED_WEB` (default `/data/grok-register/apps/web`). Does **not** deploy `control_api` / register core / supervisor, does **not** stop batch/coinbot. API code changes need a separate host update + careful control_api restart.
- Deploy key: scope write to `/data/grok-register/` (or web subdir) only when possible.
- **Local fallback:** `./scripts/deploy_web_console10.sh`. `SKIP_BUILD=1` / `CONSOLE10_TGZ=` / `DRY_RUN=1` / `PRUNE_STALE_ASSETS=1` supported.
- Dev: `cd apps/web && npm run dev` proxies `/api` → `:8787`. Legacy console9 under `apps/web/legacy/`.
- Auth (either):
- **Browser:** password login → signed cookie `control_session`
- **Scripts:** `Authorization: Bearer <CONTROL_API_TOKEN>` or `X-Control-Token`
- Operators file: `.control_api_users.json` (gitignored, mode 0600, scrypt hashes). Bootstrap is a **no-op** if this file already has users (production stays as configured).
- Login rate limit: 8 failures / 5 min per IP+username
- Default bind is localhost; use SSH tunnel for remote browser access
- Disable password login only for break-glass: `CONTROL_API_PASSWORD_LOGIN=0` (then rely on bearer or open)
Subdir `gui/` only documents that the desktop TTK UI was removed.
View File
+13
View File
@@ -0,0 +1,13 @@
# CLI
```bash
./register.sh help
./register.sh grok [count] [threads]
./register.sh mimo [count]
./register.sh core list
./register.sh core run -p <provider> -n 1
./register.sh smoke mimo
```
Grok full flags: `uv run python register_cli.py --help`
Core: `python -m register_core --help`
+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()
+13
View File
@@ -0,0 +1,13 @@
# Desktop GUI — removed
The TTK desktop UI (`GrokRegisterGUI`) was removed.
Use the **Web control plane** instead:
```bash
export CONTROL_API_TOKEN=$(openssl rand -hex 32) # recommended
./scripts/run_control_api.sh
# open http://127.0.0.1:8787
```
See `apps/README.md` and `docs/superpowers/specs/2026-07-21-web-control-plane-design.md`.
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>AI РеГЕР · Control Plane</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+4147
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
{
"name": "ai-register-console",
"private": true,
"version": "10.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@preact/signals": "^2.0.4",
"preact": "^10.26.4"
},
"devDependencies": {
"@preact/preset-vite": "^2.10.1",
"@testing-library/preact": "^3.2.4",
"jsdom": "^26.1.0",
"vite": "^6.2.0",
"vitest": "^4.1.10"
}
}
+137
View File
@@ -0,0 +1,137 @@
import { useEffect, useState } from "preact/hooks";
import { session } from "./store/session.js";
import * as api from "./api/client.js";
import { ToastHost } from "./ui/ToastHost.jsx";
import { OpsFeedbackBar } from "./ui/OpsFeedbackBar.jsx";
import { LoginGate } from "./pages/LoginGate.jsx";
import { RegisterPage } from "./pages/Register/RegisterPage.jsx";
import { LogsPage } from "./pages/RunLogs/LogsPage.jsx";
import { AccountsPage } from "./pages/Accounts/AccountsPage.jsx";
import { ResourcesPage } from "./pages/Resources/ResourcesPage.jsx";
import { SettingsPage } from "./pages/Settings/SettingsPage.jsx";
const NAV = [
{ id: "register", label: "Обзор / Регистрация", hash: "#/register" },
{ id: "logs", label: "Журнал запусков", hash: "#/logs" },
{ id: "accounts", label: "Пул аккаунтов", hash: "#/accounts" },
{ id: "resources", label: "Ресурсы", hash: "#/resources" },
{ id: "settings", label: "Настройки", hash: "#/settings" },
];
function pageFromHash() {
const h = (location.hash || "#/register").replace(/^#\/?/, "");
const id = h.split("?")[0] || "register";
return NAV.some((n) => n.id === id) ? id : "register";
}
export function App() {
const [page, setPage] = useState(pageFromHash);
const [sidebarOpen, setSidebarOpen] = useState(false);
useEffect(() => {
const onHash = () => setPage(pageFromHash());
window.addEventListener("hashchange", onHash);
return () => window.removeEventListener("hashchange", onHash);
}, []);
useEffect(() => {
(async () => {
try {
const m = await api.me();
session.value = { ...session.value, ...m, checked: true };
} catch {
session.value = { ...session.value, authenticated: false, checked: true };
}
})();
}, []);
const authed = session.value.authenticated || !session.value.auth_required;
if (!session.value.checked) return <div class="login-gate">Загрузка…</div>;
if (!authed) return <LoginGate />;
const Page = {
register: RegisterPage,
logs: LogsPage,
accounts: AccountsPage,
resources: ResourcesPage,
settings: SettingsPage,
}[page];
return (
<>
<ToastHost />
<div class={`app-shell ${sidebarOpen ? "nav-open" : ""}`}>
<button
type="button"
class="nav-toggle btn btn-ghost btn-sm"
onClick={() => setSidebarOpen((v) => !v)}
>
Меню
</button>
{sidebarOpen ? (
<button
type="button"
class="nav-backdrop"
aria-label="Закрыть меню"
onClick={() => setSidebarOpen(false)}
/>
) : null}
<aside class="sidebar">
<div class="side-brand">
<div class="logo-dot" aria-hidden="true" />
<div>
<div class="side-title">AI РеГЕР</div>
<a
class="side-link"
href="https://github.com/dengyie/ai-register-machine"
target="_blank"
rel="noopener noreferrer"
>
grok / mimo / chatgpt / typesafe
</a>
</div>
</div>
<nav class="side-nav">
{NAV.map((n) => (
<a
key={n.id}
href={n.hash}
class={`nav-item ${page === n.id ? "active" : ""}`}
onClick={() => setSidebarOpen(false)}
>
<span class="nav-dot" />
{n.label}
</a>
))}
</nav>
<div class="side-foot">
<div class="hint">{session.value.username || "operator"}</div>
<button
type="button"
class="btn btn-danger btn-sm"
onClick={async () => {
try {
await api.logout();
} finally {
api.clearToken();
session.value = {
...session.value,
authenticated: false,
username: null,
};
}
}}
>
Logout
</button>
</div>
</aside>
<div class="main-wrap">
<OpsFeedbackBar />
<Page />
</div>
</div>
</>
);
}
+217
View File
@@ -0,0 +1,217 @@
const TOKEN_KEY = "controlToken";
export function getToken() {
return sessionStorage.getItem(TOKEN_KEY) || "";
}
export function setToken(t) {
if (t) sessionStorage.setItem(TOKEN_KEY, t);
else sessionStorage.removeItem(TOKEN_KEY);
}
export function clearToken() {
sessionStorage.removeItem(TOKEN_KEY);
}
export function headers(json = false) {
const h = {};
if (json) h["Content-Type"] = "application/json";
const t = getToken();
if (t) h["Authorization"] = `Bearer ${t}`;
return h;
}
export async function api(path, opts = {}) {
const callerHeaders = opts.headers || {};
const hasAuth = Object.keys(callerHeaders).some(
(k) => k.toLowerCase() === "authorization"
);
const token = getToken();
const merged = {
...(token && !hasAuth ? { Authorization: `Bearer ${token}` } : {}),
...callerHeaders,
};
const res = await fetch(path, {
credentials: "same-origin",
...opts,
headers: merged,
});
const text = await res.text();
let body;
try {
body = text ? JSON.parse(text) : {};
} catch {
body = { detail: text };
}
if (!res.ok) {
const detail = body.detail || body.error || body.message || res.statusText;
let msg =
typeof detail === "string"
? detail
: detail != null
? JSON.stringify(detail)
: res.statusText;
// Never keep multi-KB Cloudflare HTML in Error.message — toast/banner explode.
if (
msg.length > 280 ||
/<!DOCTYPE\s+html/i.test(msg) ||
/<html[\s>]/i.test(msg)
) {
const title = (msg.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] || "";
const codeM = msg.match(/Error code\s+(\d{3})/i);
const code = codeM ? codeM[1] : String(res.status);
if (String(code) === "524" || /timeout occurred/i.test(msg)) {
msg = `Таймаут шлюза (Cloudflare 524): origin не ответил вовремя${title ? ` · ${title}` : ""}`;
} else {
msg = `HTTP ${code}: ${(title || "страница ошибки origin").replace(/\s*\|\s*.*$/, "").trim()}`;
}
}
const err = new Error(msg);
err.status = res.status;
throw err;
}
return body;
}
export async function postMultipart(url, formData) {
const res = await fetch(url, {
method: "POST",
headers: headers(),
body: formData,
credentials: "same-origin",
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(body.detail || res.statusText);
err.status = res.status;
throw err;
}
return body;
}
// Auth
export const login = (username, password) =>
api("/api/auth/login", {
method: "POST",
headers: headers(true),
body: JSON.stringify({ username, password }),
});
export const logout = () => api("/api/auth/logout", { method: "POST", headers: headers(true) });
export const me = () => api("/api/auth/me");
// Core
export const overview = () => api("/api/overview");
export const getConfig = () => api("/api/config");
export const putConfig = (partial) =>
api("/api/config", {
method: "PUT",
headers: headers(true),
body: JSON.stringify(partial),
});
// Runs
export const listRuns = () => api("/api/runs");
export const currentRun = () => api("/api/runs/current");
export const startRun = (body) =>
api("/api/runs/start", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body),
});
export const stopRun = () =>
api("/api/runs/stop", { method: "POST", headers: headers(true) });
export const runLogs = (tail = 200, which = "auto") =>
api(`/api/runs/current/logs?tail=${tail}&which=${which}`);
// Accounts
export const listAccounts = (qs) => api(`/api/accounts?${qs}`);
export const deleteAccount = (name) =>
api(`/api/accounts/${encodeURIComponent(name)}`, {
method: "DELETE",
headers: headers(),
});
// Nodes
export const listClash = () => api("/api/nodes/clash");
export const testClash = (body) =>
api("/api/nodes/clash/test", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body || {}),
});
export const importClashUrl = (body) =>
api("/api/nodes/clash/import-url", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body),
});
export const deleteClashPrefix = (body) =>
api("/api/nodes/clash/delete-prefix", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body),
});
export const pruneClashUnhealthy = (body) =>
api("/api/nodes/clash/prune-unhealthy", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body),
});
export const listCatalog = (qs) => api(`/api/nodes?${qs}`);
export const addCatalogNode = (body) =>
api("/api/nodes", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body),
});
export const testCatalog = (body) =>
api("/api/nodes/test", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body || {}),
});
export const deleteCatalogNode = (id) =>
api(`/api/nodes/${encodeURIComponent(id)}`, {
method: "DELETE",
headers: headers(),
});
export const patchCatalogNode = (id, body) =>
api(`/api/nodes/${encodeURIComponent(id)}`, {
method: "PATCH",
headers: headers(true),
body: JSON.stringify(body),
});
// Import multipart
export const importNodesFile = (fd) => postMultipart("/api/import/nodes", fd);
export const importMailText = (fd) => postMultipart("/api/import/mail", fd);
export const importAuthsFile = (fd) => postMultipart("/api/import/auths", fd);
export const importPackFile = (fd) => postMultipart("/api/import/pack", fd);
// Ops
export const selfcheck = () => api("/api/ops/selfcheck", { headers: headers() });
export const cleanupOrphans = () =>
api("/api/ops/cleanup-orphans?dry_run=false", {
method: "POST",
headers: headers(true),
});
// Mail pool probe
export const mailPoolStats = () => api("/api/mail/pool");
export const probeMail = (body) =>
api("/api/mail/probe", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body || {}),
});
export const quarantineMail = (body) =>
api("/api/mail/quarantine", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body || {}),
});
export const compactMail = (body) =>
api("/api/mail/compact", {
method: "POST",
headers: headers(true),
body: JSON.stringify(body || {}),
});
export const cloudflareDomains = () => api("/api/mail/cloudflare/domains");
+90
View File
@@ -0,0 +1,90 @@
export function escapeHtml(s) {
return String(s ?? "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
export function dash(v) {
return v == null || v === "" ? "—" : String(v);
}
export function fmtNum(v) {
return v == null || v === "" ? "—" : String(v);
}
export function pct(a, b) {
if (b == null || a == null || Number(b) <= 0) return null;
return Math.max(0, Math.min(100, (Number(a) / Number(b)) * 100));
}
/** Collapse Cloudflare / HTML error pages into a short operator-facing line. */
export function summarizeErrorText(raw, status) {
const text = String(raw ?? "").trim();
if (!text) return status ? `HTTP ${status}` : "unknown error";
const looksHtml =
/<!DOCTYPE\s+html/i.test(text) ||
/<html[\s>]/i.test(text) ||
/<\/html>/i.test(text) ||
/<title>/i.test(text);
const mCode =
text.match(/Error code\s+(\d{3})/i) ||
text.match(/\bError\s+(\d{3})\b/i) ||
text.match(/\b(52[0-9]|50[0-9])\s*:\s*A timeout occurred/i);
const title =
(text.match(/<title[^>]*>([^<]+)<\/title>/i) || [])[1] ||
(text.match(/A timeout occurred/i) ? "A timeout occurred" : "");
const code = mCode
? Number(mCode[1])
: status && Number(status) >= 400
? Number(status)
: null;
if (looksHtml || (code && code >= 500 && text.length > 180)) {
if (code === 524 || /timeout occurred/i.test(text) || /524/.test(title)) {
return (
"Таймаут шлюза (Cloudflare 524): origin обрабатывал слишком долго." +
"Сузьте диапазон/префикс проверки или повторите позже (долгие задачи переведены на параллельную проверку)."
);
}
if (code === 502 || code === 503 || code === 504) {
return `Ошибка шлюза (HTTP ${code}): origin временно недоступен, повторите позже.`;
}
if (code) {
const shortTitle = String(title || "")
.replace(/\s*\|\s*.*$/, "")
.trim()
.slice(0, 80);
return shortTitle
? `HTTP ${code}: ${shortTitle}`
: `HTTP ${code}: origin вернул страницу ошибки`;
}
return "Origin вернул HTML-страницу ошибки (тело опущено)";
}
// strip accidental HTML tags if a short fragment leaked
let one = text.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
if (one.length > 240) one = `${one.slice(0, 220)}…`;
return one;
}
export function formatApiError(e) {
if (!e) return "unknown error";
if (typeof e === "string") return summarizeErrorText(e);
const status = e.status;
const msg = e.message != null ? e.message : String(e);
const summary = summarizeErrorText(msg, status);
// summarizeErrorText already prefixes HTTP codes for HTML pages; avoid double "524: 524:"
if (status && !/^HTTP\s+\d+/.test(summary) && !summary.includes(String(status))) {
return `${status}: ${summary}`;
}
return summary;
}
export function healthBadge(h) {
if (h === "ok" || h === true) return { label: "ok", cls: "ok" };
if (h === "fail" || h === false) return { label: "fail", cls: "danger" };
return { label: "?", cls: "muted" };
}
+22
View File
@@ -0,0 +1,22 @@
// Shared API-call helpers: JSON pretty-printing + 401 session handling.
// Extracted from the four identical copies previously inlined in
// Settings / MailTab / NodesTab / ImportTab.
import { session } from "../store/session.js";
/** JSON.stringify with 2-space indent; strings pass through; never throws. */
export function pretty(v) {
try {
return typeof v === "string" ? v : JSON.stringify(v, null, 2);
} catch {
return String(v);
}
}
/** On a 401 error, drop the session so LoginGate shows. Returns true if handled. */
export function auth401(e) {
if (e && e.status === 401) {
session.value = { ...session.value, authenticated: false };
return true;
}
return false;
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, it, expect, beforeEach } from "vitest";
import { pretty, auth401 } from "./http.js";
import { session } from "../store/session.js";
const BASE = {
authenticated: true,
username: "op",
auth_required: true,
password_login_enabled: true,
users_configured: true,
checked: true,
};
beforeEach(() => {
session.value = { ...BASE };
});
describe("pretty", () => {
it("passes strings through unchanged", () => {
expect(pretty("hi")).toBe("hi");
expect(pretty("")).toBe("");
});
it("pretty-prints objects with 2-space indent", () => {
expect(pretty({ a: 1 })).toBe('{\n "a": 1\n}');
});
it("falls back to String() on circular refs", () => {
const o = {};
o.self = o;
expect(pretty(o)).toBe("[object Object]");
});
});
describe("auth401", () => {
it("returns false and leaves session alone for non-401", () => {
expect(auth401({ status: 500 })).toBe(false);
expect(session.value.authenticated).toBe(true);
});
it("returns false for null/undefined", () => {
expect(auth401(null)).toBe(false);
expect(auth401(undefined)).toBe(false);
expect(session.value.authenticated).toBe(true);
});
it("returns true and clears authenticated on 401", () => {
expect(auth401({ status: 401 })).toBe(true);
expect(session.value.authenticated).toBe(false);
});
it("keeps the rest of the session fields intact", () => {
auth401({ status: 401 });
expect(session.value.username).toBe("op");
expect(session.value.checked).toBe(true);
});
});
+56
View File
@@ -0,0 +1,56 @@
// Shared email-provider pool helpers (Register / Settings / RegForm).
// Keep in sync with runtime _EMAIL_PROVIDER_POOL_KNOWN in grok_register_ttk.py.
export const EMAIL_PROVIDERS = [
"cloudflare",
"cloudmail",
"duckmail",
"yyds",
"gmail",
"hotmail",
];
export const EMAIL_PROVIDER_STRATEGIES = ["round_robin", "random", "failover"];
export function normalizeProviderName(raw) {
let p = String(raw || "")
.trim()
.toLowerCase();
if (p === "outlook" || p === "outlookmail" || p === "microsoft") p = "hotmail";
if (p === "google" || p === "googlemail") p = "gmail";
return p;
}
/** Parse multi-select from array or comma/space string; dedupe; known only. */
export function normalizeProvidersList(raw) {
const parts = Array.isArray(raw)
? raw
: String(raw || "")
.split(/[,,;\s]+/)
.filter(Boolean);
const out = [];
const seen = new Set();
for (const item of parts) {
const p = normalizeProviderName(item);
if (!p || !EMAIL_PROVIDERS.includes(p) || seen.has(p)) continue;
seen.add(p);
out.push(p);
}
return out;
}
/**
* Resolve pool from config.email_providers, else single email_provider.
* Console Register/Settings load multi-only (no singleton promote) so a Settings
* clear-pool stays empty across Reload/Save. Use this helper only where
* runtime-style "multi or singleton" display is intentional.
* @param {object} c
* @param {{ fallback?: string[] }} [opts]
*/
export function providersFromConfig(c, { fallback = [] } = {}) {
const multi = normalizeProvidersList(c && c.email_providers);
if (multi.length) return multi;
const single = normalizeProviderName(c && c.email_provider);
if (single && EMAIL_PROVIDERS.includes(single)) return [single];
return Array.isArray(fallback) ? fallback.slice() : [];
}
+81
View File
@@ -0,0 +1,81 @@
import { describe, it, expect } from "vitest";
import {
normalizeProviderName,
normalizeProvidersList,
providersFromConfig,
EMAIL_PROVIDERS,
} from "./providers.js";
describe("normalizeProviderName", () => {
it("maps outlook aliases to hotmail", () => {
expect(normalizeProviderName("Outlook")).toBe("hotmail");
expect(normalizeProviderName("microsoft")).toBe("hotmail");
expect(normalizeProviderName(" outlookmail ")).toBe("hotmail");
});
it("maps google aliases to gmail", () => {
expect(normalizeProviderName("GoogleMail")).toBe("gmail");
expect(normalizeProviderName("google")).toBe("gmail");
});
it("returns empty string for blank input", () => {
expect(normalizeProviderName(null)).toBe("");
expect(normalizeProviderName(" ")).toBe("");
});
});
describe("normalizeProvidersList", () => {
it("parses comma / space / full-width separators", () => {
expect(normalizeProvidersList("gmail, hotmail cloudflare")).toEqual([
"gmail",
"hotmail",
"cloudflare",
]);
});
it("dedupes and drops unknown", () => {
expect(normalizeProvidersList(["gmail", "gmail", "bogus"])).toEqual(["gmail"]);
});
it("accepts arrays and preserves input order", () => {
expect(normalizeProvidersList(EMAIL_PROVIDERS)).toEqual(EMAIL_PROVIDERS);
expect(normalizeProvidersList(["hotmail", "cloudflare"])).toEqual([
"hotmail",
"cloudflare",
]);
});
it("normalizes aliases while deduping", () => {
expect(normalizeProvidersList("outlook,hotmail,google")).toEqual([
"hotmail",
"gmail",
]);
});
it("empty in → empty out", () => {
expect(normalizeProvidersList("")).toEqual([]);
expect(normalizeProvidersList(null)).toEqual([]);
expect(normalizeProvidersList([])).toEqual([]);
});
});
describe("providersFromConfig", () => {
it("prefers multi over singleton", () => {
expect(
providersFromConfig({ email_providers: ["gmail"], email_provider: "hotmail" }),
).toEqual(["gmail"]);
});
it("falls back to singleton when multi empty", () => {
expect(
providersFromConfig({ email_providers: [], email_provider: "hotmail" }),
).toEqual(["hotmail"]);
});
it("drops an unknown singleton and uses the fallback", () => {
expect(
providersFromConfig({ email_provider: "bogus" }, { fallback: ["yyds"] }),
).toEqual(["yyds"]);
});
it("returns a copy of the fallback, not the same array", () => {
const fallback = ["yyds"];
const out = providersFromConfig({}, { fallback });
expect(out).toEqual(["yyds"]);
expect(out).not.toBe(fallback);
});
it("tolerates null config", () => {
expect(providersFromConfig(null)).toEqual([]);
});
});
+17
View File
@@ -0,0 +1,17 @@
// Single-slot busy-tag state. Replaces the setBusy("tag") / busy === "tag"
// string pairs that were duplicated across every ops page.
import { useCallback, useState } from "preact/hooks";
export function useBusy(initial = "") {
const [busy, setBusy] = useState(initial);
const is = useCallback((tag) => busy === tag, [busy]);
const run = useCallback(async (tag, fn) => {
setBusy(tag);
try {
return await fn();
} finally {
setBusy("");
}
}, []);
return { busy, setBusy, is, any: busy !== "", run };
}
+62
View File
@@ -0,0 +1,62 @@
import { describe, it, expect } from "vitest";
import { render, screen, waitFor } from "@testing-library/preact";
import { useBusy } from "./useBusy.js";
function Probe({ onReady }) {
const b = useBusy();
onReady(b);
return <span data-testid="busy">{`${b.busy}|${b.is("save")}|${b.any}`}</span>;
}
describe("useBusy", () => {
it("starts idle", () => {
render(<Probe onReady={() => {}} />);
expect(screen.getByTestId("busy").textContent).toBe("|false|false");
});
it("sets tag during run and clears after", async () => {
let api;
render(
<Probe
onReady={(b) => {
api = b;
}}
/>,
);
let release;
const p = api.run(
"save",
() =>
new Promise((r) => {
release = r;
}),
);
await waitFor(() =>
expect(screen.getByTestId("busy").textContent).toBe("save|true|true"),
);
release("done");
await expect(p).resolves.toBe("done");
await waitFor(() =>
expect(screen.getByTestId("busy").textContent).toBe("|false|false"),
);
});
it("clears the tag and rethrows when fn throws", async () => {
let api;
render(
<Probe
onReady={(b) => {
api = b;
}}
/>,
);
await expect(
api.run("save", async () => {
throw new Error("boom");
}),
).rejects.toThrow("boom");
await waitFor(() =>
expect(screen.getByTestId("busy").textContent).toBe("|false|false"),
);
});
});
+130
View File
@@ -0,0 +1,130 @@
// Shared hydrated / dirty / baseline / clearable-confirm skeleton for the
// config-editing pages (Settings, Resources→Почта). Extracted with behavior
// strictly unchanged; every page-specific decision (messages, hydrate
// mapping, PUT payload, post-save rehydrate) stays in the page via callbacks.
//
// Invariants owned here (locked by SettingsPage.test.jsx / MailTab.test.jsx):
// 1. Save is a no-op until a GET succeeded (hydrated) and no load is running.
// 2. GET 401 → session cleared (auth401) and hydrated=false so Save stays blocked.
// 3. load({force:true}) while dirty asks window.confirm first; cancel = no GET.
// 4. Clearing a clearable field asks window.confirm on save; cancel = no PUT.
// 5. Successful save clears dirty and applies the page's rehydrate result.
//
// Option callbacks (all page-provided; see Settings/MailTab for usage):
// loadRequest: async () => config — GET + unwrap
// hydrate: (config) => { form, baseline } — map config into page state
// onLoaded?: async (config, form) — post-load side effects
// onLoadError?: (e) — non-401 load failure feedback
// confirmReload: { message, onCancel? } — dirty-reload confirm copy
// onSaveBlocked?: () — Save clicked before hydrated
// confirmClear?: (form, baseline) => { message } | null
// onSaveCancelled?: () — clearable confirm declined
// saveRequest: async (form) => data — build partial + PUT
// onSaved?: (data, form) => { form?, baseline? } | void
// onSaveError?: (e) — non-401 save failure feedback
import { useCallback, useRef, useState } from "preact/hooks";
import { auth401 } from "./http.js";
import { useBusy } from "./useBusy.js";
export function useConfigForm(options) {
const { empty, initialBaseline } = options;
const [form, setForm] = useState(empty);
const [hydrated, setHydrated] = useState(false);
const [dirty, setDirty] = useState(false);
const [baseline, setBaseline] = useState(initialBaseline);
const busyApi = useBusy();
const { setBusy, is: busyIs } = busyApi;
// Callbacks read page state (e.g. primaryProvider) — keep them fresh via a
// ref so load/save never close over a stale render.
const opts = useRef(options);
opts.current = options;
const set = useCallback((partial) => {
setDirty(true);
setForm((p) => ({ ...p, ...partial }));
}, []);
const load = useCallback(
async ({ force = false } = {}) => {
const o = opts.current;
if (force && dirty) {
if (!window.confirm(o.confirmReload.message)) {
o.confirmReload.onCancel?.();
return;
}
}
setBusy("load");
try {
const config = await o.loadRequest();
const next = o.hydrate(config);
setForm(next.form);
setBaseline(next.baseline);
setDirty(false);
setHydrated(true);
await o.onLoaded?.(config, next.form);
} catch (e) {
// Always clear hydrated on failure (incl. 401) so Save stays blocked.
setHydrated(false);
if (auth401(e)) return;
o.onLoadError?.(e);
} finally {
setBusy("");
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[dirty],
);
const save = useCallback(async () => {
const o = opts.current;
if (!hydrated || busyIs("load")) {
o.onSaveBlocked?.();
return;
}
const clearing = o.confirmClear?.(form, baseline);
if (clearing) {
if (!window.confirm(clearing.message)) {
o.onSaveCancelled?.();
return;
}
}
setBusy("save");
try {
const data = await o.saveRequest(form);
const next = o.onSaved?.(data, form);
if (next && next.form !== undefined) {
setForm((p) =>
typeof next.form === "function" ? next.form(p) : next.form,
);
}
if (next && next.baseline !== undefined) setBaseline(next.baseline);
setDirty(false);
} catch (e) {
if (auth401(e)) {
setHydrated(false);
return;
}
o.onSaveError?.(e);
} finally {
setBusy("");
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hydrated, form, baseline, busyIs]);
return {
form,
set,
setForm,
hydrated,
setHydrated,
dirty,
setDirty,
baseline,
setBaseline,
load,
save,
...busyApi,
busyIs,
};
}
+7
View File
@@ -0,0 +1,7 @@
import { render } from "preact";
import { App } from "./App.jsx";
import "./styles/tokens.css";
import "./styles/base.css";
import "./styles/components.css";
render(<App />, document.getElementById("root"));
@@ -0,0 +1,278 @@
// src/pages/Accounts/AccountsPage.jsx
// Account pool: filter + paginate cpa_auths (complete = access+refresh on disk).
// Delete is local-only (DELETE /api/accounts/{name}); does not touch tebi.
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import * as api from "../../api/client.js";
import { showOpsFeedback } from "../../store/feedback.js";
import { Button, Select, Kpi, PageHeader, LogDetails } from "../../ui/index.js";
import { formatApiError } from "../../lib/format.js";
import { auth401 } from "../../lib/http.js";
import "../../styles/accounts.css";
const COMPLETE_OPTS = [
{ value: "", label: "Все" },
{ value: "1", label: "только complete" },
{ value: "0", label: "только incomplete" },
];
const PAGE_SIZE_OPTS = [
{ value: "25", label: "25" },
{ value: "50", label: "50" },
{ value: "100", label: "100" },
];
function buildAccountsQuery({ q, complete, page, pageSize }) {
const params = new URLSearchParams();
const qq = (q || "").trim();
if (qq) params.set("q", qq);
if (complete !== "" && complete != null) params.set("complete", complete);
params.set("page", String(page || 1));
params.set("page_size", String(pageSize || 50));
return params.toString();
}
export function AccountsPage() {
const [q, setQ] = useState("");
const [complete, setComplete] = useState("");
const [pageSize, setPageSize] = useState("50");
const [page, setPage] = useState(1);
const [data, setData] = useState(null);
const [err, setErr] = useState("");
const [result, setResult] = useState("");
const [busy, setBusy] = useState(false);
const qTimer = useRef(null);
const qFirst = useRef(true);
// Keep latest filters for debounced load without stale closures.
const filtersRef = useRef({ q: "", complete: "", pageSize: "50", page: 1 });
filtersRef.current = { q, complete, pageSize, page };
const load = useCallback(async (override = {}) => {
const f = { ...filtersRef.current, ...override };
const pg = f.page != null ? f.page : 1;
setBusy(true);
setErr("");
try {
const qs = buildAccountsQuery({
q: f.q,
complete: f.complete,
page: pg,
pageSize: f.pageSize,
});
const res = await api.listAccounts(qs);
setData(res);
if (override.page != null) setPage(override.page);
else if (res && res.page != null) setPage(res.page);
} catch (e) {
if (auth401(e)) return;
setData(null);
setErr(formatApiError(e));
} finally {
setBusy(false);
}
}, []);
// Initial load
useEffect(() => {
load({ page: 1 });
}, [load]);
// Debounced search (skip mount — initial load handles first paint)
useEffect(() => {
if (qFirst.current) {
qFirst.current = false;
return undefined;
}
if (qTimer.current) clearTimeout(qTimer.current);
qTimer.current = setTimeout(() => {
setPage(1);
load({ page: 1, q });
}, 300);
return () => {
if (qTimer.current) clearTimeout(qTimer.current);
};
}, [q, load]);
function onCompleteChange(v) {
setComplete(v);
setPage(1);
load({ page: 1, complete: v });
}
function onPageSizeChange(v) {
setPageSize(v);
setPage(1);
load({ page: 1, pageSize: v });
}
async function onDelete(name) {
if (!name) return;
if (!window.confirm(`Удалить ${name}? Удаляет только локальный cpa_auths, не влияет на tebi.`)) {
return;
}
try {
const r = await api.deleteAccount(name);
setResult(typeof r === "string" ? r : JSON.stringify(r, null, 2));
showOpsFeedback(`Удалено ${name}`, "ok", { toast: true, sticky: false });
await load();
} catch (e) {
if (auth401(e)) return;
setResult(String(e.message || e));
showOpsFeedback(`Ошибка удаления: ${formatApiError(e)}`, "err");
}
}
const items = (data && data.items) || [];
const total = data ? data.total || 0 : 0;
const c = data ? data.complete || 0 : 0;
const inc = Math.max(0, total - c);
const dc = data && data.disk_complete != null ? data.disk_complete : null;
const pages = data ? data.pages || 1 : 1;
const curPage = data ? data.page || page : page;
return (
<section class="page page-accounts">
<PageHeader
title="Пул аккаунтов"
hint={
<>
cpa_auths пишет на диск complete (access+refresh). Основной путь регистрации заканчивается на диске; импорт в tebi идёт отдельно
Import。
</>
}
>
<Button variant="ghost" busy={busy} onClick={() => load()}>
Обновить
</Button>
</PageHeader>
<div class="card filter-bar">
<label class="inline">
Поиск{" "}
<input
type="search"
value={q}
placeholder="email / имя файла"
onInput={(e) => setQ(e.currentTarget.value)}
/>
</label>
<label class="inline">
Полнота{" "}
<Select
value={complete}
options={COMPLETE_OPTS}
onChange={onCompleteChange}
/>
</label>
<label class="inline">
На стр.{" "}
<Select
value={pageSize}
options={PAGE_SIZE_OPTS}
onChange={onPageSizeChange}
/>
</label>
<Button
variant="ghost"
size="sm"
disabled={curPage <= 1 || busy}
onClick={() => load({ page: Math.max(1, curPage - 1) })}
>
Назад
</Button>
<Button
variant="ghost"
size="sm"
disabled={curPage >= pages || busy}
onClick={() => load({ page: curPage + 1 })}
>
Вперёд
</Button>
<span class="hint">
page {curPage}/{pages}
</span>
</div>
{err ? (
<p class="hint err-text">{err}</p>
) : (
<div class="kpi-grid compact acc-summary">
<Kpi
label="итого (эта стр.)"
value={String(total)}
hint={data?.path ? `path=${data.path}` : ""}
/>
<Kpi
label="complete"
value={String(c)}
hint={`стр. ${curPage}/${pages}`}
class={c > 0 ? "ok" : ""}
/>
<Kpi
label="incomplete"
value={String(inc)}
class={inc > 0 ? "warn" : ""}
/>
{dc != null ? (
<Kpi label="disk complete" value={String(dc)} hint="Полный" class="ok" />
) : null}
</div>
)}
<div class="card table-wrap">
<table class="data">
<thead>
<tr>
<th>Статус</th>
<th>email</th>
<th>mtime</th>
<th>priority</th>
<th>kind</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
{!items.length ? (
<tr>
<td colspan="6" class="hint">
Нет аккаунтов
</td>
</tr>
) : (
items.map((it) => (
<tr key={it.name || it.email}>
<td>
<span class={`badge ${it.complete ? "ok" : "fail"}`}>
{it.complete ? "complete" : "incomplete"}
</span>{" "}
{it.disabled ? (
<span class="badge fail">disabled</span>
) : null}{" "}
{it.expired ? <span class="badge fail">expired</span> : null}
</td>
<td>
<div>{it.email || ""}</div>
<div class="hint">{it.name || ""}</div>
</td>
<td>{it.mtime_iso || ""}</td>
<td>{it.priority != null ? String(it.priority) : "—"}</td>
<td>{it.auth_kind || "—"}</td>
<td class="ops">
<Button
variant="danger"
size="sm"
onClick={() => onDelete(it.name)}
>
Удалить
</Button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
<LogDetails text={result} summary="Детали ответа операции" compact />
</section>
);
}
+83
View File
@@ -0,0 +1,83 @@
import { useState } from "preact/hooks";
import * as api from "../api/client.js";
import { session } from "../store/session.js";
import { Button } from "../ui/Button.jsx";
export function LoginGate() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
async function onSubmit(e) {
e.preventDefault();
if (busy) return;
setBusy(true);
setError("");
try {
await api.login(username.trim(), password);
const m = await api.me();
session.value = {
...session.value,
...m,
authenticated: true,
username: (m && m.username) || username.trim(),
checked: true,
};
} catch (err) {
setError((err && err.message) || "Ошибка входа");
} finally {
setBusy(false);
}
}
return (
<div class="login-gate">
<form class="login-card" autocomplete="on" onSubmit={onSubmit}>
<h1>Вход в Control Plane</h1>
<p class="hint">Нужны логин/пароль оператора. Скрипты могут использовать Bearer token.</p>
<p class="hint brand-line">
Open-source проект{" "}
<a
href="https://github.com/dengyie/ai-register-machine"
target="_blank"
rel="noopener noreferrer"
>
ai-register-machine
</a>
</p>
<label>
Логин{" "}
<input
name="username"
autocomplete="username"
placeholder="admin"
required
value={username}
onInput={(e) => setUsername(e.currentTarget.value)}
/>
</label>
<label>
Пароль{" "}
<input
name="password"
type="password"
autocomplete="current-password"
placeholder="Пароль"
required
value={password}
onInput={(e) => setPassword(e.currentTarget.value)}
/>
</label>
<div class="actions">
<Button variant="primary" type="submit" busy={busy}>
Войти
</Button>
</div>
<p class="error" role="alert">
{error}
</p>
</form>
</div>
);
}
+333
View File
@@ -0,0 +1,333 @@
// src/pages/Register/RegForm.jsx
// Left panel: start parameters. Email channel is multi-select only —
// per-provider secrets/domains live on Resources → Почта; pipeline pool
// on Settings. State is lifted to RegisterPage so the 4s poll never wipes edits.
import { useEffect } from "preact/hooks";
import { Field, Select, ProviderPoolStatus } from "../../ui/index.js";
import { regFormDirty } from "../../store/run.js";
import {
EMAIL_PROVIDERS,
normalizeProvidersList,
} from "../../lib/providers.js";
const DEFAULTS = {
email_providers: [],
target: 100,
threads: 1,
mode: "ordinary",
tag: "batch_web",
chunk: 3,
turnstile: 150,
probeChat: false,
ssoOnly: true,
batchEndInject: false,
importEvery: 100,
importSize: "",
importPause: "",
proxyMode: "clash",
proxy: "",
proxyList: "",
kind: "grok_supervisor",
product: "grok",
skipPreflight: false,
nodeScore: "",
syncMailEnv: true,
};
export function RegForm({
value,
onChange,
advancedOpen,
onToggleAdvanced,
residualPrimary = "",
}) {
useEffect(() => {
// dirty handling is done in field onChange below
}, []);
const v = { ...DEFAULTS, ...value };
const isSupervisor = (v.kind || "grok_supervisor") === "grok_supervisor";
const selected = normalizeProvidersList(v.email_providers);
function set(partial) {
regFormDirty.value = true;
onChange({ ...v, ...partial });
}
function toggleProvider(name) {
const cur = new Set(selected);
if (cur.has(name)) cur.delete(name);
else cur.add(name);
// preserve EMAIL_PROVIDERS order
set({ email_providers: EMAIL_PROVIDERS.filter((p) => cur.has(p)) });
}
return (
<form class="stack-form" onSubmit={(e) => e.preventDefault()}>
<div class="field-grid">
<Field label="Почтовые сервисы (мультивыбор)" span2>
<div class="provider-multi mail-domain-chips">
{EMAIL_PROVIDERS.map((p) => (
<label key={p} class="check chip">
<input
type="checkbox"
checked={selected.includes(p)}
onChange={() => toggleProvider(p)}
/>{" "}
{p}
</label>
))}
</div>
<ProviderPoolStatus
selected={selected}
primaryProvider={residualPrimary}
canClear={false}
/>
<p class="hint tight">
Выбор каналов только для этого батча (общий с настройками <code>email_providers</code>). Ключи / домены →{" "}
<a href="#/resources?tab=mail">Ресурсы · Почта</a>; стратегия опроса →{" "}
<a href="#/settings">Настройки</a>
</p>
{!selected.length ? (
<p class="hint warn tight">
Отметьте хотя бы один для запуска
{residualPrimary ? `(страница регистрации не отмечает автоматически остаточный одиночный канал)` : ""}。
</p>
) : null}
</Field>
<Field label="Количество target">
<input
type="number"
min="1"
value={v.target}
onInput={(e) =>
set({ target: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value) })
}
/>
</Field>
<Field label="Потоки threads">
<input
type="number"
min="1"
max="32"
value={v.threads}
onInput={(e) =>
set({ threads: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value) })
}
/>
</Field>
<Field label="Режим">
<Select
options={[
{ value: "ordinary", label: "ordinary · Clash (дата-центр)" },
{ value: "residential", label: "residential · резидентные" },
]}
value={v.mode}
onChange={(val) => set({ mode: val })}
/>
</Field>
<Field label="tag">
<input value={v.tag} onInput={(e) => set({ tag: e.currentTarget.value })} />
</Field>
</div>
<div class="info-box">По умолчанию disk-first: без mid-tebi инъекции. Полные логи на странице «Логи».</div>
<details class="advanced" open={advancedOpen} onToggle={onToggleAdvanced}>
<summary>Расширенный запуск · параметры батча / прокси / kind / product / SKIP_CLASH / NODE_SCORE</summary>
<div class="field-grid">
<Field label="SUPERVISOR_CHUNK" class={isSupervisor ? "" : "hidden"}>
<input
type="number"
min="1"
max="20"
value={v.chunk}
disabled={!isSupervisor}
onInput={(e) =>
set({ chunk: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value) })
}
/>
</Field>
<Field label="Таймаут зависания Turnstile (сек)">
<input
type="number"
min="5"
value={v.turnstile}
onInput={(e) =>
set({
turnstile: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value),
})
}
/>
</Field>
<label class="check muted" title="Supervisor жёстко задаёт CPA_PROBE_CHAT=false">
<input type="checkbox" checked={false} disabled /> Chat-проба после регистрации (принудительно выкл)
</label>
<label
class="check"
title="Инфо: mid-mint никогда не инжектится в tebi (контракт disk-first); снятие галочки не включает mid-mint inject"
>
<input
type="checkbox"
checked={v.ssoOnly}
onChange={(e) => set({ ssoOnly: e.currentTarget.checked })}
/>{" "}
Только запись auth на диск (по умолчанию · инфо)
</label>
<label class="check" title="только граница батча CPA_BATCH_END_INJECT">
<input
type="checkbox"
checked={v.batchEndInject}
disabled={!isSupervisor}
onChange={(e) => set({ batchEndInject: e.currentTarget.checked })}
/>{" "}
Авто-импорт CPA на границе батча
</label>
<Field label="CPA_BATCH_IMPORT_EVERY" class={isSupervisor ? "" : "hidden"}>
<input
type="number"
min="1"
value={v.importEvery}
disabled={!isSupervisor}
onInput={(e) =>
set({
importEvery: e.currentTarget.value === "" ? "" : Number(e.currentTarget.value),
})
}
/>
</Field>
<Field label="Стратегия прокси proxy_rotate_mode">
<Select
options={[
{ value: "clash", label: "clash · ротация встроенного пула узлов" },
{ value: "list", label: "list · PROXY_LIST / proxy_list" },
{ value: "off", label: "off · фиксированный выход" },
]}
value={v.proxyMode}
onChange={(val) => set({ proxyMode: val })}
/>
</Field>
<Field label="Фиксированный proxy URL">
<input
placeholder="http://127.0.0.1:7897"
value={v.proxy}
onInput={(e) => set({ proxy: e.currentTarget.value })}
/>
</Field>
<Field label="Пул прокси proxy_list / PROXY_LIST" span2>
<textarea
rows="4"
placeholder="По одному прокси на строку; запись только непустых; очистка — на странице настроек"
value={v.proxyList}
onInput={(e) => set({ proxyList: e.currentTarget.value })}
/>
<p class="hint tight">
Пустое поле здесь <strong>НЕ</strong> очищает серверный <code>PROXY_LIST</code>
(очистка clearable в
<a href="#/settings">Настройки</a>)。
</p>
</Field>
<Field label="kind">
<Select
options={[
{ value: "grok_supervisor", label: "grok_supervisor · пакетный надзор" },
{ value: "register_sh", label: "register_sh · одиночная оболочка" },
]}
value={v.kind}
onChange={(val) =>
set({ kind: val, product: val === "grok_supervisor" ? "grok" : v.product })
}
/>
</Field>
<Field label="product">
<Select
options={[
{ value: "grok", label: "grok (оригинал)" },
{ value: "mimo", label: "mimo (оригинал)" },
{ value: "chatgpt", label: "chatgpt (оригинал)" },
{ value: "typesafe", label: "typesafe (оригинал)" },
{ value: "vip7891", label: "⚡ vip7891 · new-api GH-OAuth" },
{ value: "agentrouter", label: "⚡ agentrouter · GH-OAuth" },
{ value: "conol", label: "⚡ conol.ai · 600cr" },
{ value: "vani", label: "⚡ vani.ai" },
{ value: "notion", label: "⚡ notion · Opus-ферма" },
{ value: "kiro", label: "⚡ kiro · BuilderID" },
{ value: "type", label: "⚡ type.com · voidash+SMS" },
{ value: "llmtr", label: "⚡ llmtr.com" },
{ value: "xkiro", label: "⚡ xkiro · TG-верификация" },
{ value: "omnirush", label: "⚡ omnirush.ai" },
{ value: "gname", label: "⚡ gname.com · слайдер" },
{ value: "abliteration", label: "⚡ abliteration.ai · квесты" },
{ value: "terrapolis", label: "⚡ terrapolis.xyz · 15M" },
{ value: "cleanapis", label: "⚡ cleanapis.com · GH-OAuth" },
{ value: "miarouter", label: "⚡ miarouter.online · TG-miniapp" },
{ value: "treg", label: "⚡ treg.to · voidash $1" },
]}
value={isSupervisor ? "grok" : v.product}
disabled={isSupervisor}
onChange={(val) =>
set(
["grok", "mimo", "chatgpt", "typesafe"].includes(val)
? { product: val }
: { product: val, kind: "register_sh" }
)
}
/>
</Field>
<label class="check" title="SKIP_CLASH_PREFLIGHT=1 пропускает пред-проверку Clash перед батчем; по умолчанию выкл">
<input
type="checkbox"
checked={v.skipPreflight}
onChange={(e) => set({ skipPreflight: e.currentTarget.checked })}
/>{" "}
Пропустить пред-проверку Clash перед батчем
</label>
<Field label="NODE_SCORE">
<Select
options={[
{ value: "", label: "(не передаётся, берётся из env)" },
{ value: "1", label: "1 · сортировка по скору" },
{ value: "0", label: "0 · скоринг выкл" },
]}
value={v.nodeScore}
onChange={(val) => set({ nodeScore: val })}
/>
</Field>
<Field label="CPA_BATCH_IMPORT_SIZE" class={isSupervisor ? "" : "hidden"}>
<input
type="number"
min="1"
placeholder="100"
value={v.importSize}
disabled={!isSupervisor}
onInput={(e) => set({ importSize: e.currentTarget.value })}
/>
</Field>
<Field label="CPA_BATCH_IMPORT_PAUSE" class={isSupervisor ? "" : "hidden"}>
<input
type="number"
min="0"
placeholder="3"
value={v.importPause}
disabled={!isSupervisor}
onInput={(e) => set({ importPause: e.currentTarget.value })}
/>
</Field>
<label
class="check span2"
title="При старте синхронизировать отмеченные EMAIL_PROVIDERS в extra_env (перекрывает одиночный канал .env)"
>
<input
type="checkbox"
checked={v.syncMailEnv}
onChange={(e) => set({ syncMailEnv: e.currentTarget.checked })}
/>{" "}
Синхронизировать EMAIL_PROVIDERS в extra_env
</label>
</div>
</details>
</form>
);
}
@@ -0,0 +1,562 @@
// src/pages/Register/RegisterPage.jsx
// Register / control home: left form + right progress. Full parity with legacy
// register UX (apps/web/legacy/assets/app.js register + renderRunStatus pipeline).
//
// Key behaviors:
// - 4s poll of api.currentRun() + api.overview(); never wipes form while
// regFormDirty.value === true; form loaded from config only once.
// - startRun body keys mirror legacy (kind/product/mode/target/threads/
// tag/extra_env{SUPERVISOR_CHUNK,CPA_BATCH_END_INJECT,CPA_BATCH_IMPORT_*,
// CPA_PROBE_CHAT=false,SKIP_CLASH_PREFLIGHT,NODE_SCORE,EMAIL_PROVIDERS,
// EMAIL_PROVIDER}). Secrets/domains are NOT written from this page.
// - stopRun: window.confirm Chinese warning first.
// - putConfig wrapped as { config: partial } (backend ConfigPutIn schema).
// - 401 → session.authenticated=false (gate shows).
// - интерфейс/эксплуатация: Сохранить / self-check(link #/settings) / Тест прокси. No duplicate cleanup/selfcheck
// buttons here (spec IA — selfcheck lives on settings).
import { useEffect, useState, useCallback } from "preact/hooks";
import * as api from "../../api/client.js";
import { auth401 } from "../../lib/http.js";
import { showOpsFeedback } from "../../store/feedback.js";
import {
currentRunState,
overviewState,
regFormDirty,
regFormLoaded,
lastProductOk,
} from "../../store/run.js";
import { PageHeader } from "../../ui/index.js";
import { RegForm } from "./RegForm.jsx";
import { RunProgress } from "./RunProgress.jsx";
import { formatApiError as formatApiErrorShared } from "../../lib/format.js";
import { normalizeProvidersList } from "../../lib/providers.js";
import "../../styles/run.css";
// Initial form state (also used before config loads). Mirrors legacy defaults.
// Email: multi-select pool only — secrets/domains on Resources, strategy on Settings.
// email_providers starts empty until GET /api/config (no singleton pre-fill).
const initialForm = {
email_providers: [],
target: 100,
threads: 1,
mode: "ordinary",
tag: "batch_web",
chunk: 3,
turnstile: 150,
ssoOnly: true,
batchEndInject: false,
importEvery: 100,
importSize: "",
importPause: "",
proxyMode: "clash",
proxy: "",
proxyList: "",
kind: "grok_supervisor",
product: "grok",
skipPreflight: false,
nodeScore: "",
syncMailEnv: true,
};
function formatApiError(e) {
if (!e) return "Неизвестная ошибка";
if (e.status === 409) {
const msg = String(e.message || e);
return `Задача уже выполняется (${msg}). Главная покажет текущий progress; для остановки нажмите «Стоп» (убьёт внешний supervisor).`;
}
if (e.status === 401) return "Не авторизованы или сессия истекла — войдите заново.";
if (e.status === 422) return `Ошибка валидации параметров: ${formatApiErrorShared(e)}`;
return formatApiErrorShared(e);
}
function snapshotFormFromConfig(c, prev) {
// No prev → first load: apply defaults, then overlay config protocol bits
// (email pool / proxy / turnstile). Run params stay at HTML defaults.
// prev → forced refresh: re-hydrate protocol bits but PRESERVE user edits to
// run params.
// Multi-list only — never promote singleton email_provider into chips
// (Settings clear-pool must survive Register load/save).
const f = { ...initialForm, ...(prev || {}) };
f.email_providers = normalizeProvidersList(c.email_providers);
if (c.proxy != null) f.proxy = String(c.proxy);
if (c.proxy_rotate_mode) f.proxyMode = c.proxy_rotate_mode;
if (c.proxy_list != null) {
const pl = c.proxy_list;
f.proxyList = Array.isArray(pl) ? pl.join("\n") : String(pl);
}
if (c.turnstile_stuck_timeout != null) {
f.turnstile = Number(c.turnstile_stuck_timeout);
}
f.probeChat = false; // supervisor hard-forced off
return f;
}
export function RegisterPage() {
const [form, setForm] = useState(initialForm);
// Residual singleton when multi is empty (Settings single-channel mode).
const [primaryProvider, setPrimaryProvider] = useState("");
const [advancedOpen, setAdvancedOpen] = useState(false);
const [busyKey, setBusyKey] = useState(null); // 'start' | 'stop' | 'save' | 'proxy' | 'refresh'
const [actionResult, setActionResult] = useState("");
// Load form from /api/config exactly once (and on explicit refresh).
const loadForm = useCallback(async ({ force = false } = {}) => {
if (regFormLoaded.value && !force) return;
if (!force && regFormDirty.value && regFormLoaded.value) return;
try {
const data = await api.getConfig();
const c = data.config || {};
setPrimaryProvider(String(c.email_provider || "").trim().toLowerCase());
setForm((prev) =>
snapshotFormFromConfig(c, force ? prev : undefined),
);
regFormLoaded.value = true;
if (force) regFormDirty.value = false;
} catch (e) {
if (auth401(e)) {
return;
}
if (force) showOpsFeedback(`Ошибка загрузки конфига: ${formatApiError(e)}`, "err");
}
}, []);
// 4s poll: run + overview only. Never destroys form edits.
useEffect(() => {
let cancelled = false;
async function tick() {
try {
const [cur, ov] = await Promise.all([api.currentRun(), api.overview()]);
if (cancelled) return;
const run = cur.run ?? cur ?? null;
currentRunState.value = run;
if (ov) {
overviewState.value = ov;
if (ov.product_ok != null) lastProductOk.value = ov.product_ok;
}
} catch (e) {
auth401(e);
// poll failures stay silent (no toast spam)
}
}
loadForm({ force: false });
tick();
const id = setInterval(tick, 4000);
return () => {
cancelled = true;
clearInterval(id);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
function gotoLogs() {
location.hash = "#/logs";
}
// Build the start body exactly mirroring legacy startRun().
function buildStartBody() {
const v = form;
const kind = v.kind || "grok_supervisor";
const product =
kind === "grok_supervisor" ? "grok" : v.product || "grok";
const extra_env = {};
if (kind === "grok_supervisor") {
const chunk = String(v.chunk ?? "").trim();
if (chunk) extra_env.SUPERVISOR_CHUNK = chunk;
extra_env.CPA_BATCH_END_INJECT = v.batchEndInject ? "true" : "false";
const every = String(v.importEvery ?? "").trim();
if (every) extra_env.CPA_BATCH_IMPORT_EVERY = every;
const size = String(v.importSize ?? "").trim();
if (size) extra_env.CPA_BATCH_IMPORT_SIZE = size;
const pause = String(v.importPause ?? "").trim();
if (pause !== "") extra_env.CPA_BATCH_IMPORT_PAUSE = pause;
}
// Universal: probe-off
extra_env.CPA_PROBE_CHAT = "false";
if (v.skipPreflight) extra_env.SKIP_CLASH_PREFLIGHT = "1";
const nodeScore = String(v.nodeScore ?? "").trim();
if (nodeScore !== "") extra_env.NODE_SCORE = nodeScore;
if (v.syncMailEnv) {
const pool = normalizeProvidersList(v.email_providers);
if (pool.length) {
extra_env.EMAIL_PROVIDERS = pool.join(",");
// Keep single EMAIL_PROVIDER aligned with first pool member for
// code paths that still read the singleton.
extra_env.EMAIL_PROVIDER = pool[0];
}
// Empty multi: do NOT inject EMAIL_PROVIDERS (would not clear disk pool
// via empty env anyway). Start is blocked unless chips are checked.
}
return {
kind,
product,
mode: v.mode || "ordinary",
target: Number(v.target == null || v.target === "" ? 100 : v.target),
threads: Number(v.threads == null || v.threads === "" ? 1 : v.threads),
tag: String(v.tag || "batch_web").trim() || "batch_web",
extra_env,
};
}
// Build the config partial from the form (save path).
// Register only writes email_providers + proxy/turnstile knobs —
// never secrets or defaultDomains (those live on Resources).
// Empty provider multi-select is OMITTED (not clearable from this page) so a
// mis-click cannot wipe the saved EMAIL_PROVIDERS pool.
// Empty proxy_list is also OMITTED — intentional clear lives on Settings.
function buildConfigPartial() {
const v = form;
const providers = normalizeProvidersList(v.email_providers);
const proxy = (v.proxy || "").trim();
const proxyList = String(v.proxyList ?? "").trim();
const partial = {
proxy_rotate_mode: v.proxyMode,
turnstile_stuck_timeout: Number(v.turnstile || 150),
// disk-first mid-mint inject always off; batch-end inject is CPA_BATCH_END_INJECT (extra_env).
cpa_remote_inject: false,
cpa_probe_chat: false,
};
if (providers.length) {
partial.email_providers = providers;
// Primary for UIs / code paths that still read the singleton.
partial.email_provider = providers[0];
}
if (proxy) partial.proxy = proxy;
// Non-empty only: blank must not clear PROXY_LIST via clearable write-through.
if (proxyList) partial.proxy_list = v.proxyList;
return { partial, providers };
}
async function saveConfig({ silent = false } = {}) {
// Never persist the pre-load default form (would risk proxy_list/provider drift).
if (!regFormLoaded.value) {
if (!silent) {
showOpsFeedback("Сначала загрузите конфиг, потом сохраняйте", "err", { toast: true, sticky: true });
}
throw new Error("config not loaded");
}
if (!silent) setBusyKey("save");
try {
const { partial, providers } = buildConfigPartial();
// Wrap in { config: partial } — backend ConfigPutIn schema.
const data = await api.putConfig({ config: partial });
regFormDirty.value = false;
regFormLoaded.value = true;
// Re-hydrate from server multi only (never singleton → chips).
const saved = data.config || {};
if (saved.email_provider != null) {
setPrimaryProvider(String(saved.email_provider || "").trim().toLowerCase());
}
const serverMulti = normalizeProvidersList(saved.email_providers);
setForm((p) => {
const next = {
...p,
// Prefer server multi. Empty form omit leaves disk multi intact →
// show server list so UI matches disk (Register cannot clear pool).
email_providers: serverMulti.length
? serverMulti
: providers.length
? providers
: [],
};
if (saved.proxy != null && String(saved.proxy).trim()) {
next.proxy = String(saved.proxy);
}
return next;
});
if (!silent) {
const envN = (data.changed_env_keys || []).length;
const envHint = envN ? ` · env×${envN}` : "";
if (!providers.length) {
const kept = serverMulti.join(",") || "∅";
showOpsFeedback(
`Конфиг сохранён · пустой выбор не изменил пул · серверные providers=${kept}${envHint}`,
"ok",
);
} else {
showOpsFeedback(
`Конфиг сохранён · providers=${providers.join(",")}${envHint}`,
"ok",
);
}
}
return data;
} catch (e) {
if (auth401(e)) {
throw e;
}
if (!silent) showOpsFeedback(`Ошибка сохранения: ${formatApiError(e)}`, "err");
throw e;
} finally {
if (!silent) setBusyKey(null);
}
}
async function refresh() {
setBusyKey("refresh");
try {
await loadForm({ force: true });
// One immediate run refresh too.
const cur = await api.currentRun();
const run = cur.run ?? cur ?? null;
currentRunState.value = run;
try {
const ov = await api.overview();
overviewState.value = ov;
if (ov && ov.product_ok != null) lastProductOk.value = ov.product_ok;
} catch {
/* render with last known */
}
const phase = (run && (run.phase_title || run.phase)) || "—";
const alive = !!(run && run.alive);
const sub = run && run.sub != null ? ` sub=${run.sub}` : "";
const complete = run && run.complete != null ? ` complete=${run.complete}` : "";
const worker =
run && run.worker_log
? ` · worker=${String(run.worker_log).split(/[\\/]/).pop()}`
: "";
showOpsFeedback(
`Обновлено · ${alive ? "выполняется" : "ожидание"} · ${phase}${sub}${complete}${worker}`,
"ok",
{ toast: true, sticky: true },
);
} catch (e) {
if (auth401(e)) {
return;
}
showOpsFeedback(formatApiError(e), "err");
} finally {
setBusyKey(null);
}
}
async function start() {
if (!regFormLoaded.value) {
showOpsFeedback("Дождитесь загрузки конфига перед стартом", "err", {
toast: true,
sticky: true,
});
return;
}
const providers = normalizeProvidersList(form.email_providers);
if (!providers.length) {
showOpsFeedback(
primaryProvider
? `Отметьте хотя бы один Provider перед стартом (одиночный канал ${primaryProvider} используется runtime только после очистки multi в настройках; страница регистрации не пишет singleton обратно в пул)`
: "Отметьте хотя бы один почтовый Provider перед стартом (пустой выбор не очищает сохранённый пул и не инжектит EMAIL_PROVIDERS в этот батч)",
"err",
{ toast: true, sticky: true },
);
return;
}
setBusyKey("start");
showOpsFeedback("Сохранение конфига и запуск…", "info", { toast: false, sticky: true });
try {
await saveConfig({ silent: true });
} catch (e) {
showOpsFeedback(
`Ошибка сохранения конфига (старт всё равно пробует): ${formatApiError(e)}`,
"warn",
{ toast: true, sticky: true },
);
}
const body = buildStartBody();
try {
const data = await api.startRun(body);
const pid = data && data.run && data.run.pid;
const detail = (data && data.detail) || "started";
showOpsFeedback(
`Запущено · ${detail}${pid != null ? ` pid=${pid}` : ""} · tag=${body.tag}`,
"ok",
);
// immediate progress refresh
try {
const cur = await api.currentRun();
currentRunState.value = cur.run ?? cur ?? null;
const ov = await api.overview();
overviewState.value = ov;
if (ov && ov.product_ok != null) lastProductOk.value = ov.product_ok;
} catch {
/* fine */
}
} catch (e) {
if (auth401(e)) {
return;
}
showOpsFeedback(formatApiError(e), "err");
if (e.status === 409) {
try {
const cur = await api.currentRun();
currentRunState.value = cur.run ?? cur ?? null;
} catch {
/* ignore */
}
}
} finally {
setBusyKey(null);
}
}
async function stop() {
const ok = window.confirm(
"Остановить текущую задачу?\n\nЗавершит группу процессов control и попытается остановить внешний supervisor (flock pid).\nРабочий batch будет убит.",
);
if (!ok) {
showOpsFeedback("Остановка отменена", "info", { toast: true, sticky: false });
return;
}
setBusyKey("stop");
showOpsFeedback("Остановка…", "warn", { toast: false, sticky: true });
try {
const data = await api.stopRun();
const detail =
(data && data.detail) || (data && data.ok ? "stopped" : "no active run");
const pid = data && data.pid;
showOpsFeedback(
`${data && data.ok ? "Остановлено" : "Остановка не сработала"} · ${detail}${pid != null ? ` pid=${pid}` : ""}`,
data && data.ok ? "ok" : "warn",
);
const cur = await api.currentRun();
currentRunState.value = cur.run ?? cur ?? null;
} catch (e) {
if (auth401(e)) {
return;
}
showOpsFeedback(formatApiError(e), "err");
} finally {
setBusyKey(null);
}
}
async function testProxy() {
setBusyKey("proxy");
showOpsFeedback("Тестирование прокси…", "info", { toast: false, sticky: true });
try {
let data;
let via = "clash";
try {
data = await api.testClash({ limit: 8 });
} catch {
via = "catalog";
data = await api.testCatalog({ limit: 8 });
}
const healthy =
data && (data.healthy != null
? data.healthy
: data.ok_count != null
? data.ok_count
: null);
const total =
data && (data.total != null
? data.total
: data.tested != null
? data.tested
: null);
const summary =
healthy != null && total != null
? `healthy=${healthy}/${total}`
: (data && data.detail) || "done";
showOpsFeedback(`Тест прокси завершён (${via}) · ${summary}`, "ok");
setActionResult(typeof data === "string" ? data : JSON.stringify(data, null, 2));
} catch (e) {
if (auth401(e)) {
return;
}
showOpsFeedback(`Ошибка теста прокси: ${formatApiError(e)}`, "err");
} finally {
setBusyKey(null);
}
}
return (
<section class="page">
<PageHeader
title="Протокольная регистрация"
hint="Слева параметры запуска · справа live-прогресс. Полные логи worker/supervisor → страница логов."
>
<button
type="button"
class="btn btn-primary btn-md"
disabled={busyKey === "start" || !regFormLoaded.value}
title={!regFormLoaded.value ? "Сначала загрузите конфиг" : undefined}
onClick={start}
>
{busyKey === "start" ? "Запуск…" : "Старт"}
</button>
<button
type="button"
class="btn btn-danger btn-md"
disabled={busyKey === "stop"}
onClick={stop}
>
{busyKey === "stop" ? "Остановка…" : "Стоп"}
</button>
<button
type="button"
class="btn btn-ghost btn-md"
disabled={busyKey === "refresh"}
onClick={refresh}
>
{busyKey === "refresh" ? "Обновление…" : "Обновить"}
</button>
<button
type="button"
class="btn btn-ghost btn-md"
onClick={gotoLogs}
>
Логи →
</button>
</PageHeader>
{/* Sticky banner + ops log live in App shell OpsFeedbackBar (all pages). */}
<div class="split">
<div class="panel form-panel">
<RegForm
value={form}
residualPrimary={primaryProvider}
onChange={(next) => setForm(next)}
advancedOpen={advancedOpen}
onToggleAdvanced={(e) => setAdvancedOpen(e.currentTarget.open)}
/>
{/* Footer toolbar: Сохранить / self-check(link #/settings) / Тест прокси.
No duplicate cleanup/selfcheck buttons (settings only). */}
<div class="form-foot-toolbar">
<button
type="button"
class="btn btn-ghost btn-sm"
disabled={busyKey === "save" || !regFormLoaded.value}
title={!regFormLoaded.value ? "Сначала загрузите конфиг" : undefined}
onClick={() => saveConfig().catch(() => {})}
>
{busyKey === "save" ? "Сохранение…" : "Сохранить"}
</button>
<button
type="button"
class="btn btn-ghost btn-sm"
disabled={busyKey === "proxy"}
onClick={testProxy}
>
{busyKey === "proxy" ? "Тест прокси…" : "Тест прокси"}
</button>
{/* Not a button: эта страница не выполняет self-check/чистку, только переход на страницу настроек. */}
<a class="link-hint" href="#/settings">
Self-check / чистка → страница настроек
</a>
</div>
{actionResult ? (
<pre class={`log compact ${actionResult ? "ok" : ""}`}>{actionResult}</pre>
) : null}
</div>
<div class="panel progress-panel">
<RunProgress onGotoLogs={gotoLogs} />
</div>
</div>
</section>
);
}
+292
View File
@@ -0,0 +1,292 @@
// src/pages/Register/RunProgress.jsx
// Right panel: live run progress. Renders from run store signals.
// Pure render pieces come from progressRender.jsx.
import { useState } from "preact/hooks";
import { StatusDot, Chip, Kpi } from "../../ui/index.js";
import {
currentRunState,
overviewState,
lastProductOk,
} from "../../store/run.js";
import {
runHeader,
kpiGrid,
bars,
stepRail,
statusCard,
recentWrites,
timeline,
failureStats,
} from "./progressRender.jsx";
import "../../styles/run-progress.css";
function barKind(cls) {
if (cls === "danger") return "err";
if (cls === "warn") return "warn";
return "ok";
}
export function RunProgress({ onGotoLogs }) {
const [timelineOpen, setTimelineOpen] = useState(true);
const [writesOpen, setWritesOpen] = useState(true);
const run = currentRunState.value;
const ov = overviewState.value;
const head = runHeader(run);
const kpis = kpiGrid(run, ov, lastProductOk.value);
const brs = bars(run);
const steps = stepRail(run && run.steps);
const sc = statusCard(run);
const writes = recentWrites(run && run.recent_writes);
const tl = timeline(run && run.timeline);
const fstats = failureStats(run);
return (
<div class="run-progress">
<div
class={`run-header run-header-${head.state}`}
data-state={head.state}
>
<StatusDot kind={head.dotKind} />
<span class="status-word">{head.word}</span>
<span class="meta-chips">
{head.chips.map((c, i) => (
<Chip
key={i}
kind={c.danger ? "err" : "default"}
class="mini"
title={c.title}
>
{c.label}
</Chip>
))}
</span>
</div>
<div class="kpi-grid">
{kpis.map((k, i) => (
<Kpi
key={i}
label={k.label}
value={k.value}
hint={k.hint}
class={k.cls}
/>
))}
</div>
<div class="bars">
{brs.map((b, i) => {
const p = b.value == null ? 0 : b.value;
const cap = b.value == null
? "—"
: `${fmtN(b.a)} / ${fmtN(b.b)} (${Math.round(b.value)}%)`;
return (
<div key={i} class="bar-row">
<span class="bar-label">{b.label}</span>
<div
class="bar-track"
role="progressbar"
aria-valuenow={Math.round(p)}
aria-valuemin={0}
aria-valuemax={100}
>
<div
class={`bar-fill bar-${barKind(b.cls)}`}
style={{ width: `${p.toFixed(1)}%` }}
/>
</div>
<span class={`bar-caption ${b.cls || ""}`}>{cap}</span>
</div>
);
})}
</div>
{steps.length > 0 ? (
<div class="step-rail">
{steps.map((s, i) => (
<span
key={i}
class={`step ${s.state}`}
title={s.desc}
>
{s.title}
</span>
))}
</div>
) : null}
<div class="status-card">
<div class="status-title">{sc.title}</div>
<pre class="status-body">{sc.body}</pre>
</div>
{fstats ? <FailureStats stats={fstats} /> : null}
{writes.length > 0 ? (
<details
class="writes-wrap"
open={writesOpen}
onToggle={(e) => setWritesOpen(e.currentTarget.open)}
>
<summary>Последние записи на диск ({writes.length})</summary>
<div class="run-writes">
{writes.map((w, i) => (
<span key={i} class="write-chip" title={w.raw}>
{w.name}
</span>
))}
</div>
</details>
) : null}
<details
class="timeline-wrap"
open={timelineOpen}
onToggle={(e) => setTimelineOpen(e.currentTarget.open)}
>
<summary>Таймлайн</summary>
<ol class="timeline">
{tl.length ? (
tl.map((it, i) => (
<li key={i} class="timeline-item">
<span class="src">{it.src}</span>
<span>
{it.title}
{it.line ? ` · ${it.line}` : ""}
</span>
</li>
))
) : (
<li class="timeline-item hint">событий пока нет</li>
)}
</ol>
</details>
<p class="hint progress-log-hint">
Полный tail и история worker / supervisor →
<button
type="button"
class="linkish"
onClick={onGotoLogs}
>
Логи
</button>
</p>
</div>
);
}
function fmtN(v) {
return v == null || v === "" ? "—" : String(v);
}
// Batch failure statistics card. Renders only when run.batch_failures has data.
function FailureStats({ stats }) {
const { kpis, breakdown, reasons, series } = stats;
return (
<div class="failure-stats">
<div class="failure-stats-head">
<span class="failure-stats-title">Статистика ошибок батча</span>
<span class="hint">агрегат {stats.subs} под-батчей</span>
</div>
<div class="failure-kpis">
{kpis.map((k, i) => (
<div key={i} class={`failure-kpi ${k.cls || ""}`}>
<div class="failure-kpi-value">{k.value}</div>
<div class="failure-kpi-label">{k.label}</div>
{k.hint ? <div class="failure-kpi-hint hint">{k.hint}</div> : null}
</div>
))}
</div>
{breakdown.length > 0 ? (
<div class="failure-breakdown">
<div class="failure-breakdown-bar">
{breakdown.map((s, i) => (
<div
key={i}
class={`fseg fseg-${s.cls}`}
style={{ width: `${s.pct.toFixed(1)}%` }}
title={`${s.label}: ${s.value}`}
/>
))}
</div>
<div class="failure-legend">
{breakdown.map((s, i) => (
<span key={i} class="failure-legend-item">
<span class={`fdot fseg-${s.cls}`} />
{s.label} <b>{s.value}</b>
</span>
))}
</div>
</div>
) : (
<p class="hint failure-empty">В этом батче ошибок нет ✓</p>
)}
{series.fail.length > 1 ? (
<FailureSparkline fail={series.fail} success={series.success} />
) : null}
{reasons.map((r, i) => (
<div key={i} class="failure-reasons">
<div class="failure-reasons-title">{r.title}</div>
{r.rows.map((row, j) => (
<div key={j} class="failure-reason-row">
<span class="failure-reason-label" title={row.label}>
{row.label}
</span>
<span class="failure-reason-count">{row.count}</span>
</div>
))}
</div>
))}
</div>
);
}
// Compact per-sub reg fail/success trend. Pure SVG, no chart lib.
function FailureSparkline({ fail, success }) {
const n = fail.length;
const totals = fail.map((f, i) => f + (success[i] || 0));
const max = Math.max(1, ...totals);
const W = 100;
const H = 28;
const bw = W / n;
return (
<div class="failure-spark">
<div class="failure-spark-title hint">Тренд ошибок/успехов по под-батчам</div>
<svg viewBox={`0 0 ${W} ${H}`} class="failure-spark-svg" preserveAspectRatio="none">
{fail.map((f, i) => {
const ok = success[i] || 0;
const total = f + ok;
const x = i * bw;
const failH = (f / max) * H;
const okH = (ok / max) * H;
return (
<g key={i}>
<rect
x={x + bw * 0.15}
y={H - okH}
width={bw * 0.7}
height={okH}
class="spark-ok"
/>
<rect
x={x + bw * 0.15}
y={H - okH - failH}
width={bw * 0.7}
height={failH}
class="spark-fail"
>
<title>{`sub#${i + 1}: fail=${f} ok=${ok}`}</title>
</rect>
</g>
);
})}
</svg>
</div>
);
}
@@ -0,0 +1,252 @@
// src/pages/Register/progressRender.jsx
// Pure render (no DOM mutation) ported from legacy app.js:
// renderRunHeader / renderKpiGrid / renderBars / renderStepRail /
// renderStatusCard / renderRecentWrites / renderTimeline.
// All pure helpers: given (run, overview) → { ... } plain data for JSX.
import { fmtNum, pct } from "../../lib/format.js";
// ── Run header (hero) ────────────────────────────────────────────────────────
// returns { state, word, dotKind, chips: [{ label, danger, title }] }
export function runHeader(run) {
const alive = !!(run && run.alive);
const stuck = !!(run && run.stuck);
const state = stuck ? "stuck" : alive ? "alive" : "idle";
const word = alive ? "ALIVE" : run ? "idle" : "нет задачи";
const dotKind = stuck ? "err" : alive ? "busy" : "idle";
const meta = (run && run.meta) || {};
const tag = (run && run.tag) || meta.tag;
const chips = [];
if (tag) chips.push({ label: `tag=${tag}` });
if (run && run.pid != null) chips.push({ label: `pid=${run.pid}` });
if (run && run.mode) chips.push({ label: String(run.mode) });
if (run && run.kind) chips.push({ label: String(run.kind) });
if (run && run.complete != null) {
const goal = run.goal_complete != null ? ` / ${run.goal_complete}` : "";
chips.push({ label: `complete=${run.complete}${goal}` });
}
if (stuck) {
const reason =
(run && (run.stuck_reason || (run.summary && run.summary.fatal_reason))) ||
"";
chips.push({ label: "stuck", danger: true, title: reason });
}
return { state, word, dotKind, chips };
}
// ── KPI grid ────────────────────────────────────────────────────────────────
// returns [{ label, value, hint, cls }]
export function kpiGrid(run, overview, lastProductOk) {
const alive = !!(run && run.alive);
const complete = run && run.complete != null ? run.complete : null;
const goal = run && run.goal_complete != null ? run.goal_complete : null;
const remain = run && run.remain != null ? run.remain : null;
const gained = run && run.batch_gained != null ? run.batch_gained : null;
const target = run && (run.target != null ? run.target : run.target_new);
const batchRemain = run && run.batch_remain != null ? run.batch_remain : null;
const sub = run && run.sub != null ? run.sub : null;
const zero = run && run.consecutive_zero != null ? run.consecutive_zero : null;
const disk =
overview && overview.product_ok != null ? overview.product_ok : lastProductOk;
const nodes = overview && overview.nodes ? overview.nodes : null;
const zeroClass =
run && run.stuck ? "danger" : zero != null && Number(zero) >= 4 ? "warn" : "";
const completeClass = alive && remain === 0 ? "ok" : "";
const diskClass =
disk != null && Number(disk) > 0 ? "ok" : disk == null ? "" : "warn";
return [
{
label: "complete / goal",
value: `${fmtNum(complete)}${goal != null ? " / " + goal : ""}`,
hint: remain != null ? `осталось ${remain}` : "",
cls: completeClass,
},
{
label: "gained этого батча",
value: `${fmtNum(gained)}${target != null ? " / " + target : ""}`,
hint: batchRemain != null ? `осталось ${batchRemain}` : "",
cls: "",
},
{
label: "disk product_ok",
value: fmtNum(disk),
hint: "",
cls: diskClass,
},
{
label: "sub · zero",
value: `${fmtNum(sub)} · ${fmtNum(zero)}`,
hint: run && run.chunk != null ? `chunk ${run.chunk}` : "",
cls: zeroClass,
},
{
label: "mode",
value: fmtNum(run && run.mode),
hint: run && run.kind ? String(run.kind) : "",
cls: "",
},
{
label: "nodes healthy",
value: nodes ? `${fmtNum(nodes.healthy)} / ${fmtNum(nodes.total)}` : "—",
hint: nodes && nodes.enabled != null ? `enabled ${nodes.enabled}` : "",
cls: "",
},
];
}
// ── Bars ────────────────────────────────────────────────────────────────────
// returns [{ label, a, b, value: pctVal|null, cls }]
export function bars(run) {
const complete = run && run.complete != null ? run.complete : null;
const goal = run && run.goal_complete != null ? run.goal_complete : null;
const gained = run && run.batch_gained != null ? run.batch_gained : null;
const target = run && (run.target != null ? run.target : run.target_new);
const stuck = !!(run && run.stuck);
const gp = pct(complete, goal);
const bp = pct(gained, target);
return [
{ label: "Глобально", a: complete, b: goal, value: gp, cls: stuck ? "danger" : "ok" },
{ label: "Этот батч", a: gained, b: target, value: bp, cls: stuck ? "warn" : "ok" },
];
}
// ── Step rail ───────────────────────────────────────────────────────────────
// returns [{ state, title, desc }] (state: done|active|pending)
export function stepRail(steps) {
if (!Array.isArray(steps) || !steps.length) return [];
return steps.map((s) => {
const state = s && s.state ? String(s.state) : "pending";
const title = s && (s.title || s.id) ? String(s.title || s.id) : "";
const desc = s && s.desc ? String(s.desc) : "";
return { state, title, desc };
});
}
// ── Status card ─────────────────────────────────────────────────────────────
// returns { title, body }
export function statusCard(run) {
const alive = !!(run && run.alive);
const phase = (run && (run.phase_title || run.phase)) || "—";
const title = `Статус задачи: ${alive ? "выполняется" : run ? "ожидание" : "—"} · ${phase}`;
const lines = [];
if (run) {
if (run.phase_detail) lines.push(run.phase_detail);
const fatal = run.summary && run.summary.fatal_reason;
if (fatal) lines.push(`fatal: ${fatal}`);
if (run.worker_log) lines.push(`worker: ${run.worker_log}`);
if (run.supervisor_log) lines.push(`supervisor: ${run.supervisor_log}`);
if (run.stuck_reason && !fatal) lines.push(`stuck: ${run.stuck_reason}`);
if (!lines.length) lines.push("Текущая задача загружена.");
} else {
lines.push("Активного supervisor нет. Заполните параметры слева и нажмите «Старт».");
}
return { title, body: lines.join("\n") };
}
// ── Recent writes ────────────────────────────────────────────────────────────
// returns [{ name, raw }] (last ≤5)
export function recentWrites(writes) {
if (!Array.isArray(writes) || !writes.length) return [];
return writes.slice(-5).map((p) => {
const raw = String(p);
const name = raw.split(/[\\/]/).pop() || raw;
return { name, raw };
});
}
// ── Failure stats ─────────────────────────────────────────────────────────────
// Aggregated batch-level failures from run.batch_failures (control_api parses
// every per-sub SUMMARY_JSON in the supervisor log). Returns null when there is
// nothing to show yet so the card can hide entirely.
// returns { subs, kpis:[{label,value,cls,hint}], breakdown:[{label,value,cls}],
// reasons:[{title, rows:[{label,count}]}], series:{fail,success} } | null
export function failureStats(run) {
const bf = run && run.batch_failures;
if (!bf || !bf.subs) return null;
const regFail = Number(bf.reg_fail || 0);
const attempts = Number(bf.attempts || 0);
const rate = attempts ? (regFail / attempts) * 100 : 0;
const rateCls = rate >= 50 ? "danger" : rate >= 20 ? "warn" : rate > 0 ? "" : "ok";
const totalFail = Number(bf.total_fail || 0);
const kpis = [
{
label: "Доля ошибок регистрации",
value: attempts ? `${rate.toFixed(0)}%` : "—",
hint: attempts ? `${regFail} / ${attempts} попыток` : "нет записей попыток",
cls: rateCls,
},
{
label: "Всего ошибок",
value: String(totalFail),
hint: `агрегат ${bf.subs} под-батчей`,
cls: totalFail > 0 ? "warn" : "ok",
},
{
label: "fatal под-батч",
value: String(bf.fatal_subs || 0),
hint: bf.fatal_subs ? "см. причину fatal ниже" : "нет",
cls: bf.fatal_subs > 0 ? "danger" : "ok",
},
];
// Failure-type distribution (stacked/segmented bar).
const segRaw = [
{ label: "Регистрация", value: regFail, cls: "err" },
{ label: "Mint", value: Number(bf.mint_fail || 0), cls: "warn" },
{ label: "Chat отказ", value: Number(bf.chat_denied || 0), cls: "warn" },
{ label: "Chat ошибка", value: Number(bf.chat_fail || 0), cls: "err" },
{ label: "Инъекция", value: Number(bf.remote_inject_fail || 0), cls: "err" },
{ label: "Live", value: Number(bf.remote_live_fail || 0), cls: "warn" },
];
const segTotal = segRaw.reduce((a, s) => a + s.value, 0) || 1;
const breakdown = segRaw
.filter((s) => s.value > 0)
.map((s) => ({
label: s.label,
value: s.value,
pct: (s.value / segTotal) * 100,
cls: s.cls,
}));
const reasons = [];
const mintReasons = Array.isArray(bf.mint_fail_reasons) ? bf.mint_fail_reasons : [];
if (mintReasons.length) {
reasons.push({
title: "Причина ошибки Mint",
rows: mintReasons.map(([label, count]) => ({ label: String(label), count })),
});
}
const fatalReasons = Array.isArray(bf.fatal_reasons) ? bf.fatal_reasons : [];
if (fatalReasons.length) {
reasons.push({
title: "Причина fatal",
rows: fatalReasons.map(([label, count]) => ({ label: String(label), count })),
});
}
const failSeries = Array.isArray(bf.reg_fail_series) ? bf.reg_fail_series : [];
const okSeries = Array.isArray(bf.reg_success_series) ? bf.reg_success_series : [];
return {
subs: bf.subs,
kpis,
breakdown,
reasons,
series: { fail: failSeries, success: okSeries },
};
}
// ── Timeline ──────────────────────────────────────────────────────────────────
// returns [{ src, title, line }] (last ≤6)
export function timeline(items) {
const cap = 6;
const rows = Array.isArray(items) ? items.slice(-cap) : [];
return rows.map((it) => ({
src: String((it && (it.source || it.phase)) || "log"),
title: String((it && it.title) || ""),
line: String((it && it.line) || "").slice(0, 300),
}));
}
+187
View File
@@ -0,0 +1,187 @@
// ImportTab — 2×2 cards: nodes file, mail text, auths file, pack zip
import { useRef, useState } from "preact/hooks";
import * as api from "../../api/client.js";
import { showOpsFeedback } from "../../store/feedback.js";
import { Button, LogDetails } from "../../ui/index.js";
import { formatApiError } from "../../lib/format.js";
import { pretty, auth401 } from "../../lib/http.js";
import { useBusy } from "../../lib/useBusy.js";
export function ImportTab() {
const [result, setResult] = useState("");
const { is: busyIs, run: withBusy } = useBusy();
const nodesFile = useRef(null);
const authsFile = useRef(null);
const packFile = useRef(null);
const [nodesDry, setNodesDry] = useState(true);
const [nodesReplace, setNodesReplace] = useState(false);
const [mailText, setMailText] = useState("");
const [mailMode, setMailMode] = useState("append");
const [authsRemote, setAuthsRemote] = useState(false);
const [packApply, setPackApply] = useState(false);
async function run(key, fn) {
await withBusy(key, async () => {
try {
const body = await fn();
setResult(pretty(body));
if (key === "mail") {
const r = (body && body.result) || body || {};
const summary =
(body && body.detail) ||
r.summary ||
`Импорт почты · новых ${r.new ?? r.lines_written ?? 0} · дублей ${r.duplicate ?? 0} · невалидных ${r.skipped ?? 0}`;
const status = r.status || (r.new > 0 || r.lines_written > 0 ? "success" : "empty");
const kind = status === "success" ? "ok" : "info";
showOpsFeedback(summary, kind, { toast: true, sticky: true });
} else {
showOpsFeedback(`Импорт завершён · ${key}`, "ok", { toast: true, sticky: false });
}
} catch (e) {
if (auth401(e)) return;
setResult(pretty({ error: formatApiError(e) }));
showOpsFeedback(`Ошибка импорта: ${formatApiError(e)}`, "err");
}
});
}
return (
<div class="resources-tab import-tab">
<div class="import-grid">
<div class="card">
<h2>Файл Nodes / proxies</h2>
<input type="file" ref={nodesFile} />
<label class="check">
<input
type="checkbox"
checked={nodesDry}
onChange={(e) => setNodesDry(e.currentTarget.checked)}
/>{" "}
dry-run
</label>
<label class="check">
<input
type="checkbox"
checked={nodesReplace}
onChange={(e) => setNodesReplace(e.currentTarget.checked)}
/>{" "}
replace
</label>
<Button
variant="ghost"
busy={busyIs("nodes")}
onClick={() =>
run("nodes", async () => {
const f = nodesFile.current?.files?.[0];
if (!f) throw new Error("pick a file");
const fd = new FormData();
fd.append("file", f);
fd.append("dry_run", nodesDry ? "true" : "false");
fd.append("replace", nodesReplace ? "true" : "false");
return api.importNodesFile(fd);
})
}
>
Import nodes
</Button>
</div>
<div class="card">
<h2>Mail credentials</h2>
<p class="hint">
Общий источник с «Ресурсы → Почта». Поддержка JSON/CSV/pipe; append с дедупом, фидбек: новых/дублей/невалидных.
</p>
<textarea
rows={5}
value={mailText}
placeholder={"email----password----clientId----refresh_token\nили JSON / CSV"}
onInput={(e) => setMailText(e.currentTarget.value)}
/>
<label class="inline">
mode{" "}
<select
value={mailMode}
onChange={(e) => setMailMode(e.currentTarget.value)}
>
<option value="append">append</option>
<option value="replace">replace</option>
</select>
</label>
<Button
variant="ghost"
busy={busyIs("mail")}
onClick={() =>
run("mail", async () => {
const fd = new FormData();
fd.append("content", mailText || "");
fd.append("mode", mailMode || "append");
return api.importMailText(fd);
})
}
>
Import mail
</Button>
</div>
<div class="card">
<h2>Account / token dumps</h2>
<input type="file" ref={authsFile} />
<label class="check">
<input
type="checkbox"
checked={authsRemote}
onChange={(e) => setAuthsRemote(e.currentTarget.checked)}
/>{" "}
allow remote CPA inject
</label>
<Button
variant="ghost"
busy={busyIs("auths")}
onClick={() =>
run("auths", async () => {
const f = authsFile.current?.files?.[0];
if (!f) throw new Error("pick a file");
const fd = new FormData();
fd.append("file", f);
fd.append("no_remote", authsRemote ? "false" : "true");
return api.importAuthsFile(fd);
})
}
>
Import auths
</Button>
</div>
<div class="card">
<h2>Config pack (zip)</h2>
<input type="file" ref={packFile} />
<label class="check">
<input
type="checkbox"
checked={packApply}
onChange={(e) => setPackApply(e.currentTarget.checked)}
/>{" "}
apply
</label>
<Button
variant="ghost"
busy={busyIs("pack")}
onClick={() =>
run("pack", async () => {
const f = packFile.current?.files?.[0];
if (!f) throw new Error("pick a file");
const fd = new FormData();
fd.append("file", f);
fd.append("apply", packApply ? "true" : "false");
return api.importPackFile(fd);
})
}
>
Import pack
</Button>
</div>
</div>
<LogDetails text={result} summary="Детали ответа импорта" />
</div>
);
}
+317
View File
@@ -0,0 +1,317 @@
// MailTab — per-provider email config + hotmail cred import + pool probe.
// Pipeline multi-select / strategy live on Settings; Register only picks pool.
import { useCallback, useEffect, useState } from "preact/hooks";
import * as api from "../../api/client.js";
import { showOpsFeedback } from "../../store/feedback.js";
import { Button, LogDetails } from "../../ui/index.js";
import { formatApiError } from "../../lib/format.js";
import { pretty, auth401 } from "../../lib/http.js";
import { useConfigForm } from "../../lib/useConfigForm.js";
import { parseDomainList, joinDomains } from "./mail/domains.js";
import { DefaultDomainsCard } from "./mail/DefaultDomainsCard.jsx";
import { MailProviderPanels } from "./mail/MailProviderPanels.jsx";
import { MailCredImport } from "./mail/MailCredImport.jsx";
import { MailPoolProbe } from "./mail/MailPoolProbe.jsx";
const SECRET_KEYS = [
"cloudflare_api_key",
"duckmail_api_key",
"yyds_api_key",
"cloudmail_password",
];
const EMPTY = {
defaultDomains: "",
cloudflare_api_base: "",
cloudflare_api_key: "",
duckmail_api_key: "",
yyds_api_key: "",
cloudmail_url: "",
cloudmail_admin_email: "",
cloudmail_password: "",
gmail_imap_user: "",
hotmail_accounts_file: "",
hotmail_allow_plus_alias: false,
};
export function MailTab() {
const [result, setResult] = useState("");
const [openPanels, setOpenPanels] = useState({
cloudflare: true,
cloudmail: false,
duckmail: false,
yyds: false,
gmail: false,
hotmail: true,
});
const [cfDomains, setCfDomains] = useState([]);
const [cfSelected, setCfSelected] = useState([]);
const [cfMeta, setCfMeta] = useState(null);
// Pool stats owned here — cred import and probe both invalidate them.
const [pool, setPool] = useState(null);
const loadPool = useCallback(async () => {
try {
const data = await api.mailPoolStats();
setPool(data);
} catch (e) {
if (auth401(e)) return;
setPool(null);
}
}, []);
const cfg = useConfigForm({
empty: EMPTY,
// Last successful load domains — detect intentional clear on save.
// (String, not object — kept as-is from the pre-hook implementation.)
initialBaseline: "",
loadRequest: async () => {
const data = await api.getConfig();
return data.config || {};
},
hydrate: (c) => {
const next = { ...EMPTY };
for (const k of Object.keys(EMPTY)) {
if (c[k] == null) continue;
if (k === "hotmail_allow_plus_alias") {
next[k] = c[k] === true || c[k] === "true" || c[k] === 1 || c[k] === "1";
} else if (SECRET_KEYS.includes(k)) {
next[k] = "";
} else {
next[k] = String(c[k]);
}
}
return { form: next, baseline: String(next.defaultDomains || "") };
},
onLoaded: async (c, next) => {
setCfSelected(parseDomainList(next.defaultDomains));
setResult(
pretty({
loaded: true,
domains: c.defaultDomains,
note: "Пул каналов/стратегия — на странице настроек; здесь только тонкая настройка Provider",
}),
);
await loadPool();
},
onLoadError: (e) => {
setResult(String(e.message || e));
showOpsFeedback(`Ошибка загрузки конфига почты: ${formatApiError(e)}`, "err");
},
confirmReload: {
message: "Есть несохранённые изменения конфига почты. Отменить и перезагрузить?",
onCancel: () =>
showOpsFeedback("Перезагрузка отменена", "info", { toast: true, sticky: false }),
},
onSaveBlocked: () =>
showOpsFeedback("Сначала загрузите конфиг, потом сохраняйте (пустая форма очистит defaultDomains)", "err", {
toast: true,
sticky: true,
}),
// Single source of truth for domains:
// - form.defaultDomains is always kept in sync with chips / hand-edit.
// - empty string is intentional clear (backend defaultDomains is clearable).
confirmClear: (f, baselineDomains) => {
const domains = joinDomains(parseDomainList(f.defaultDomains));
const baselineJoined = joinDomains(parseDomainList(baselineDomains));
if (domains || !baselineJoined) return null;
return {
message:
"Очистить defaultDomains?\n\nЗапишет пустое значение в config и .env (DEFAULT_DOMAINS=).\nCloudflare / CloudMail / Gmail catch-all останутся без доменов.",
};
},
onSaveCancelled: () =>
showOpsFeedback("Сохранение отменено", "info", { toast: true, sticky: false }),
saveRequest: (f) => {
const partial = {};
partial.defaultDomains = joinDomains(parseDomainList(f.defaultDomains));
for (const [k, raw] of Object.entries(f)) {
if (k === "defaultDomains") continue;
if (SECRET_KEYS.includes(k)) {
const v = String(raw || "");
if (v === "" || v.startsWith("***")) continue;
partial[k] = v;
continue;
}
if (k === "hotmail_allow_plus_alias") {
partial[k] = !!raw;
continue;
}
if (raw === "" || raw == null) continue;
partial[k] = raw;
}
return api.putConfig({ config: partial });
},
onSaved: (data, f) => {
const domains = joinDomains(parseDomainList(f.defaultDomains));
setResult(pretty(data));
const saved = data.config || {};
const savedDomains =
saved.defaultDomains != null ? String(saved.defaultDomains) : domains;
setCfSelected(parseDomainList(savedDomains));
showOpsFeedback(
domains
? `Конфиг почты сохранён · domains=${domains}`
: "Конфиг почты сохранён · defaultDomains очищен",
"ok",
);
return {
form: (p) => {
const n = { ...p };
for (const k of SECRET_KEYS) n[k] = "";
n.defaultDomains = savedDomains;
return n;
},
baseline: savedDomains,
};
},
onSaveError: (e) => {
setResult(String(e.message || e));
showOpsFeedback(`Ошибка сохранения: ${formatApiError(e)}`, "err");
},
});
const { form, set, hydrated, dirty, load, save, busyIs, setBusy } = cfg;
useEffect(() => {
load();
// initial mount only
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
function togglePanel(name, next) {
setOpenPanels((p) => ({ ...p, [name]: next === undefined ? !p[name] : next }));
}
async function fetchCfDomains() {
setBusy("cfDomains");
try {
const data = await api.cloudflareDomains();
const list = data.domains || [];
setCfDomains(list);
setCfMeta({
count: data.count,
api_base: data.api_base,
has_api_key: data.has_api_key,
});
// Keep form.defaultDomains as the only selection source.
// Never auto-check the full Worker list — that can dump dozens of
// domains into DEFAULT_DOMAINS on the next save. If form is empty but
// server still has selected, mirror that known selection only.
const fromForm = parseDomainList(form.defaultDomains);
if (fromForm.length) {
setCfSelected(fromForm);
} else {
const fromServer = Array.isArray(data.selected)
? data.selected.map((d) => String(d || "").trim()).filter(Boolean)
: [];
if (fromServer.length) {
const joined = joinDomains(fromServer);
set({ defaultDomains: joined });
setCfSelected(parseDomainList(joined));
} else {
setCfSelected([]);
}
}
showOpsFeedback(
fromForm.length || (data.selected || []).length
? `Загружено ${list.length} доменов · отметки сохранены`
: `Загружено ${list.length} доменов · отметьте и сохраните (авто-выбор всех отключён)`,
"ok",
);
setResult(pretty({ cloudflare_domains: list, selected: data.selected }));
} catch (e) {
if (auth401(e)) return;
showOpsFeedback(`Ошибка загрузки доменов: ${formatApiError(e)}`, "err");
setResult(pretty({ error: formatApiError(e) }));
} finally {
setBusy("");
}
}
function toggleCfDomain(dom) {
// form.defaultDomains is the single source; cfSelected mirrors it.
// Compute next outside setState updaters — no nested setState side effects.
const cur = parseDomainList(form.defaultDomains);
const low = String(dom).toLowerCase();
const next = cur.some((d) => d.toLowerCase() === low)
? cur.filter((d) => d.toLowerCase() !== low)
: [...cur, dom];
const joined = joinDomains(next);
set({ defaultDomains: joined });
setCfSelected(parseDomainList(joined));
}
function editDomains(v) {
set({ defaultDomains: v });
setCfSelected(parseDomainList(v));
}
return (
<div class="resources-tab mail-tab">
<div class="toolbar wrap mail-toolbar">
<Button
variant="ghost"
busy={busyIs("load")}
onClick={() => load({ force: true })}
>
Перезагрузить
</Button>
<Button
variant="primary"
busy={busyIs("save")}
disabled={!hydrated || busyIs("load")}
onClick={save}
title={!hydrated ? "Сначала загрузите конфиг" : undefined}
>
Сохранить конфиг почты
</Button>
<a class="btn btn-ghost btn-sm" href="#/settings">
Пул каналов → Настройки
</a>
</div>
<p class="hint">
Эта страница настраивает только ключи / домены / учётки Provider. Выбор каналов и стратегия опроса — в
<a href="#/settings">Настройки</a>
(общий со страницей регистрации <code>email_providers</code>).
{!hydrated ? (
<span class="hint warn"> Конфиг не загружен, сохранение отключено.</span>
) : dirty ? (
<span class="hint warn"> Есть несохранённые изменения.</span>
) : null}
</p>
<h2 class="mail-section-title">Конфиг (после изменений нажмите «Сохранить конфиг почты»)</h2>
<DefaultDomainsCard
form={form}
cfDomains={cfDomains}
cfMeta={cfMeta}
cfSelected={cfSelected}
onFetchCfDomains={fetchCfDomains}
onToggleCfDomain={toggleCfDomain}
onEditDomains={editDomains}
busy={busyIs("cfDomains")}
/>
<MailProviderPanels
form={form}
set={set}
openPanels={openPanels}
onTogglePanel={togglePanel}
/>
<h2 class="mail-section-title">
Эксплуатация <span class="hint tight">· действия применяются сразу, без «Сохранить конфиг почты»</span>
</h2>
<MailCredImport onResult={setResult} onImported={loadPool} />
<MailPoolProbe pool={pool} onReloadPool={loadPool} onResult={setResult} />
<LogDetails text={result} summary="Детали ответа импорта / проверки" />
</div>
);
}
@@ -0,0 +1,120 @@
// Regression tests locking MailTab's config-form invariants.
// Written BEFORE the useConfigForm extraction — these must stay green after it.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, waitFor, fireEvent } from "@testing-library/preact";
vi.mock("../../api/client.js", () => ({
getConfig: vi.fn(),
putConfig: vi.fn(),
mailPoolStats: vi.fn(),
cloudflareDomains: vi.fn(),
importMailText: vi.fn(),
probeMail: vi.fn(),
compactMail: vi.fn(),
quarantineMail: vi.fn(),
}));
import * as api from "../../api/client.js";
import { session } from "../../store/session.js";
import { MailTab } from "./MailTab.jsx";
const LOADED = {
config: {
defaultDomains: "a.com,b.com",
cloudflare_api_base: "https://cf.example",
},
};
function saveBtn() {
return screen.getByRole("button", { name: "Сохранить конфиг почты" });
}
function reloadBtn() {
return screen.getByRole("button", { name: "Перезагрузить" });
}
function domainsInput() {
return screen.getByLabelText(/defaultDomains(Глобально/);
}
beforeEach(() => {
vi.clearAllMocks();
session.value = { authenticated: true, checked: true };
api.mailPoolStats.mockResolvedValue({ by_domain: {}, known_domains: [] });
vi.spyOn(window, "confirm").mockReturnValue(true);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("MailTab config-form invariants", () => {
it("1. GET failure leaves Save disabled and sends no PUT", async () => {
api.getConfig.mockRejectedValue(new Error("boom"));
render(<MailTab />);
await waitFor(() => expect(saveBtn().disabled).toBe(true));
fireEvent.click(saveBtn());
await waitFor(() => expect(api.putConfig).not.toHaveBeenCalled());
});
it("2. GET 401 clears the session and leaves Save disabled", async () => {
const e = new Error("unauthorized");
e.status = 401;
api.getConfig.mockRejectedValue(e);
render(<MailTab />);
await waitFor(() => expect(session.value.authenticated).toBe(false));
expect(saveBtn().disabled).toBe(true);
});
it("3. Reload while dirty prompts, and cancelling sends no second GET", async () => {
api.getConfig.mockResolvedValue(LOADED);
render(<MailTab />);
await waitFor(() => expect(saveBtn().disabled).toBe(false));
expect(api.getConfig).toHaveBeenCalledTimes(1);
fireEvent.input(domainsInput(), { target: { value: "c.com" } });
window.confirm.mockReturnValue(false);
fireEvent.click(reloadBtn());
await waitFor(() => expect(window.confirm).toHaveBeenCalled());
expect(api.getConfig).toHaveBeenCalledTimes(1);
});
it("4. clearing defaultDomains prompts on Save; cancelling sends no PUT", async () => {
api.getConfig.mockResolvedValue(LOADED);
render(<MailTab />);
await waitFor(() => expect(saveBtn().disabled).toBe(false));
fireEvent.input(domainsInput(), { target: { value: "" } });
window.confirm.mockReturnValue(false);
fireEvent.click(saveBtn());
await waitFor(() => expect(window.confirm).toHaveBeenCalled());
expect(window.confirm.mock.calls[0][0]).toContain("defaultDomains");
expect(api.putConfig).not.toHaveBeenCalled();
});
it("5. successful Save clears dirty and rehydrates domains from the server response", async () => {
api.getConfig.mockResolvedValue(LOADED);
api.putConfig.mockResolvedValue({
config: { defaultDomains: "server.com" },
});
render(<MailTab />);
await waitFor(() => expect(saveBtn().disabled).toBe(false));
fireEvent.input(domainsInput(), { target: { value: "c.com,d.com" } });
fireEvent.click(saveBtn());
await waitFor(() => expect(api.putConfig).toHaveBeenCalledTimes(1));
expect(api.putConfig.mock.calls[0][0].config.defaultDomains).toBe(
"c.com,d.com",
);
// Server value wins after save; dirty is cleared so Reload won't prompt.
await waitFor(() =>
expect(domainsInput().value).toBe("server.com"),
);
window.confirm.mockClear();
fireEvent.click(reloadBtn());
await waitFor(() => expect(api.getConfig).toHaveBeenCalledTimes(2));
expect(window.confirm).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,68 @@
// Resources page: Узлы·Clash | Узлы·catalog | Почта | Импорт
// Batch-2 IA: под-вкладка Nodes поднята на верхний уровень (убрана трёхуровневая вложенность).
// Clash/catalog остаются смонтированными (семантика active), фильтры/ввод форм не теряются при переключении вкладок.
import { useEffect, useState } from "preact/hooks";
import { Tabs, PageHeader } from "../../ui/index.js";
import { ClashPanel } from "./nodes/ClashPanel.jsx";
import { CatalogPanel } from "./nodes/CatalogPanel.jsx";
import { MailTab } from "./MailTab.jsx";
import { ImportTab } from "./ImportTab.jsx";
import "../../styles/resources.css";
import "../../styles/accounts.css"; // table.data / badge / filter-bar shared
const TABS = [
{ id: "clash", label: "Узлы · Clash" },
{ id: "catalog", label: "Узлы · catalog" },
{ id: "mail", label: "Почта" },
{ id: "import", label: "Импорт" },
];
function tabFromHash() {
try {
const h = location.hash || "";
const m = h.match(/[?&]tab=([a-z]+)/i);
const t = m && m[1];
if (t === "nodes") return "clash"; // legacy two-level URL
if (t && TABS.some((x) => x.id === t)) return t;
} catch {
/* ignore */
}
return "clash";
}
export function ResourcesPage() {
const [tab, setTab] = useState(tabFromHash);
useEffect(() => {
const base = "#/resources";
const next = tab === "clash" ? base : `${base}?tab=${tab}`;
if (location.hash !== next && (location.hash.startsWith("#/resources") || !location.hash)) {
location.hash = next;
}
}, [tab]);
return (
<section class="page page-resources">
<PageHeader
title="Ресурсы"
hint={
<>
Пулы узлов (Clash + catalog), приём почты и импорт. Учётные данные Hotmail — только на этой вкладке «Почта».
</>
}
/>
<div class="card">
<Tabs items={TABS} value={tab} onChange={setTab} />
</div>
{/* Clash/catalog остаются смонтированными (семантика прежней под-вкладки Nodes); mail/import монтируются по требованию. */}
<div class="resources-tab nodes-tab" hidden={tab !== "clash" && tab !== "catalog"}>
<ClashPanel active={tab === "clash"} />
<CatalogPanel active={tab === "catalog"} />
</div>
{tab === "mail" ? <MailTab /> : null}
{tab === "import" ? <ImportTab /> : null}
</section>
);
}
@@ -0,0 +1,72 @@
// DefaultDomainsCard — редактирование глобального defaultDomains в одном месте (batch-2 IA)
// Раньше в панелях CF и CloudMail было по одному полю defaultDomains, одно значение редактировалось в двух местах,
// выглядит как per-provider конфиг. Здесь поднят в глобальную зону над панелями provider, домены Worker
// Выбор также размещён здесь (результат выбора пишется в это глобальное значение).
import { useMemo } from "preact/hooks";
import { Button } from "../../../ui/index.js";
import { parseDomainList } from "./domains.js";
export function DefaultDomainsCard({
form,
cfDomains,
cfMeta,
cfSelected,
onFetchCfDomains,
onToggleCfDomain,
onEditDomains,
busy,
}) {
const selectedDomainSet = useMemo(
() => new Set(cfSelected.map((d) => d.toLowerCase())),
[cfSelected],
);
const known = cfDomains.length
? cfDomains
: parseDomainList(form.defaultDomains);
return (
<div class="card mail-global-domains">
<h2>Глобальный пул доменов</h2>
<p class="hint tight">
Cloudflare / CloudMail / Gmail catch-all используют общий{" "}
<code>defaultDomains</code>; домены yyds / duckmail берутся из их API, не отсюда.
</p>
<div class="toolbar wrap">
<Button variant="ghost" busy={busy} onClick={onFetchCfDomains}>
Загрузить домены из Worker
</Button>
<span class="hint tight">
{cfMeta
? `Загружено ${cfMeta.count ?? cfDomains.length} · base=${cfMeta.api_base || "—"} · key=${cfMeta.has_api_key ? "есть" : "нет"} · без авто-выбора всех`
: "Сначала сохраните Cloudflare base/key, потом pull; отмеченные пишутся в defaultDomains (без авто-выбора всех)"}
</span>
</div>
<div class="mail-domain-chips" style={{ marginTop: "0.5rem" }}>
{known.map((d) => (
<label key={d} class="check chip">
<input
type="checkbox"
checked={selectedDomainSet.has(String(d).toLowerCase())}
onChange={() => onToggleCfDomain(d)}
/>{" "}
{d}
</label>
))}
{!known.length ? (
<span class="hint">Доменов пока нет · pull или заполните вручную ниже</span>
) : null}
</div>
<label class="mail-domains-input">
defaultDomains (глобальный · результат выбора CF · можно очистить)
<input
value={form.defaultDomains}
placeholder="a.com,b.com · пустое значение при сохранении = очистка"
onInput={(e) => onEditDomains(e.currentTarget.value)}
/>
</label>
</div>
);
}
@@ -0,0 +1,67 @@
// MailCredImport — карточка пакетного импорта учётных данных Hotmail / Outlook.
// Moved verbatim from MailTab.jsx — JSX/classes/copy unchanged.
import { useState } from "preact/hooks";
import * as api from "../../../api/client.js";
import { showOpsFeedback } from "../../../store/feedback.js";
import { Button } from "../../../ui/index.js";
import { formatApiError } from "../../../lib/format.js";
import { pretty, auth401 } from "../../../lib/http.js";
import { useBusy } from "../../../lib/useBusy.js";
export function MailCredImport({ onResult, onImported }) {
const [credText, setCredText] = useState("");
const [credMode, setCredMode] = useState("append");
const { setBusy, is } = useBusy();
async function importCreds() {
setBusy("cred");
try {
const fd = new FormData();
fd.append("content", credText || "");
fd.append("mode", credMode || "append");
const body = await api.importMailText(fd);
onResult(pretty(body));
const r = (body && body.result) || body || {};
const summary =
(body && body.detail) ||
r.summary ||
`Импорт завершён · новых ${r.new ?? r.lines_written ?? 0} · дублей ${r.duplicate ?? 0} · невалидных ${r.skipped ?? 0}`;
const status = r.status || (r.new > 0 || r.lines_written > 0 ? "success" : "empty");
const kind = status === "success" ? "ok" : status === "partial" ? "info" : "info";
showOpsFeedback(summary, kind, { toast: true, sticky: true });
await onImported();
} catch (e) {
if (auth401(e)) return;
onResult(pretty({ error: formatApiError(e) }));
showOpsFeedback(`Ошибка импорта: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
return (
<div class="card">
<h2>Импорт учётных данных Hotmail / Outlook</h2>
<p class="hint">
Поддержка четырёхчастного формата <code>email----password----clientId----token</code>, JSON / CSV /
Разделитель pipe; append с авто-дедупом. Результат импорта покажет новых / дублей / невалидных.
</p>
<textarea
rows={6}
value={credText}
placeholder="email----password----clientId----refresh_token"
onInput={(e) => setCredText(e.currentTarget.value)}
/>
<label class="inline">
mode{" "}
<select value={credMode} onChange={(e) => setCredMode(e.currentTarget.value)}>
<option value="append">append</option>
<option value="replace">replace</option>
</select>
</label>
<Button variant="ghost" busy={is("cred")} onClick={importCreds}>
Импорт учётных данных
</Button>
</div>
);
}
@@ -0,0 +1,722 @@
// MailPoolProbe — KPI пула почты + OAuth refresh-проверка + чистка/дедуп + исключение.
// Moved verbatim from MailTab.jsx — JSX/classes/copy unchanged.
import { useEffect, useMemo, useState } from "preact/hooks";
import * as api from "../../../api/client.js";
import { showOpsFeedback } from "../../../store/feedback.js";
import { Button } from "../../../ui/index.js";
import { formatApiError } from "../../../lib/format.js";
import { pretty, auth401 } from "../../../lib/http.js";
import { useBusy } from "../../../lib/useBusy.js";
export function isQuarantinable(row) {
if (!row) return false;
if (typeof row.quarantinable === "boolean") return row.quarantinable;
return (
row.status === "grant_expired" ||
row.status === "refresh_invalid" ||
row.status === "abuse_mode"
);
}
export function statusLabel(row) {
if (!row) return "—";
if (row.status === "ok") return "рабочий";
if (isQuarantinable(row)) return "мёртв";
return "неопред.";
}
const WAVE_LIMIT_MAX = 500;
// Full-scan UI keeps at most this many result rows in the table (oldest dropped)
// so a 64k pool does not freeze the browser. Counts still aggregate fully.
const FULL_SCAN_RESULTS_CAP = 2000;
// Cloudflare origin ~100s → keep UI waves under gateway budget; more waves OK.
const FULL_SCAN_WALL_SECONDS = 90;
const FULL_SCAN_DEFAULT_WAVE = 200;
function mergeByStatus(into, add) {
const out = { ...(into || {}) };
for (const [k, v] of Object.entries(add || {})) {
out[k] = (out[k] || 0) + Number(v || 0);
}
return out;
}
function capResults(rows, cap) {
if (!rows || rows.length <= cap) return rows || [];
return rows.slice(rows.length - cap);
}
function collectQuarantinableEmails(results, into) {
const out = into instanceof Set ? into : new Set(into || []);
for (const r of results || []) {
if (isQuarantinable(r) && r.email) out.add(String(r.email));
}
return out;
}
export function MailPoolProbe({ pool, onReloadPool, onResult }) {
const [probeDomains, setProbeDomains] = useState([]);
const [probeLimit, setProbeLimit] = useState(30);
const [probeOut, setProbeOut] = useState(null);
const [selected, setSelected] = useState({}); // email -> bool
// Uncapped dead-email set across full-scan waves (table is capped).
const [quarantinableEmails, setQuarantinableEmails] = useState([]);
const [scanProgress, setScanProgress] = useState(null); // {offset, total, wave, ...}
const { setBusy, is, any } = useBusy();
// Abort flag for multi-wave full scan (mutable ref via object so closures see it).
const scanCtl = useMemo(() => ({ stop: false }), []);
// Seed the domain selection from whatever the pool reports (parent owns the
// fetch); never clobber a selection the user already made.
useEffect(() => {
if (!pool) return;
const known = pool.known_domains || [];
const present = Object.keys(pool.by_domain || {});
const defaults = known.filter((d) => present.includes(d));
setProbeDomains((prev) =>
prev.length ? prev : defaults.length ? defaults : known.slice(0, 2),
);
}, [pool]);
function toggleDomain(dom) {
setProbeDomains((prev) => {
if (prev.includes(dom)) return prev.filter((d) => d !== dom);
return [...prev, dom];
});
}
function selectFromEmailList(emails) {
const nextSel = {};
for (const e of emails || []) {
if (e) nextSel[e] = true;
}
setSelected(nextSel);
}
async function runProbeOnce({ offset = null, limit, concurrency, wallSeconds } = {}) {
const body = {
domains: probeDomains,
limit: Math.max(1, Math.min(WAVE_LIMIT_MAX, Number(limit ?? probeLimit) || 30)),
concurrency: concurrency ?? 4,
wall_seconds: wallSeconds ?? 90,
};
if (offset != null) body.offset = offset;
return api.probeMail(body);
}
async function runProbe() {
if (!probeDomains.length) {
showOpsFeedback("Отметьте хотя бы один домен (без отметок проверка всех не запускается)", "info");
return;
}
if (any) return;
scanCtl.stop = false;
setBusy("probe");
setScanProgress(null);
try {
const data = await runProbeOnce({
limit: probeLimit,
concurrency: 4,
wallSeconds: 90,
});
const qEmails = [...collectQuarantinableEmails(data.results)];
setQuarantinableEmails(qEmails);
setProbeOut(data);
selectFromEmailList(qEmails);
const qn =
data.quarantinable != null
? data.quarantinable
: qEmails.length;
const msg =
`Проверка завершена: рабочих ${data.ok || 0} / мёртвых к удалению ${qn} / неопред. ${Math.max(0, (data.dead || 0) - qn)}` +
(data.timed_out ? " · обрезано по таймауту" : "");
showOpsFeedback(msg, data.dead ? "info" : "ok");
onResult(
pretty({
probed: data.probed,
ok: data.ok,
dead: data.dead,
quarantinable: qn,
timed_out: data.timed_out,
by_status: data.by_status,
mode: data.mode,
}),
);
} catch (e) {
if (auth401(e)) return;
showOpsFeedback(`Ошибка проверки: ${formatApiError(e)}`, "err");
onResult(pretty({ error: formatApiError(e) }));
} finally {
setBusy("");
setScanProgress(null);
}
}
async function runFullScan() {
if (!probeDomains.length) {
showOpsFeedback("Отметьте хотя бы один домен (без отметок проверка всех не запускается)", "info");
return;
}
if (any) return;
const totalHint =
probeDomains.reduce((s, d) => s + Number((pool && pool.by_domain && pool.by_domain[d]) || 0), 0) ||
(pool && pool.total) ||
0;
// Prefer explicit per-wave input; if still default sample size (30), use a
// larger full-scan default so 64k does not need ~2k waves.
const rawLimit = Number(probeLimit);
const waveLimit = Math.max(
1,
Math.min(
WAVE_LIMIT_MAX,
Number.isFinite(rawLimit) && rawLimit > 0
? rawLimit === 30
? FULL_SCAN_DEFAULT_WAVE
: rawLimit
: FULL_SCAN_DEFAULT_WAVE,
),
);
const ok = window.confirm(
`Сканировать весь пул?\n\n` +
`· домены: ${probeDomains.join(", ")}\n` +
`· всего ~${totalHint || "?"}, скан волнами по ${waveLimit} (wall ${FULL_SCAN_WALL_SECONDS}s, обход CF 524)\n` +
`· до конца скана удаление/чистка запрещены (сбой offset); можно нажать «Стоп полного скана»\n` +
`· в таблице последние ${FULL_SCAN_RESULTS_CAP} строк; список к удалению копится полностью`,
);
if (!ok) return;
scanCtl.stop = false;
setBusy("probe");
setQuarantinableEmails([]);
// Higher concurrency; wall capped under CF ~100s origin budget.
const concurrency = 8;
const wallSeconds = FULL_SCAN_WALL_SECONDS;
let offset = 0;
let wave = 0;
let totalOk = 0;
let totalDead = 0;
let totalQ = 0;
let totalProbed = 0;
let byStatus = {};
let timedAny = false;
let allResults = [];
let qEmailSet = new Set();
let poolTotal = totalHint;
let stopped = false;
try {
while (!scanCtl.stop) {
wave += 1;
setScanProgress({
wave,
offset,
total: poolTotal,
probed: totalProbed,
ok: totalOk,
dead: totalDead,
quarantinable: totalQ,
});
const data = await runProbeOnce({
offset,
limit: waveLimit,
concurrency,
wallSeconds,
});
if (data.pool_filtered_total != null) poolTotal = data.pool_filtered_total;
totalProbed += Number(data.probed || 0);
totalOk += Number(data.ok || 0);
totalDead += Number(data.dead || 0);
totalQ += Number(data.quarantinable || 0);
timedAny = timedAny || !!data.timed_out;
byStatus = mergeByStatus(byStatus, data.by_status);
qEmailSet = collectQuarantinableEmails(data.results, qEmailSet);
allResults = capResults(
allResults.concat(data.results || []),
FULL_SCAN_RESULTS_CAP,
);
const qEmailList = [...qEmailSet];
const agg = {
mode: "sequential_all",
probed: totalProbed,
ok: totalOk,
dead: totalDead,
quarantinable: totalQ,
by_status: byStatus,
timed_out: timedAny,
results: allResults,
results_capped: allResults.length < totalProbed,
pool_filtered_total: poolTotal,
offset: data.offset,
next_offset: data.next_offset,
done: !!data.done,
wave,
};
setProbeOut(agg);
setQuarantinableEmails(qEmailList);
// Don't auto-select thousands mid-scan (selection is heavy); user hits «Выбрать все к удалению» after.
setScanProgress({
wave,
offset: data.offset,
next_offset: data.next_offset,
total: poolTotal,
probed: totalProbed,
ok: totalOk,
dead: totalDead,
quarantinable: totalQ,
done: !!data.done,
});
if (data.done || !data.probed) break;
const nxt = data.next_offset;
if (nxt == null || Number(nxt) <= offset) break;
offset = Number(nxt);
}
if (scanCtl.stop) stopped = true;
const qEmailList = [...qEmailSet];
setQuarantinableEmails(qEmailList);
selectFromEmailList(qEmailList);
const msg =
`${stopped ? "Полное сканирование остановлено" : "Полное сканирование завершено"}: проверено ${totalProbed}/${poolTotal || "?"} · рабочих ${totalOk} · к удалению ${totalQ} · неопред. ${Math.max(0, totalDead - totalQ)}` +
(timedAny ? " · включая волну с таймаутом" : "");
showOpsFeedback(msg, totalDead ? "info" : "ok", { toast: true, sticky: true });
onResult(
pretty({
mode: "sequential_all",
stopped,
probed: totalProbed,
ok: totalOk,
dead: totalDead,
quarantinable: totalQ,
pool_filtered_total: poolTotal,
waves: wave,
timed_out: timedAny,
by_status: byStatus,
results_shown: allResults.length,
quarantinable_emails: qEmailList.length,
}),
);
await onReloadPool();
} catch (e) {
if (auth401(e)) return;
showOpsFeedback(`Ошибка полного скана: ${formatApiError(e)}`, "err");
onResult(pretty({ error: formatApiError(e) }));
} finally {
setBusy("");
setScanProgress(null);
}
}
function stopFullScan() {
scanCtl.stop = true;
showOpsFeedback("Остановка полного скана (закончит текущую волну)…", "info");
}
function selectAllDead() {
// Prefer uncapped full-scan email list; fall back to visible table rows.
if (quarantinableEmails && quarantinableEmails.length) {
selectFromEmailList(quarantinableEmails);
return;
}
const next = {};
for (const r of (probeOut && probeOut.results) || []) {
if (isQuarantinable(r) && r.email) next[r.email] = true;
}
setSelected(next);
}
function clearSelection() {
setSelected({});
}
function toggleRow(email) {
setSelected((prev) => ({ ...prev, [email]: !prev[email] }));
}
const selectedEmails = useMemo(
() => Object.keys(selected).filter((k) => selected[k]),
[selected],
);
// Full scan mutates offsets against a frozen pool — block quarantine/compact
// while probe busy so single-slot useBusy cannot clear "probe" mid-loop.
const poolMutationsBlocked = is("probe");
async function doCompact(dryRun = false) {
if (poolMutationsBlocked) {
showOpsFeedback("Идёт проверка/полный скан — сначала остановите, потом чистите", "info");
return;
}
if (!dryRun) {
const ok = window.confirm(
"Выполнить чистку пула email?\n\n" +
"· дедуп по email (сохраняет первое вхождение)\n" +
"· удаляет невалидные строки\n" +
"· сначала бэкап mail_credentials.txt.bak-compact-*\n" +
"· не трогает dead-архив",
);
if (!ok) return;
}
setBusy("compact");
try {
const data = await api.compactMail({
dry_run: !!dryRun,
drop_invalid: true,
drop_comments: false,
});
onResult(pretty(data));
const summary =
data.summary ||
`${dryRun ? "Предпросмотр" : "Чистка"} · уникальных ${data.unique ?? "—"} · дублей ${data.duplicate_extra ?? 0}`;
showOpsFeedback(summary, data.changed ? "ok" : "info", {
toast: true,
sticky: true,
});
await onReloadPool();
} catch (e) {
if (auth401(e)) return;
showOpsFeedback(`Ошибка чистки: ${formatApiError(e)}`, "err");
onResult(pretty({ error: formatApiError(e) }));
} finally {
setBusy("");
}
}
async function doQuarantine() {
if (poolMutationsBlocked) {
showOpsFeedback("Идёт полный скан/проверка — сначала остановите, потом удаляйте (сбой offset)", "info");
return;
}
if (!selectedEmails.length) {
showOpsFeedback("Сначала отметьте email для исключения", "info");
return;
}
const rows = (probeOut && probeOut.results) || [];
const byEmail = Object.fromEntries(
rows.map((r) => [String(r.email || "").toLowerCase(), r]),
);
// Uncapped full-scan list is authoritative for hard-dead even when table capped.
const qSet = new Set(
(quarantinableEmails || []).map((e) => String(e).toLowerCase()),
);
const hard = [];
const soft = [];
for (const e of selectedEmails) {
const low = e.toLowerCase();
const r = byEmail[low];
if ((r && isQuarantinable(r)) || qSet.has(low)) hard.push(e);
else soft.push(e);
}
if (!hard.length) {
showOpsFeedback(
"Ни один выбранный элемент не в статусе удаления (grant_expired / refresh_invalid / abuse_mode)",
"info",
);
return;
}
const softNote = soft.length
? `\nЕщё ${soft.length} сетевых/неизвестных ошибок пропущено автоматически.`
: "";
const ok = window.confirm(
`Исключить ${hard.length} подтверждённо мёртвых email?${softNote}\n\n` +
`Они будут удалены из основного пула и добавлены в mail_credentials.dead.txt (сначала бэкап пула).\n` +
`удаляются только grant_expired / refresh_invalid / abuse_mode.`,
);
if (!ok) return;
setBusy("quarantine");
try {
const data = await api.quarantineMail({
emails: hard,
reason: "probe:ui",
});
const removedN = Number(data.removed || 0);
showOpsFeedback(
`Исключено ${removedN} (не найдено ${data.not_found || 0})`,
"ok",
);
onResult(pretty(data));
const gone = new Set(hard.map((e) => e.toLowerCase()));
setQuarantinableEmails((prev) =>
(prev || []).filter((e) => !gone.has(String(e).toLowerCase())),
);
if (probeOut) {
const left = (probeOut.results || []).filter(
(r) => !gone.has(String(r.email || "").toLowerCase()),
);
// Decrement aggregates by removed delta — never recompute from capped table.
const prevQ =
probeOut.quarantinable != null
? Number(probeOut.quarantinable)
: (probeOut.results || []).filter(isQuarantinable).length;
setProbeOut({
...probeOut,
results: left,
// keep probed/ok totals; dead/quarantinable shrink by successful removes
dead: Math.max(0, Number(probeOut.dead || 0) - removedN),
quarantinable: Math.max(0, prevQ - removedN),
});
}
setSelected({});
await onReloadPool();
} catch (e) {
if (auth401(e)) return;
showOpsFeedback(`Ошибка исключения: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
const domainChips = useMemo(() => {
const known = (pool && pool.known_domains) || [
"hotmail.com",
"outlook.com",
"live.com",
"msn.com",
];
const counts = (pool && pool.by_domain) || {};
return known.map((d) => ({
domain: d,
count: counts[d] || 0,
}));
}, [pool]);
return (
<div class="card mail-probe">
<h2>Проверка почтовых учётных данных (OAuth refresh)</h2>
<p class="hint">
Проверяет только обмен refresh_token на access_token; успех = рабочий. Только grant_expired /
refresh_invalid / abuse_mode по умолчанию можно исключить; сетевой таймаут помечается «неопред.» и не отмечается по умолчанию. Пароль/token не возвращаются.
За одну проверку максимум {WAVE_LIMIT_MAX}/волна; для больших пулов используйте «Сканировать весь пул» (много волн по offset).
</p>
<div class="mail-probe-kpis">
<span>
Уникальных в основном пуле <strong>{pool ? pool.total : "—"}</strong>
</span>
{pool && pool.raw_lines != null && pool.raw_lines !== pool.total ? (
<span>
Строк в файле <strong>{pool.raw_lines}</strong>
</span>
) : null}
{pool && pool.duplicate_extra ? (
<span class="warn">
Лишних дублей <strong>{pool.duplicate_extra}</strong>
</span>
) : null}
{pool && pool.invalid_lines ? (
<span class="warn">
Невалидных строк <strong>{pool.invalid_lines}</strong>
</span>
) : null}
<span>
Архив dead <strong>{pool ? pool.dead_total : "—"}</strong>
</span>
{pool && pool.by_domain
? Object.entries(pool.by_domain).map(([d, n]) => (
<span key={d}>
{d} <strong>{n}</strong>
</span>
))
: null}
</div>
<div class="mail-probe-controls toolbar wrap">
<div class="mail-domain-chips">
{domainChips.map(({ domain, count }) => (
<label key={domain} class="check chip">
<input
type="checkbox"
checked={probeDomains.includes(domain)}
onChange={() => toggleDomain(domain)}
disabled={is("probe")}
/>{" "}
{domain}
{count ? ` (${count})` : ""}
</label>
))}
</div>
<label class="inline">
За волну{" "}
<input
type="number"
min={1}
max={WAVE_LIMIT_MAX}
value={probeLimit}
style={{ width: "5rem" }}
disabled={is("probe")}
onInput={(e) => setProbeLimit(e.currentTarget.value)}
title={`Лимит волны/выборки ${WAVE_LIMIT_MAX}; при полном скане = размер волны`}
/>
</label>
<Button
variant="primary"
busy={is("probe") && !scanProgress}
onClick={runProbe}
disabled={is("probe") || !probeDomains.length}
>
Начать проверку (выборка)
</Button>
<Button
variant="primary"
busy={is("probe") && !!scanProgress}
onClick={runFullScan}
disabled={is("probe") || !probeDomains.length}
title="Скан всех выбранных доменов постранично по offset в порядке файла"
>
Сканировать весь пул
</Button>
{is("probe") && scanProgress ? (
<Button variant="danger" onClick={stopFullScan}>
Стоп полного скана
</Button>
) : null}
<Button variant="ghost" onClick={onReloadPool} disabled={is("probe")}>
Обновить статистику
</Button>
<Button
variant="ghost"
busy={is("compact")}
onClick={() => doCompact(true)}
disabled={is("compact") || is("probe")}
>
Предпросмотр чистки
</Button>
<Button
variant="ghost"
busy={is("compact")}
onClick={() => doCompact(false)}
disabled={
is("compact") ||
is("probe") ||
!(pool && (pool.needs_compact || pool.duplicate_extra || pool.invalid_lines))
}
title={
pool && pool.needs_compact
? "Дедуп по email + удаление невалидных строк"
: "Чистка не нужна (нет дублей/невалидных строк)"
}
>
Чистка/дедуп
{pool && pool.duplicate_extra ? ` (−${pool.duplicate_extra})` : ""}
</Button>
</div>
{scanProgress ? (
<p class="hint mail-probe-progress">
Идёт полный скан · волна {scanProgress.wave} · offset {scanProgress.offset}
{scanProgress.next_offset != null ? ` → ${scanProgress.next_offset}` : ""}
{" · "}
Проверено {scanProgress.probed}
{scanProgress.total ? ` / ${scanProgress.total}` : ""}
{" · рабочие "}
{scanProgress.ok}
{" · к удалению "}
{scanProgress.quarantinable}
</p>
) : null}
{probeOut ? (
<div class="mail-probe-results">
<div class="toolbar wrap">
<span>
Результат: проверено {probeOut.probed}
{probeOut.pool_filtered_total != null
? ` / ${probeOut.pool_filtered_total}`
: ""}
{" · рабочие "}
{probeOut.ok} · к удалению{" "}
{probeOut.quarantinable != null
? probeOut.quarantinable
: (probeOut.results || []).filter(isQuarantinable).length}
{" · неопред. "}
{Math.max(
0,
(probeOut.dead || 0) -
(probeOut.quarantinable != null
? probeOut.quarantinable
: (probeOut.results || []).filter(isQuarantinable).length),
)}
{probeOut.timed_out ? " · обрезано по таймауту" : ""}
{probeOut.mode === "sequential_all" || probeOut.mode === "sequential"
? ` · ${probeOut.mode}`
: ""}
{probeOut.results_capped
? ` · в таблице только последние ${(probeOut.results || []).length} строк`
: ""}
</span>
<Button variant="ghost" onClick={selectAllDead}>
Выбрать все к удалению
</Button>
<Button variant="ghost" onClick={clearSelection}>
Снять отметки
</Button>
<Button
variant="danger"
busy={is("quarantine")}
onClick={doQuarantine}
disabled={
!selectedEmails.length ||
is("quarantine") ||
poolMutationsBlocked
}
title={
poolMutationsBlocked
? "Во время проверки/полного скана удаление запрещено (сбой offset)"
: undefined
}
>
Исключить выбранные ({selectedEmails.length})
</Button>
</div>
<div class="table-wrap">
<table class="data-table">
<thead>
<tr>
<th></th>
<th>email</th>
<th>domain</th>
<th>Статус</th>
<th>reason</th>
</tr>
</thead>
<tbody>
{(probeOut.results || []).map((r) => {
const q = isQuarantinable(r);
const soft = r.status !== "ok" && !q;
const rowClass = r.status === "ok" ? "ok" : q ? "dead" : "soft";
const badgeClass =
r.status === "ok" ? "badge ok" : q ? "badge bad" : "badge soft";
return (
<tr key={r.email} class={rowClass}>
<td>
<input
type="checkbox"
checked={!!selected[r.email]}
onChange={() => toggleRow(r.email)}
disabled={r.status === "ok"}
/>
</td>
<td>{r.email}</td>
<td>{r.domain}</td>
<td>
<span class={badgeClass}>
{statusLabel(r)}
{r.status !== "ok" ? ` / ${r.status}` : ""}
{soft ? " · по умолчанию не удаляются" : ""}
</span>
</td>
<td class="muted" title={r.ms_error || r.reason || ""}>
{(r.ms_error || r.reason || "").slice(0, 80)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
) : null}
</div>
);
}
@@ -0,0 +1,175 @@
// MailProviderPanels — the six per-provider collapsible panels.
// Batch-2 IA: глобальный defaultDomains (включая выбор доменов Worker) поднят в
// DefaultDomainsCard, в этом компоненте остались только настоящие per-provider поля.
export function MailProviderPanels({ form, set, openPanels, onTogglePanel }) {
function panel(name, title, body) {
const open = !!openPanels[name];
return (
<details
class="card provider-panel"
open={open}
onToggle={(e) => {
const next = e.currentTarget.open;
onTogglePanel(name, next);
}}
>
<summary class="provider-panel-summary" onClick={(e) => e.preventDefault()}>
<button type="button" class="provider-panel-toggle" onClick={() => onTogglePanel(name)}>
{open ? "▾" : "▸"} {title}
</button>
</summary>
{open ? <div class="provider-panel-body grid mail-form">{body}</div> : null}
</details>
);
}
return (
<>
{panel(
"cloudflare",
"Cloudflare temp-mail",
<>
<label>
cloudflare_api_base
<input
value={form.cloudflare_api_base}
placeholder="https://mail-api.example.com"
onInput={(e) => set({ cloudflare_api_base: e.currentTarget.value })}
/>
</label>
<label>
cloudflare_api_key
<input
type="password"
value={form.cloudflare_api_key}
placeholder="leave empty to keep"
onInput={(e) => set({ cloudflare_api_key: e.currentTarget.value })}
/>
</label>
<p class="span2 hint tight">
Выбор доменов и <code>defaultDomains</code> редактируются выше в «Глобальный пул доменов».
</p>
</>,
)}
{panel(
"cloudmail",
"CloudMail (свой)",
<>
<label>
cloudmail_url
<input
value={form.cloudmail_url}
placeholder="https://mail.example.com"
onInput={(e) => set({ cloudmail_url: e.currentTarget.value })}
/>
</label>
<label>
cloudmail_admin_email
<input
value={form.cloudmail_admin_email}
onInput={(e) => set({ cloudmail_admin_email: e.currentTarget.value })}
/>
</label>
<label>
cloudmail_password
<input
type="password"
value={form.cloudmail_password}
placeholder="leave empty to keep"
onInput={(e) => set({ cloudmail_password: e.currentTarget.value })}
/>
</label>
<p class="span2 hint tight">
Домены приёма — <code>defaultDomains</code> из «Глобальный пул доменов» выше.
</p>
</>,
)}
{panel(
"duckmail",
"DuckMail",
<>
<label class="span2">
duckmail_api_key
<input
type="password"
value={form.duckmail_api_key}
placeholder="leave empty to keep"
onInput={(e) => set({ duckmail_api_key: e.currentTarget.value })}
/>
</label>
<p class="span2 hint tight">Домены берутся автоматически из DuckMail API /domains, defaultDomains заполнять не нужно.</p>
</>,
)}
{panel(
"yyds",
"yydsmail",
<>
<label class="span2">
yyds_api_key
<input
type="password"
value={form.yyds_api_key}
placeholder="leave empty to keep"
onInput={(e) => set({ yyds_api_key: e.currentTarget.value })}
/>
</label>
<p class="span2 hint tight">
Домены загружаются из yyds API. Если нужен jwt — укажите YYDS_JWT в .env (здесь не раскрывается).
</p>
</>,
)}
{panel(
"gmail",
"Gmail catch-all(IMAP)",
<>
<p class="span2 hint">
Форма не пишет app-пароль. Настройте в <code>.env</code> проекта{" "}
<code>GMAIL_IMAP_USER</code> / <code>GMAIL_IMAP_PASSWORD</code>
; catch-all домены используют глобальный defaultDomains выше (панели CF/CloudMail).
</p>
<label>
gmail_imap_user (опциональная подсказка)
<input
value={form.gmail_imap_user}
placeholder="опционально · можно только .env"
onInput={(e) => set({ gmail_imap_user: e.currentTarget.value })}
/>
</label>
</>,
)}
{panel(
"hotmail",
"Hotmail / Outlook",
<>
<label>
hotmail_accounts_file
<input
value={form.hotmail_accounts_file}
placeholder="mail_credentials.txt"
onInput={(e) => set({ hotmail_accounts_file: e.currentTarget.value })}
/>
</label>
<label class="check span2">
<input
type="checkbox"
checked={!!form.hotmail_allow_plus_alias}
onChange={(e) =>
set({ hotmail_allow_plus_alias: e.currentTarget.checked })
}
/>{" "}
hotmail_allow_plus_alias (не включать в проде)
</label>
<p class="span2 hint tight">
Формат учётных данных: <code>email----password----ClientID----refresh_token</code>
. defaultDomains не используется. Ниже — пакетный импорт.
</p>
</>,
)}
</>
);
}
@@ -0,0 +1,24 @@
// Domain-list helpers shared by MailTab and its sub-panels.
// Moved verbatim from MailTab.jsx — behavior unchanged.
export function parseDomainList(raw) {
return String(raw || "")
.replace(/,/g, ",")
.split(/[,\s]+/)
.map((s) => s.trim())
.filter(Boolean);
}
export function joinDomains(list) {
const out = [];
const seen = new Set();
for (const d of list || []) {
const name = String(d || "").trim();
if (!name) continue;
const low = name.toLowerCase();
if (seen.has(low)) continue;
seen.add(low);
out.push(name);
}
return out.join(",");
}
@@ -0,0 +1,29 @@
import { describe, it, expect } from "vitest";
import { parseDomainList, joinDomains } from "./domains.js";
describe("parseDomainList", () => {
it("splits on comma, full-width comma, and whitespace", () => {
expect(parseDomainList("a.com,b.com c.com")).toEqual([
"a.com",
"b.com",
"c.com",
]);
});
it("returns [] for empty/null", () => {
expect(parseDomainList("")).toEqual([]);
expect(parseDomainList(null)).toEqual([]);
});
});
describe("joinDomains", () => {
it("dedupes case-insensitively, keeping first spelling and order", () => {
expect(joinDomains(["A.com", "b.com", "a.COM"])).toBe("A.com,b.com");
});
it("drops blanks", () => {
expect(joinDomains(["", " ", "a.com"])).toBe("a.com");
});
it("returns '' for empty/null", () => {
expect(joinDomains(null)).toBe("");
expect(joinDomains([])).toBe("");
});
});
@@ -0,0 +1,356 @@
// CatalogPanel — каталог проекта: добавление узлов + фильтр/пагинация + таблица catalog.
// Moved verbatim from NodesTab.jsx — JSX/classes/copy unchanged.
import { useCallback, useEffect, useState } from "preact/hooks";
import * as api from "../../../api/client.js";
import { showOpsFeedback } from "../../../store/feedback.js";
import { Button, Select, LogDetails } from "../../../ui/index.js";
import { formatApiError, healthBadge } from "../../../lib/format.js";
import { pretty, auth401 } from "../../../lib/http.js";
import { useBusy } from "../../../lib/useBusy.js";
import { HEALTH_OPTS, TIER_OPTS, PAGE_SIZES } from "./clashFilters.js";
export function CatalogPanel({ active = true }) {
const { setBusy, is: busyIs } = useBusy();
const [cat, setCat] = useState(null);
const [catQ, setCatQ] = useState("");
const [catHealth, setCatHealth] = useState("");
const [catTier, setCatTier] = useState("");
const [catPageSize, setCatPageSize] = useState("50");
const [catPage, setCatPage] = useState(1);
const [catResult, setCatResult] = useState("");
const [addUrl, setAddUrl] = useState("");
const [addLabel, setAddLabel] = useState("");
const [addTags, setAddTags] = useState("");
const [addTier, setAddTier] = useState("0");
const refreshCatalog = useCallback(async (override = {}) => {
setBusy("catalog");
try {
const page = override.page != null ? override.page : catPage;
const q = override.q != null ? override.q : catQ;
const health = override.health != null ? override.health : catHealth;
const tier = override.tier != null ? override.tier : catTier;
const pageSize =
override.pageSize != null ? override.pageSize : catPageSize;
const params = new URLSearchParams();
const qq = String(q || "").trim();
if (qq) params.set("q", qq);
if (health) params.set("health", health);
if (tier !== "") params.set("tier", tier);
params.set("page", String(page));
params.set("page_size", pageSize);
params.set("sort", "priority");
const data = await api.listCatalog(params.toString());
setCat(data);
if (override.page != null) setCatPage(override.page);
else if (data.page != null) setCatPage(data.page);
} catch (e) {
if (auth401(e)) return;
setCat(null);
setCatResult(String(e.message || e));
} finally {
setBusy("");
}
}, [catQ, catHealth, catTier, catPage, catPageSize]);
async function onCatalogAction(act, id, enabled) {
try {
if (act === "del") {
if (!window.confirm(`Удалить узел ${id}?`)) return;
setCatResult(pretty(await api.deleteCatalogNode(id)));
} else if (act === "toggle") {
setCatResult(
pretty(await api.patchCatalogNode(id, { enabled: !enabled })),
);
} else if (act === "test") {
setCatResult(pretty(await api.testCatalog({ ids: [id] })));
}
await refreshCatalog();
} catch (e) {
if (auth401(e)) return;
setCatResult(String(e.message || e));
}
}
async function addNode() {
try {
const tags = (addTags || "")
.split(/[,;]/)
.map((s) => s.trim())
.filter(Boolean);
const data = await api.addCatalogNode({
url: addUrl.trim(),
label: addLabel.trim(),
tags,
tier: Number(addTier || 0),
enabled: true,
});
setCatResult(pretty(data));
if (data.ok) {
setAddUrl("");
setAddLabel("");
}
await refreshCatalog();
} catch (e) {
if (auth401(e)) return;
setCatResult(String(e.message || e));
}
}
async function testAllCatalog() {
setCatResult("testing…");
try {
const data = await api.testCatalog({ limit: 50 });
setCatResult(pretty(data));
await refreshCatalog();
} catch (e) {
if (auth401(e)) return;
setCatResult(String(e.message || e));
}
}
const catPages = cat?.pages || 1;
const catCur = cat?.page || catPage;
// Same semantics as the old combined NodesTab: refresh on every switch to
// this subtab (the original effect keyed on `sub`), skip while inactive.
useEffect(() => {
if (active) refreshCatalog({ page: 1 });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
if (!active) return null;
return (
<>
<div class="card grid">
<label>
proxy URL{" "}
<input
value={addUrl}
placeholder="http://user:pass@host:port"
onInput={(e) => setAddUrl(e.currentTarget.value)}
/>
</label>
<label>
label{" "}
<input
value={addLabel}
onInput={(e) => setAddLabel(e.currentTarget.value)}
/>
</label>
<label>
tags{" "}
<input
value={addTags}
placeholder="residential,us"
onInput={(e) => setAddTags(e.currentTarget.value)}
/>
</label>
<label>
tier{" "}
<select
value={addTier}
onChange={(e) => setAddTier(e.currentTarget.value)}
>
<option value="0">0 datacenter</option>
<option value="1">1 residential</option>
</select>
</label>
<div class="actions">
<Button variant="ghost" onClick={addNode}>
Добавить узел
</Button>
<Button variant="ghost" onClick={testAllCatalog}>
Проверка(enabled≤50)
</Button>
<Button
variant="ghost"
busy={busyIs("catalog")}
onClick={() => refreshCatalog()}
>
Обновить
</Button>
</div>
</div>
<div class="card filter-bar">
<label class="inline">
Поиск{" "}
<input
value={catQ}
onInput={(e) => setCatQ(e.currentTarget.value)}
/>
</label>
<label class="inline">
жив{" "}
<Select
value={catHealth}
options={HEALTH_OPTS}
onChange={(v) => {
setCatHealth(v);
refreshCatalog({ page: 1, health: v });
}}
/>
</label>
<label class="inline">
tier{" "}
<Select
value={catTier}
options={TIER_OPTS}
onChange={(v) => {
setCatTier(v);
refreshCatalog({ page: 1, tier: v });
}}
/>
</label>
<label class="inline">
На стр.{" "}
<Select
value={catPageSize}
options={PAGE_SIZES}
onChange={(v) => {
setCatPageSize(v);
refreshCatalog({ page: 1, pageSize: v });
}}
/>
</label>
<Button
variant="ghost"
size="sm"
disabled={catCur <= 1}
onClick={() => refreshCatalog({ page: Math.max(1, catCur - 1) })}
>
Назад
</Button>
<Button
variant="ghost"
size="sm"
disabled={catCur >= catPages}
onClick={() => refreshCatalog({ page: catCur + 1 })}
>
Вперёд
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => refreshCatalog({ page: 1, q: catQ })}
>
Применить фильтр
</Button>
<span class="hint">
page {catCur}/{catPages} · showing {(cat?.nodes || []).length}
</span>
</div>
<div class={`card ${cat && cat.healthy > 0 ? "ok" : "muted"}`}>
{cat
? `path=${cat.path} · total=${cat.total} enabled=${cat.enabled} healthy=${cat.healthy}` +
(cat.fail != null ? ` fail=${cat.fail}` : "") +
(cat.unknown != null ? ` unknown=${cat.unknown}` : "") +
` · фильтр ${cat.filtered}/${cat.total} · стр. ${cat.page}/${cat.pages || 1}`
: "—"}
</div>
<div class="card table-wrap">
<table class="data">
<thead>
<tr>
<th>Статус</th>
<th>label</th>
<th>tier</th>
<th>Задержка</th>
<th>IP</th>
<th>Приоритет</th>
<th>Ошибка</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
{!(cat?.nodes || []).length ? (
<tr>
<td colspan="8" class="hint">
Нет подходящих узлов
</td>
</tr>
) : (
(cat.nodes || []).map((n) => {
const health =
n.health ||
(n.last_ok === true
? "ok"
: n.last_ok === false
? "fail"
: "unknown");
const hb = healthBadge(health);
return (
<tr key={n.id}>
<td>
<span
class={`badge ${hb.cls === "danger" ? "fail" : hb.cls === "ok" ? "ok" : "unknown"}`}
>
{hb.label}
</span>
{n.cooling
? ` · cool:${n.cooldown_reason || ""}`
: ""}
{n.enabled === false ? (
<span class="badge fail">выкл</span>
) : null}
</td>
<td>
<div>{n.label || n.id}</div>
<div class="hint">{n.id}</div>
</td>
<td>{n.tier === 1 ? "резидентный" : "дата-центр"}</td>
<td>{n.last_ms != null ? `${n.last_ms}ms` : "—"}</td>
<td>{n.last_ip || "—"}</td>
<td>
{n.priority_score != null
? n.priority_score
: n.quality_score != null
? n.quality_score
: "—"}
</td>
<td>
{n.fail_count || 0}
{n.last_error ? (
<div class="hint">{n.last_error}</div>
) : null}
</td>
<td class="ops">
<Button
variant="ghost"
size="sm"
onClick={() => onCatalogAction("test", n.id)}
>
Проверка
</Button>
<Button
variant="ghost"
size="sm"
onClick={() =>
onCatalogAction("toggle", n.id, n.enabled !== false)
}
>
{n.enabled === false ? "вкл" : "выкл"}
</Button>
<Button
variant="danger"
size="sm"
onClick={() => onCatalogAction("del", n.id)}
>
Удалить
</Button>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
<LogDetails text={catResult} summary="Детали ответа catalog" compact />
</>
);
}
@@ -0,0 +1,564 @@
// ClashPanel — встроенный Clash / mihomo: импорт подписки + проверка пула + группы стратегий + таблица leaf-узлов.
// Moved verbatim from NodesTab.jsx — JSX/classes/copy unchanged.
import { useCallback, useEffect, useMemo, useState } from "preact/hooks";
import * as api from "../../../api/client.js";
import { showOpsFeedback } from "../../../store/feedback.js";
import { Button, Select, Chip, LogDetails } from "../../../ui/index.js";
import { formatApiError, healthBadge } from "../../../lib/format.js";
import { pretty, auth401 } from "../../../lib/http.js";
import { useBusy } from "../../../lib/useBusy.js";
import {
filterClashLeaves,
namesInPool,
CLASH_FILTER,
IMPORT_POOL_OPTS,
IMPORT_MODE_OPTS,
} from "./clashFilters.js";
export function ClashPanel({ active = true }) {
const [clash, setClash] = useState(null);
const [clashFilter, setClashFilter] = useState("pool");
const [clashQ, setClashQ] = useState("");
const [clashResult, setClashResult] = useState("");
const { setBusy, is: busyIs } = useBusy();
const [importUrl, setImportUrl] = useState("");
// Default real import (write + reload). dry-run is opt-in via checkbox.
const [importDry, setImportDry] = useState(false);
const [importGroup, setImportGroup] = useState("🎯Grok-регистрация");
const [importMode, setImportMode] = useState("merge");
const [importPrefix, setImportPrefix] = useState("SUB");
// Pool health: independent from subscription import prefix/mode.
const [poolTarget, setPoolTarget] = useState("🎯Grok-регистрация");
const [lastPoolProbe, setLastPoolProbe] = useState(null);
const refreshClash = useCallback(async () => {
setBusy("clash");
try {
const data = await api.listClash();
setClash(data);
if (data && !data.ok) setClashResult(pretty(data));
else setClashResult("");
} catch (e) {
if (auth401(e)) return;
setClash(null);
setClashResult(String(e.message || e));
} finally {
setBusy("");
}
}, []);
const shownLeaves = useMemo(() => {
if (!clash || !clash.ok) return [];
return filterClashLeaves(clash.leaves || [], clashFilter, clashQ);
}, [clash, clashFilter, clashQ]);
async function clashTestOne(name) {
setClashResult("testing…");
try {
const r = await api.testClash({ names: [name], timeout_ms: 4000, limit: 1 });
setClashResult(pretty(r));
await refreshClash();
} catch (e) {
if (auth401(e)) return;
setClashResult(String(e.message || e));
}
}
async function clashTest(limit, poolOnly) {
setClashResult("testing…");
setBusy("test");
try {
let names = null;
if (poolOnly) {
const listing = clash || (await api.listClash());
names = namesInPool(listing, "🎯Grok-регистрация", limit || 120);
if (!names.length) {
names = (listing.leaves || [])
.filter((x) => x.in_register_pool)
.map((x) => x.name)
.slice(0, limit || 120);
}
}
const body = names
? { names, limit: names.length || 40, timeout_ms: 4000 }
: { limit: limit || 40, timeout_ms: 4000 };
const data = await api.testClash(body);
setClashResult(pretty(data));
showOpsFeedback(
data.ok
? `Проверка завершена · проверено ${data.tested || 0} · живых ${data.healthy || 0}`
: `Ошибка проверки: ${(data && (data.error || data.message)) || "unknown"}`,
data.ok ? "ok" : "err",
);
await refreshClash();
} catch (e) {
if (auth401(e)) return;
setClashResult(String(e.message || e));
showOpsFeedback(`Ошибка проверки: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
async function doPoolDelayTest() {
const group = (poolTarget || "").trim() || "🎯Grok-регистрация";
setBusy("pool-test");
setClashResult("testing pool…");
try {
const listing = clash || (await api.listClash());
const names = namesInPool(listing, group, 120);
if (!names.length) {
showOpsFeedback(`В пуле «${group}» нет проверяемых leaf-узлов`, "warn");
setClashResult(pretty({ ok: false, error: "empty_pool", group }));
return;
}
const data = await api.testClash({
names,
limit: names.length,
timeout_ms: 4000,
});
setClashResult(pretty(data));
const tested = data.tested != null ? data.tested : 0;
const healthy = data.healthy != null ? data.healthy : 0;
const dead = Math.max(0, tested - healthy);
setLastPoolProbe({
group,
tested,
healthy,
dead,
ms: data.ms,
at: Date.now(),
});
showOpsFeedback(
data.ok
? `Проверка пула «${group}» · проверено ${tested} · живых ${healthy} · мёртвых ${dead}${data.ms != null ? ` · ${data.ms}ms` : ""}`
: `Ошибка проверки пула: ${(data && (data.error || data.message)) || "unknown"}`,
data.ok ? "ok" : "err",
);
await refreshClash();
} catch (e) {
if (auth401(e)) return;
setClashResult(String(e.message || e));
showOpsFeedback(`Ошибка проверки пула: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
async function doPoolDeleteDead() {
const group = (poolTarget || "").trim() || "🎯Grok-регистрация";
if (
!window.confirm(
`Проверить пул «${group}» и удалить мёртвые узлы?\n\nУдалит определения мёртвых узлов и ссылки групп из Clash YAML, затем hot-reload.\nНе влияет на запущенные batch / coinbot.`,
)
) {
return;
}
setBusy("pool-prune");
try {
const data = await api.pruneClashUnhealthy({
prefix: "",
group,
dry_run: false,
reload: true,
delete_defs: true,
timeout_ms: 4000,
limit: 120,
});
setClashResult(pretty(data));
const dead =
data.unhealthy != null
? data.unhealthy
: data.would_remove != null
? data.would_remove
: 0;
const tested = data.tested != null ? data.tested : 0;
const healthy = data.healthy != null ? data.healthy : Math.max(0, tested - dead);
setLastPoolProbe({
group,
tested,
healthy,
dead,
removed: data.removed != null ? data.removed : dead,
ms: data.ms,
at: Date.now(),
});
showOpsFeedback(
data.ok
? `Удалены мёртвые «${group}» · проверено ${tested} · мёртвых ${dead} · удалено ${data.removed != null ? data.removed : dead}`
: `Ошибка удаления мёртвых: ${(data && (data.detail || data.error || data.message)) || "unknown"}`,
data.ok ? "ok" : "err",
);
if (data.ok) await refreshClash();
} catch (e) {
if (auth401(e)) return;
setClashResult(String(e.message || e));
showOpsFeedback(`Ошибка удаления мёртвых: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
async function doPoolPreviewDead() {
const group = (poolTarget || "").trim() || "🎯Grok-регистрация";
setBusy("pool-preview");
try {
const data = await api.pruneClashUnhealthy({
prefix: "",
group,
dry_run: true,
reload: false,
delete_defs: true,
timeout_ms: 4000,
limit: 120,
});
setClashResult(pretty(data));
const dead =
data.unhealthy != null
? data.unhealthy
: data.would_remove != null
? data.would_remove
: 0;
const tested = data.tested != null ? data.tested : 0;
const healthy = data.healthy != null ? data.healthy : Math.max(0, tested - dead);
setLastPoolProbe({
group,
tested,
healthy,
dead,
preview: true,
ms: data.ms,
at: Date.now(),
});
showOpsFeedback(
data.ok
? `Предпроверка «${group}» · проверено ${tested} · живых ${healthy} · будет удалено ${dead} (без записи)`
: `Ошибка предпроверки: ${(data && (data.detail || data.error || data.message)) || "unknown"}`,
data.ok ? "ok" : "err",
);
} catch (e) {
if (auth401(e)) return;
setClashResult(String(e.message || e));
showOpsFeedback(`Ошибка предпроверки: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
async function doImportUrl() {
const url = importUrl.trim();
if (!url) {
showOpsFeedback("Введите URL подписки", "warn");
return;
}
const group = (importGroup || "").trim() || "🎯Grok-регистрация";
const prefix = (importPrefix || "").trim() || "SUB";
const mode = (importMode || "merge").trim() || "merge";
setBusy("import");
try {
// Backend: group + groups — we send both so the chosen pool is explicit
// (default alone used to look like "whatever is in YAML" when UI omitted it).
const body = {
url,
dry_run: importDry,
group,
groups: [group],
prefix,
mode,
reload: !importDry,
};
const data = await api.importClashUrl(body);
setClashResult(pretty(data));
const ms =
data.total_ms != null
? data.total_ms
: data.timings && data.timings.total_ms;
const msTxt = ms != null ? ` · ${Math.round(ms)}ms` : "";
const poolTxt = (data.groups && data.groups.join(",")) || group;
const n =
(data.parse && data.parse.imported) != null
? data.parse.imported
: data.ok
? "?"
: 0;
showOpsFeedback(
data.ok
? `Импорт Clash${importDry ? " dry-run" : ""} · ${n} узлов → пул ${poolTxt}${msTxt}`
: `Ошибка импорта: ${(data && (data.detail || data.error || data.message)) || "unknown"}`,
data.ok ? "ok" : "err",
);
if (!importDry && data.ok) await refreshClash();
} catch (e) {
if (auth401(e)) return;
setClashResult(String(e.message || e));
showOpsFeedback(`Ошибка импорта: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
const leaves = clash?.leaves || [];
const poolN = leaves.filter((x) => x.in_register_pool).length;
const okN = leaves.filter((x) => x.health === "ok").length;
// Same semantics as the old combined NodesTab: refresh on every switch to
// this subtab (the original effect keyed on `sub`), skip while inactive.
useEffect(() => {
if (active) refreshClash();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
if (!active) return null;
return (
<>
<div class="card actions-bar">
<Button
variant="ghost"
busy={busyIs("clash")}
onClick={refreshClash}
>
Обновить Clash
</Button>
<Button
variant="ghost"
busy={busyIs("test")}
onClick={() => clashTest(40, true)}
>
ПроверкаПул регистрации
</Button>
<Button
variant="ghost"
busy={busyIs("test")}
onClick={() => clashTest(40, false)}
>
Проверка (первые 40)
</Button>
<label class="inline">
Фильтр{" "}
<Select
value={clashFilter}
options={CLASH_FILTER}
onChange={setClashFilter}
/>
</label>
<label class="inline">
Поиск{" "}
<input
value={clashQ}
placeholder="Ключевое слово названия"
onInput={(e) => setClashQ(e.currentTarget.value)}
/>
</label>
<span class="hint">
{clash && clash.ok
? `api=${clash.api} · leaves=${clash.leaf_count} · пул регистрации ${poolN} · доступно ${okN} · показано ${shownLeaves.length} · groups=${clash.group_count} · secret=${clash.secret_configured ? "yes" : "no"}`
: clash
? `Clash недоступен: ${clash.error || "unknown"} (api=${clash.api || ""})`
: "—"}
</span>
</div>
<div class="card">
<h2>Импорт подписки</h2>
<p class="hint" style={{ marginTop: 0 }}>
Узлы записываются в список leaf-узлов <strong>указанной группы стратегии (пула)</strong> в Clash YAML.
Батчи регистрации используют группы «🎯Grok-регистрация / ♻️Grok-избранное»; не выбирайте посторонние основные группы стратегий.
</p>
<div class="actions-bar wrap">
<input
class="grow"
value={importUrl}
placeholder="https://… subscription URL"
onInput={(e) => setImportUrl(e.currentTarget.value)}
/>
</div>
<div class="actions-bar wrap">
<label class="inline">
Целевой пул{" "}
<Select
value={importGroup}
options={IMPORT_POOL_OPTS}
onChange={setImportGroup}
/>
</label>
<label class="inline">
Режим{" "}
<Select
value={importMode}
options={IMPORT_MODE_OPTS}
onChange={setImportMode}
/>
</label>
<label class="inline">
Префикс{" "}
<input
style={{ width: "6rem" }}
value={importPrefix}
title="Префикс имён узлов; при replace_prefix старые подписки чистятся по этому префиксу"
onInput={(e) => setImportPrefix(e.currentTarget.value)}
/>
</label>
<label class="check">
<input
type="checkbox"
checked={importDry}
onChange={(e) => setImportDry(e.currentTarget.checked)}
/>{" "}
Только предпроверка (без записи)
</label>
<Button
variant="primary"
busy={busyIs("import")}
onClick={doImportUrl}
>
{importDry ? "Предпроверка" : "Импорт"}
</Button>
</div>
<p class="hint">
Текущая цель: <code>{importGroup || "🎯Grok-регистрация"}</code>
{" · "}
{importMode}
{" · "}
prefix=<code>{importPrefix || "SUB"}</code>
{importDry ? " · только предпроверка, без записи" : " · импорт в выбранный пул + hot-reload"}
</p>
</div>
<div class="card">
<h2>Проверка пула / удаление мёртвых</h2>
<p class="hint" style={{ marginTop: 0 }}>
Выберите группу стратегии (пул узлов) → сначала <strong>Проверка</strong> для задержки, или
<strong>Удалить мёртвые одним кликом</strong> (узлы с failed delay удаляются из YAML + hot-reload).
Не влияет на процессы batch / coinbot. За раз проверяется/удаляется до ~120 узлов.
</p>
<div class="actions-bar wrap">
<label class="inline">
Пул узлов{" "}
<Select
value={poolTarget}
options={IMPORT_POOL_OPTS}
onChange={setPoolTarget}
/>
</label>
<Button
variant="primary"
busy={busyIs("pool-test")}
onClick={doPoolDelayTest}
>
Проверить этот пул
</Button>
<Button
variant="ghost"
busy={busyIs("pool-preview")}
onClick={doPoolPreviewDead}
>
Сколько удалит предпроверка
</Button>
<Button
variant="danger"
busy={busyIs("pool-prune")}
onClick={doPoolDeleteDead}
>
Удалить мёртвые узлы
</Button>
</div>
<p class="hint">
Текущий пул:<code>{poolTarget || "🎯Grok-регистрация"}</code>
{lastPoolProbe && lastPoolProbe.group === poolTarget
? ` · прошлый раз: проверено ${lastPoolProbe.tested} · живых ${lastPoolProbe.healthy} · мёртвых ${lastPoolProbe.dead}${
lastPoolProbe.preview
? "(предпроверка без записи)"
: lastPoolProbe.removed != null
? ` · удалено ${lastPoolProbe.removed}`
: ""
}${lastPoolProbe.ms != null ? ` · ${lastPoolProbe.ms}ms` : ""}`
: " · ещё не проверены"}
</p>
</div>
<div class="card">
<h2>Группа стратегии</h2>
<div class="chip-row">
{(clash?.groups || []).map((g, i) => (
<Chip
key={i}
class={g.register_relevant ? "hot" : ""}
title={`${g.type || ""} now=${g.now || ""}`}
>
{g.name} · {g.count}
{g.now ? ` → ${g.now}` : ""}
</Chip>
))}
</div>
</div>
<div class="card table-wrap">
<table class="data">
<thead>
<tr>
<th>жив</th>
<th>Название</th>
<th>Тип</th>
<th>Задержка</th>
<th>Оценка приоритета</th>
<th>Пул регистрации</th>
<th>Группа</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
{!shownLeaves.length ? (
<tr>
<td colspan="8" class="hint">
Нет узлов под текущим фильтром
</td>
</tr>
) : (
shownLeaves.map((n) => {
const hb = healthBadge(n.health || "unknown");
const groups = (n.groups || []).slice(0, 4).join(", ");
return (
<tr key={n.name}>
<td>
<span class={`badge ${hb.cls === "danger" ? "fail" : hb.cls === "ok" ? "ok" : "unknown"}`}>
{hb.label}
</span>
</td>
<td>{n.name}</td>
<td>{n.type || ""}</td>
<td>
{n.last_delay_ms != null ? `${n.last_delay_ms}ms` : "—"}
</td>
<td>
{n.priority_score != null ? n.priority_score : "—"}
</td>
<td>
{n.in_register_pool ? (
<span class="badge pool">Пул регистрации</span>
) : (
"—"
)}
</td>
<td class="hint">{groups}</td>
<td class="ops">
<Button
variant="ghost"
size="sm"
onClick={() => clashTestOne(n.name)}
>
Проверка
</Button>
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
<LogDetails text={clashResult} summary="Детали ответа Clash" compact />
</>
);
}
@@ -0,0 +1,76 @@
// Clash leaf filtering / pool-name resolution + the NodesTab select options.
// Moved verbatim from NodesTab.jsx — behavior unchanged.
export function filterClashLeaves(leaves, mode, q) {
let out = leaves || [];
if (mode === "pool") out = out.filter((n) => n.in_register_pool);
else if (mode === "ok") out = out.filter((n) => n.health === "ok");
else if (mode === "fail") out = out.filter((n) => n.health === "fail");
const qq = (q || "").trim().toLowerCase();
if (qq) out = out.filter((n) => (n.name || "").toLowerCase().includes(qq));
return out.slice().sort((a, b) => {
const pa = a.in_register_pool ? 0 : 1;
const pb = b.in_register_pool ? 0 : 1;
if (pa !== pb) return pa - pb;
const rank = { ok: 0, unknown: 1, fail: 2 };
const ha = rank[a.health || "unknown"] ?? 1;
const hb = rank[b.health || "unknown"] ?? 1;
if (ha !== hb) return ha - hb;
const da = a.last_delay_ms != null ? a.last_delay_ms : 1e9;
const db = b.last_delay_ms != null ? b.last_delay_ms : 1e9;
return da - db;
});
}
export function namesInPool(listing, groupName, limit = 120) {
const g = (groupName || "").trim();
const leaves = (listing && listing.leaves) || [];
let names = leaves
.filter((x) => Array.isArray(x.groups) && x.groups.includes(g))
.map((x) => x.name);
// fallback: register-pool flag when group is a known register group
if (!names.length && (g.includes("Grok") || g.includes("GROK") || g === "PROXY")) {
names = leaves.filter((x) => x.in_register_pool).map((x) => x.name);
}
return names.slice(0, Math.max(1, limit));
}
export const CLASH_FILTER = [
{ value: "pool", label: "только пул регистрации" },
{ value: "all", label: "Все leaf-узлы" },
{ value: "ok", label: "только доступные" },
{ value: "fail", label: "только ошибки" },
];
// Must match apps.control_api.nodes_ops.IMPORTABLE_GROUPS (register-relevant first).
export const IMPORT_POOL_OPTS = [
{ value: "🎯Grok-регистрация", label: "🎯Grok-регистрация · основной пул (рекомендуется)" },
{ value: "♻️Grok-избранное", label: "♻️Grok-избранное" },
{ value: "PROXY", label: "PROXY" },
{ value: "🔰ChatGPT", label: "🔰ChatGPT" },
{ value: "GROK-REG", label: "GROK-REG · изолированная группа доменов" },
];
export const IMPORT_MODE_OPTS = [
{ value: "merge", label: "merge · добавление/перезапись по имени" },
{ value: "replace_prefix", label: "replace_prefix · замена по префиксу" },
];
export const HEALTH_OPTS = [
{ value: "", label: "Все" },
{ value: "ok", label: "доступен" },
{ value: "fail", label: "Ошибка" },
{ value: "unknown", label: "не проверен" },
];
export const TIER_OPTS = [
{ value: "", label: "Все" },
{ value: "0", label: "Дата-центр 0" },
{ value: "1", label: "Резидентные 1" },
];
export const PAGE_SIZES = [
{ value: "25", label: "25" },
{ value: "50", label: "50" },
{ value: "100", label: "100" },
];
@@ -0,0 +1,51 @@
import { describe, it, expect } from "vitest";
import { filterClashLeaves, namesInPool } from "./clashFilters.js";
const LEAVES = [
{ name: "hk-1", health: "fail", in_register_pool: true, last_delay_ms: 100, groups: ["🎯Grok-регистрация"] },
{ name: "us-2", health: "ok", in_register_pool: true, last_delay_ms: 300, groups: ["🎯Grok-регистрация"] },
{ name: "jp-3", health: "ok", in_register_pool: false, last_delay_ms: 50, groups: ["PROXY"] },
{ name: "sg-4", health: "unknown", in_register_pool: true, last_delay_ms: null, groups: [] },
];
describe("filterClashLeaves", () => {
it("pool mode keeps only register-pool leaves", () => {
expect(filterClashLeaves(LEAVES, "pool", "").map((n) => n.name)).toEqual([
"us-2",
"sg-4",
"hk-1",
]);
});
it("sorts pool-first, then ok > unknown > fail, then by delay", () => {
expect(filterClashLeaves(LEAVES, "all", "").map((n) => n.name)).toEqual([
"us-2",
"sg-4",
"hk-1",
"jp-3",
]);
});
it("query filters by case-insensitive substring", () => {
expect(filterClashLeaves(LEAVES, "all", "JP").map((n) => n.name)).toEqual(["jp-3"]);
});
it("does not mutate the input array", () => {
const before = LEAVES.map((n) => n.name);
filterClashLeaves(LEAVES, "all", "");
expect(LEAVES.map((n) => n.name)).toEqual(before);
});
});
describe("namesInPool", () => {
it("matches by group membership", () => {
expect(namesInPool({ leaves: LEAVES }, "PROXY")).toEqual(["jp-3"]);
});
it("falls back to in_register_pool for known register groups", () => {
expect(namesInPool({ leaves: LEAVES }, "♻️Grok-избранное")).toEqual([
"hk-1",
"us-2",
"sg-4",
]);
});
it("honours the limit", () => {
expect(namesInPool({ leaves: LEAVES }, "♻️Grok-избранное", 2)).toHaveLength(2);
});
});
+305
View File
@@ -0,0 +1,305 @@
// src/pages/RunLogs/LogsPage.jsx
// Logs page: current-run status strip + path summary + which/tail/follow tail
// + supervisor history. Path is RunLogs/ because root .gitignore has logs/.
// Hash route remains #/logs.
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import * as api from "../../api/client.js";
import { auth401 } from "../../lib/http.js";
import {
currentRunState,
overviewState,
lastProductOk,
} from "../../store/run.js";
import { showOpsFeedback } from "../../store/feedback.js";
import { StatusDot, Chip, Button, Select, PageHeader } from "../../ui/index.js";
import { runHeader } from "../Register/progressRender.jsx";
import { formatApiError } from "../../lib/format.js";
import "../../styles/run.css";
import "../../styles/logs.css";
const WHICH_OPTS = [
{ value: "auto", label: "auto" },
{ value: "worker", label: "worker" },
{ value: "supervisor", label: "supervisor" },
{ value: "both", label: "both" },
];
const TAIL_OPTS = [
{ value: "100", label: "100" },
{ value: "200", label: "200" },
{ value: "500", label: "500" },
];
function pathSummary(run) {
const parts = [];
if (run && run.worker_log) parts.push(`worker: ${run.worker_log}`);
if (run && run.supervisor_log) parts.push(`supervisor: ${run.supervisor_log}`);
return parts.length ? parts.join(" · ") : "path: —";
}
function historyItems(data) {
const runs = Array.isArray(data?.runs) ? data.runs : [];
return runs.slice(0, 12).map((r) => {
const d = new Date((r.mtime || 0) * 1000);
const iso = Number.isNaN(d.getTime())
? "—"
: d.toISOString().replace("T", " ").slice(0, 19);
return { iso, name: r.name || "" };
});
}
export function LogsPage() {
const [which, setWhich] = useState("auto");
const [tail, setTail] = useState("200");
const [follow, setFollow] = useState(true);
const [logText, setLogText] = useState("");
const [logPath, setLogPath] = useState("");
const [history, setHistory] = useState(null); // null=loading | [] | items
const [historyOpen, setHistoryOpen] = useState(true);
const [historyErr, setHistoryErr] = useState("");
const [busy, setBusy] = useState(false);
const preRef = useRef(null);
const whichRef = useRef(which);
const tailRef = useRef(tail);
whichRef.current = which;
tailRef.current = tail;
const refreshStatus = useCallback(async () => {
try {
const [cur, ov] = await Promise.all([api.currentRun(), api.overview()]);
const run = cur?.run ?? cur ?? null;
currentRunState.value = run;
if (ov) {
overviewState.value = ov;
if (ov.product_ok != null) lastProductOk.value = ov.product_ok;
}
return run;
} catch (e) {
if (auth401(e)) return null;
throw e;
}
}, []);
const refreshLogs = useCallback(async () => {
try {
const logs = await api.runLogs(
Number(tailRef.current) || 200,
whichRef.current || "auto",
);
setLogPath(logs.path ? `path: ${logs.path}` : "");
setLogText(logs.text || "");
// stick to bottom like legacy
requestAnimationFrame(() => {
const el = preRef.current;
if (el) el.scrollTop = el.scrollHeight;
});
} catch (e) {
if (auth401(e)) return;
setLogText(String(e.message || e));
}
}, []);
const refreshHistory = useCallback(async () => {
setHistoryErr("");
try {
const data = await api.listRuns();
setHistory(historyItems(data));
} catch (e) {
if (auth401(e)) return;
setHistory([]);
setHistoryErr(String(e.message || e));
}
}, []);
const refreshAll = useCallback(
async ({ explicit = false } = {}) => {
if (explicit) setBusy(true);
try {
const run = await refreshStatus();
await refreshLogs();
if (historyOpen) await refreshHistory();
if (explicit) {
const phase = (run && (run.phase_title || run.phase)) || "—";
const alive = !!(run && run.alive);
const sub = run && run.sub != null ? ` sub=${run.sub}` : "";
const complete =
run && run.complete != null ? ` complete=${run.complete}` : "";
const worker =
run && run.worker_log
? ` · worker=${String(run.worker_log).split(/[\\/]/).pop()}`
: "";
showOpsFeedback(
`Обновлено · ${alive ? "выполняется" : "ожидание"} · ${phase}${sub}${complete}${worker}`,
"ok",
{ toast: true, sticky: true },
);
}
} catch (e) {
if (auth401(e)) return;
if (explicit) showOpsFeedback(formatApiError(e), "err");
} finally {
if (explicit) setBusy(false);
}
},
[refreshStatus, refreshLogs, refreshHistory, historyOpen],
);
// Mount: load status + logs + history; follow poll every 4s while checked.
useEffect(() => {
let cancelled = false;
(async () => {
if (cancelled) return;
await refreshAll({ explicit: false });
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!follow) return undefined;
const id = setInterval(() => {
refreshStatus().catch(() => {});
refreshLogs().catch(() => {});
}, 4000);
return () => clearInterval(id);
}, [follow, refreshStatus, refreshLogs]);
// which/tail change → immediate re-fetch
useEffect(() => {
refreshLogs();
}, [which, tail, refreshLogs]);
// history opens → load
useEffect(() => {
if (historyOpen) refreshHistory();
}, [historyOpen, refreshHistory]);
const run = currentRunState.value;
const head = runHeader(run);
// Logs summary chips lean: pid / tag / mode / stuck (legacy)
const meta = (run && run.meta) || {};
const tag = (run && run.tag) || meta.tag;
const logChips = [];
if (run && run.pid != null) logChips.push({ label: `pid=${run.pid}` });
if (tag) logChips.push({ label: `tag=${tag}` });
if (run && run.mode) logChips.push({ label: String(run.mode) });
if (run && run.stuck) logChips.push({ label: "stuck", danger: true });
const chips = logChips.length ? logChips : head.chips;
return (
<section class="page page-logs">
<PageHeader
title="Логи"
toolbarClass="toolbar wrap"
hint={
<>
tail worker / supervisor текущего run, сводка путей и история supervisor. Запуск и прогресс — во вкладке «Регистрация».
</>
}
>
<Button
variant="ghost"
busy={busy}
onClick={() => refreshAll({ explicit: true })}
>
Обновить
</Button>
<Button
variant="ghost"
onClick={() => {
location.hash = "#/register";
}}
>
← Регистрация
</Button>
<label class="inline check">
<input
type="checkbox"
checked={follow}
onChange={(e) => setFollow(!!e.currentTarget.checked)}
/>{" "}
Авто-обновление
</label>
</PageHeader>
<div
class={`run-header run-header-${head.state}`}
data-state={head.state}
id="logs-summary"
>
<StatusDot kind={head.dotKind} />
<span class="status-word">{head.word}</span>
<span class="meta-chips">
{chips.map((c, i) => (
<Chip
key={i}
kind={c.danger ? "err" : "default"}
class="mini"
title={c.title}
>
{c.label}
</Chip>
))}
</span>
</div>
<div class="logs-paths hint mono">{pathSummary(run)}</div>
<div class="panel logs-log-panel">
<div class="log-toolbar">
<h2>Текущий tail</h2>
<label class="inline">
Источник{" "}
<Select
value={which}
options={WHICH_OPTS}
onChange={(v) => setWhich(v)}
/>
</label>
<label class="inline">
Строк{" "}
<Select
value={tail}
options={TAIL_OPTS}
onChange={(v) => setTail(v)}
/>
</label>
<span class="hint mono log-path-inline">{logPath}</span>
</div>
<pre ref={preRef} class="log logs-log mono">
{logText}
</pre>
</div>
<details
class="card run-history-wrap"
open={historyOpen}
onToggle={(e) => setHistoryOpen(e.currentTarget.open)}
>
<summary>Последняя история supervisor</summary>
<div class="run-history">
{historyErr ? (
<span class="hint">Ошибка загрузки: {historyErr}</span>
) : history == null ? (
<span class="hint">Загрузка…</span>
) : history.length === 0 ? (
<span class="hint">Исторических логов supervisor пока нет.</span>
) : (
<ul class="run-history-list">
{history.map((h, i) => (
<li key={i}>
<span class="mono hint">{h.iso}</span>
{" · "}
<span class="mono">{h.name}</span>
</li>
))}
</ul>
)}
</div>
</details>
</section>
);
}
@@ -0,0 +1,424 @@
// Settings — pipeline email providers + proxy/turnstile/cpa + bearer + ops.
// Per-provider secrets/domains live only on Resources → Почта.
import { useEffect, useState } from "preact/hooks";
import * as api from "../../api/client.js";
import { getToken, setToken } from "../../api/client.js";
import { showOpsFeedback } from "../../store/feedback.js";
import { Button, PageHeader, LogDetails, ProviderPoolStatus } from "../../ui/index.js";
import { formatApiError } from "../../lib/format.js";
import { pretty, auth401 } from "../../lib/http.js";
import { useConfigForm } from "../../lib/useConfigForm.js";
import {
EMAIL_PROVIDERS,
EMAIL_PROVIDER_STRATEGIES,
normalizeProvidersList,
} from "../../lib/providers.js";
import "../../styles/settings.css";
const EMPTY = {
email_providers: [],
email_provider_strategy: "round_robin",
proxy: "",
proxy_rotate_mode: "",
proxy_list: "",
turnstile_stuck_timeout: "",
cpa_probe_chat: "",
cpa_remote_inject: "",
};
export function SettingsPage() {
// Residual singleton primary (not editable here). Shown when multi is empty.
const [primaryProvider, setPrimaryProvider] = useState("");
const [token, setTokenLocal] = useState(getToken());
const [result, setResult] = useState("");
const cfg = useConfigForm({
empty: EMPTY,
// Snapshot of last successful load — used to detect intentional clearable wipes.
initialBaseline: { email_providers: [], proxy_list: "" },
loadRequest: async () => {
const data = await api.getConfig();
return data.config || {};
},
hydrate: (c) => {
const next = { ...EMPTY };
// Multi-list only — do NOT fall back to singleton email_provider.
// Empty multi means intentional single-channel mode; reloading must keep
// chips empty so a clear+reload+save cannot re-open the pool.
next.email_providers = normalizeProvidersList(c.email_providers);
const strat = String(c.email_provider_strategy || "round_robin").trim().toLowerCase();
next.email_provider_strategy = EMAIL_PROVIDER_STRATEGIES.includes(strat)
? strat
: "round_robin";
for (const k of Object.keys(EMPTY)) {
if (k === "email_providers" || k === "email_provider_strategy") continue;
if (c[k] == null) continue;
if (k === "cpa_probe_chat" || k === "cpa_remote_inject") {
if (c[k] === true) next[k] = "true";
else if (c[k] === false) next[k] = "false";
else next[k] = String(c[k]);
} else if (k === "proxy_list") {
next[k] = Array.isArray(c[k]) ? c[k].join("\n") : String(c[k]);
} else {
next[k] = String(c[k]);
}
}
return {
form: next,
baseline: {
email_providers: next.email_providers.slice(),
proxy_list: String(next.proxy_list || ""),
},
};
},
onLoaded: (c, next) => {
const primary = String(c.email_provider || "").trim().toLowerCase();
setPrimaryProvider(primary);
setResult(
pretty({
loaded: true,
email_providers: next.email_providers,
email_provider: primary || null,
email_provider_strategy: next.email_provider_strategy,
}),
);
},
onLoadError: (e) => {
setResult(String(e.message || e));
showOpsFeedback(`Ошибка загрузки настроек: ${formatApiError(e)}`, "err");
},
confirmReload: {
message: "Есть несохранённые изменения настроек. Отменить и перезагрузить?",
onCancel: () =>
showOpsFeedback("Reload отменён", "info", { toast: true, sticky: false }),
},
onSaveBlocked: () =>
showOpsFeedback("Сначала загрузите конфиг, потом сохраняйте (пустая форма очистит пул мультивыбора)", "err", {
toast: true,
sticky: true,
}),
confirmClear: (f, baseline) => {
const providers = normalizeProvidersList(f.email_providers);
const proxyListNow = String(f.proxy_list || "");
const clearing = [];
if (!providers.length && baseline.email_providers.length) {
clearing.push("email_providers (мультивыбор пула)");
}
if (!proxyListNow.trim() && String(baseline.proxy_list || "").trim()) {
clearing.push("proxy_list / PROXY_LIST");
}
if (!clearing.length) return null;
return {
message: `Очистить следующие clearable-поля?\n\n· ${clearing.join("\n· ")}\n\nЗапишет пустые значения в config и .env.`,
};
},
onSaveCancelled: () =>
showOpsFeedback("Сохранение отменено", "info", { toast: true, sticky: false }),
saveRequest: (f) => {
const providers = normalizeProvidersList(f.email_providers);
// Settings is allowed to clear the multi-select pool (→ single email_provider).
const partial = {
email_providers: providers,
email_provider_strategy: f.email_provider_strategy || "round_robin",
};
if (providers.length) {
partial.email_provider = providers[0];
}
for (const [k, raw] of Object.entries(f)) {
if (k === "email_providers" || k === "email_provider_strategy") continue;
let v = raw;
if (k === "cpa_probe_chat" || k === "cpa_remote_inject") {
if (v === "") continue;
if (v === "true") v = true;
else if (v === "false") v = false;
partial[k] = v;
continue;
}
if (k === "turnstile_stuck_timeout") {
if (v === "") continue;
partial[k] = Number(v);
continue;
}
if (v === "" && k !== "proxy_list") continue;
partial[k] = v;
}
return api.putConfig({ config: partial });
},
onSaved: (data, f) => {
const providers = normalizeProvidersList(f.email_providers);
const proxyListNow = String(f.proxy_list || "");
const strategy = f.email_provider_strategy || "round_robin";
setResult(pretty(data));
const saved = data.config || {};
const savedPrimary = String(saved.email_provider || primaryProvider || "").trim();
if (savedPrimary) setPrimaryProvider(savedPrimary.toLowerCase());
const savedMulti = Array.isArray(saved.email_providers)
? normalizeProvidersList(saved.email_providers)
: providers;
const savedProxyList =
saved.proxy_list != null
? Array.isArray(saved.proxy_list)
? saved.proxy_list.join("\n")
: String(saved.proxy_list)
: proxyListNow;
showOpsFeedback(
providers.length
? `Настройки сохранены · providers=${providers.join(",")} · strategy=${strategy}`
: `Настройки сохранены · multi=∅ · одиночный канал=${savedPrimary || primaryProvider || "—"} · strategy=${strategy}`,
"ok",
);
return {
form: (p) => ({
...p,
// Prefer server multi-list; empty server list after clear stays empty
// (do not fall back to singleton — Settings owns clearable pool).
email_providers: savedMulti,
email_provider_strategy:
String(saved.email_provider_strategy || p.email_provider_strategy || "round_robin")
.trim()
.toLowerCase() || "round_robin",
proxy_list: savedProxyList,
}),
baseline: {
email_providers: savedMulti.slice(),
proxy_list: savedProxyList,
},
};
},
onSaveError: (e) => {
setResult(String(e.message || e));
showOpsFeedback(`Ошибка сохранения: ${formatApiError(e)}`, "err");
},
});
const { form, set, hydrated, dirty, load, busyIs, setBusy } = cfg;
useEffect(() => {
load();
// initial mount only — load identity changes with dirty; do not re-fetch.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
function toggleProvider(name) {
const cur = new Set(form.email_providers || []);
if (cur.has(name)) cur.delete(name);
else cur.add(name);
set({ email_providers: EMAIL_PROVIDERS.filter((p) => cur.has(p)) });
}
function save(ev) {
if (ev) ev.preventDefault();
return cfg.save();
}
function saveBearer() {
setToken(token.trim());
showOpsFeedback(
token.trim() ? "Bearer записан в sessionStorage" : "Bearer очищен",
"ok",
{ toast: true, sticky: false },
);
}
async function runSelfcheck() {
setBusy("selfcheck");
try {
const data = await api.selfcheck();
setResult(pretty(data));
showOpsFeedback("Self-check завершён", "ok");
} catch (e) {
if (auth401(e)) return;
setResult(String(e.message || e));
showOpsFeedback(`Ошибка self-check: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
async function runCleanup() {
if (
!window.confirm(
"Очистить остатки после антибот-щита?\n\nУдалит orphan chromium / остаточные каталоги на этой машине (dry_run=false).",
)
) {
showOpsFeedback("Чистка отменена", "info", { toast: true, sticky: false });
return;
}
setBusy("cleanup");
try {
const data = await api.cleanupOrphans();
setResult(pretty(data));
showOpsFeedback("Чистка завершена", "ok");
} catch (e) {
if (auth401(e)) return;
setResult(String(e.message || e));
showOpsFeedback(`Ошибка чистки: ${formatApiError(e)}`, "err");
} finally {
setBusy("");
}
}
const selected = form.email_providers || [];
return (
<section class="page page-settings">
<PageHeader
title="Настройки"
hint={
<>
Здесь настраивается, какие почтовые Provider и стратегию опроса использует канал регистрации. Общий с страницей регистрации
<code> email_providers </code>
(два сохранения перекрывают друг друга). Ключи / домены / учётки каждого Provider — в
<a href="#/resources">Ресурсы → Почта</a>
тонкая настройка.
</>
}
>
<Button
variant="ghost"
busy={busyIs("load")}
onClick={() => load({ force: true })}
>
Reload
</Button>
<Button
variant="primary"
busy={busyIs("save")}
disabled={!hydrated || busyIs("load")}
onClick={save}
title={!hydrated ? "Сначала загрузите конфиг" : undefined}
>
Save
</Button>
</PageHeader>
<form class="card grid settings-form" onSubmit={save}>
<div class="span2 provider-pipeline">
<div class="settings-section-title">Почтовый канал (доступные Provider)</div>
<ProviderPoolStatus
selected={selected}
primaryProvider={primaryProvider}
canClear
hydrated={hydrated}
dirty={dirty}
/>
<p class="hint tight">
Отмеченное пишется в <code>email_providers</code>; снятие всех отметок очищает пул, возврат к одиночному каналу{" "}
<code>email_provider</code>. Тонкая настройка → <a href="#/resources?tab=mail">Ресурсы · Почта</a>
</p>
<div class="mail-domain-chips provider-multi">
{EMAIL_PROVIDERS.map((p) => (
<label key={p} class="check chip">
<input
type="checkbox"
checked={selected.includes(p)}
onChange={() => toggleProvider(p)}
/>{" "}
{p}
</label>
))}
</div>
</div>
<label class="span2">
Стратегия опроса (email_provider_strategy)
<select
value={form.email_provider_strategy}
onChange={(e) => set({ email_provider_strategy: e.currentTarget.value })}
>
{EMAIL_PROVIDER_STRATEGIES.map((s) => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</label>
<div class="span2 settings-section-title">Прокси</div>
<label>
Одиночный прокси (proxy)
<input
value={form.proxy}
onInput={(e) => set({ proxy: e.currentTarget.value })}
/>
</label>
<label>
Режим ротации (proxy_rotate_mode)
<input
value={form.proxy_rotate_mode}
onInput={(e) => set({ proxy_rotate_mode: e.currentTarget.value })}
/>
</label>
<label class="span2">
Список прокси (proxy_list · по одному на строку)
<textarea
rows={3}
value={form.proxy_list}
onInput={(e) => set({ proxy_list: e.currentTarget.value })}
/>
</label>
<div class="span2 settings-section-title">Поведение регистрации</div>
<label>
Таймаут зависания Turnstile, сек (turnstile_stuck_timeout)
<input
type="number"
step="1"
value={form.turnstile_stuck_timeout}
onInput={(e) => set({ turnstile_stuck_timeout: e.currentTarget.value })}
/>
</label>
<label>
Chat-проба после регистрации (cpa_probe_chat)
<select
value={form.cpa_probe_chat}
onChange={(e) => set({ cpa_probe_chat: e.currentTarget.value })}
>
<option value="">(unchanged)</option>
<option value="false">false</option>
<option value="true">true</option>
</select>
</label>
<label>
Намерение удалённой инъекции (cpa_remote_inject)
<select
value={form.cpa_remote_inject}
onChange={(e) => set({ cpa_remote_inject: e.currentTarget.value })}
>
<option value="">(unchanged)</option>
<option value="false">false</option>
<option value="true">true</option>
</select>
</label>
</form>
<div class="card">
<h2>Bearer token скрипта (опционально)</h2>
<label class="inline">
API Token{" "}
<input
type="password"
value={token}
placeholder="optional bearer"
autocomplete="off"
onInput={(e) => setTokenLocal(e.currentTarget.value)}
/>
</label>
<Button variant="ghost" onClick={saveBearer}>
Save token
</Button>
</div>
<div class="card">
<h2>Операционный self-check</h2>
<div class="toolbar wrap">
<Button variant="ghost" busy={busyIs("selfcheck")} onClick={runSelfcheck}>
Запустить self-check
</Button>
<Button variant="ghost" busy={busyIs("cleanup")} onClick={runCleanup}>
Очистить остатки после щита
</Button>
</div>
<LogDetails text={result} summary="Детали ответа self-check / чистки" />
</div>
</section>
);
}
@@ -0,0 +1,123 @@
// Regression tests locking SettingsPage's config-form invariants.
// Written BEFORE the useConfigForm extraction — these must stay green after it.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, waitFor, fireEvent } from "@testing-library/preact";
vi.mock("../../api/client.js", () => ({
getConfig: vi.fn(),
putConfig: vi.fn(),
selfcheck: vi.fn(),
cleanupOrphans: vi.fn(),
getToken: vi.fn(() => ""),
setToken: vi.fn(),
}));
import * as api from "../../api/client.js";
import { session } from "../../store/session.js";
import { SettingsPage } from "./SettingsPage.jsx";
const LOADED = {
config: {
email_providers: ["hotmail", "gmail"],
email_provider: "hotmail",
email_provider_strategy: "round_robin",
proxy: "http://p:1",
proxy_list: "http://a:1\nhttp://b:2",
},
};
function btn(name) {
return screen.getByRole("button", { name });
}
beforeEach(() => {
vi.clearAllMocks();
session.value = { authenticated: true, checked: true };
vi.spyOn(window, "confirm").mockReturnValue(true);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("SettingsPage config-form invariants", () => {
it("1. GET failure leaves Save disabled and sends no PUT", async () => {
api.getConfig.mockRejectedValue(new Error("boom"));
render(<SettingsPage />);
await waitFor(() => expect(btn("Save").disabled).toBe(true));
fireEvent.click(btn("Save"));
await waitFor(() => expect(api.putConfig).not.toHaveBeenCalled());
});
it("2. GET 401 clears the session and leaves Save disabled", async () => {
const e = new Error("unauthorized");
e.status = 401;
api.getConfig.mockRejectedValue(e);
render(<SettingsPage />);
await waitFor(() => expect(session.value.authenticated).toBe(false));
expect(btn("Save").disabled).toBe(true);
});
it("3. Reload while dirty prompts, and cancelling sends no second GET", async () => {
api.getConfig.mockResolvedValue(LOADED);
render(<SettingsPage />);
await waitFor(() => expect(btn("Save").disabled).toBe(false));
expect(api.getConfig).toHaveBeenCalledTimes(1);
// Make the form dirty.
fireEvent.input(screen.getByLabelText(/Одиночный прокси/), {
target: { value: "http://changed:9" },
});
await screen.findByText("не сохранено");
window.confirm.mockReturnValue(false);
fireEvent.click(btn("Reload"));
await waitFor(() => expect(window.confirm).toHaveBeenCalled());
expect(api.getConfig).toHaveBeenCalledTimes(1);
});
it("4. clearing a clearable field prompts on Save; cancelling sends no PUT", async () => {
api.getConfig.mockResolvedValue(LOADED);
render(<SettingsPage />);
await waitFor(() => expect(btn("Save").disabled).toBe(false));
// Untick every provider chip -> clears the multi pool.
for (const p of ["hotmail", "gmail"]) {
fireEvent.click(screen.getByLabelText(p));
}
window.confirm.mockReturnValue(false);
fireEvent.click(btn("Save"));
await waitFor(() => expect(window.confirm).toHaveBeenCalled());
expect(window.confirm.mock.calls[0][0]).toContain("email_providers");
expect(api.putConfig).not.toHaveBeenCalled();
});
it("5. successful Save clears dirty and rehydrates proxy_list from the server response", async () => {
api.getConfig.mockResolvedValue(LOADED);
api.putConfig.mockResolvedValue({
config: { ...LOADED.config, proxy_list: ["http://server-said:7"] },
});
render(<SettingsPage />);
await waitFor(() => expect(btn("Save").disabled).toBe(false));
fireEvent.input(screen.getByLabelText(/proxy_list/), {
target: { value: "http://changed:9" },
});
await screen.findByText("не сохранено");
fireEvent.click(btn("Save"));
await waitFor(() => expect(api.putConfig).toHaveBeenCalledTimes(1));
expect(api.putConfig.mock.calls[0][0].config.proxy_list).toBe(
"http://changed:9",
);
await waitFor(() =>
expect(screen.queryByText("не сохранено")).toBeNull(),
);
// Server multi-list / proxy_list win over the local edit after save.
expect(screen.getByLabelText(/proxy_list/).value).toBe(
"http://server-said:7",
);
});
});
+40
View File
@@ -0,0 +1,40 @@
// src/store/feedback.js
import { signal } from "@preact/signals";
const OPS_LOG_MAX = 40;
export const opsLog = signal([]);
export const stickyBanner = signal(null); // { message, kind } | null
export const toasts = signal([]); // { id, message, kind }[]
let toastSeq = 0;
export function pushOpsLog(message, kind = "info") {
const t = new Date().toTimeString().slice(0, 8);
const next = [{ t, kind, m: String(message || "") }, ...opsLog.value];
if (next.length > OPS_LOG_MAX) next.length = OPS_LOG_MAX;
opsLog.value = next;
}
export function showOpsFeedback(
message,
kind = "info",
{ toast = true, sticky = true, log = true } = {},
) {
const text = String(message || "").trim() || "(нет сообщения)";
if (sticky) stickyBanner.value = { message: text, kind };
if (log) pushOpsLog(text, kind);
if (!toast) return;
const id = ++toastSeq;
toasts.value = [
...toasts.value,
{ id, message: text.length > 220 ? text.slice(0, 217) + "…" : text, kind },
];
const ms = kind === "err" ? 6500 : 3200;
setTimeout(() => {
toasts.value = toasts.value.filter((x) => x.id !== id);
}, ms);
}
export function clearStickyBanner() {
stickyBanner.value = null;
}
+12
View File
@@ -0,0 +1,12 @@
// src/store/run.js
// Live run + overview state, polled every 4s by the Register page.
// regFormDirty guards form edits from being wiped by background config reloads.
import { signal } from "@preact/signals";
export const currentRunState = signal(null); // run object | null
export const overviewState = signal(null);
export const regFormDirty = signal(false); // true → poll must not overwrite form fields
export const regFormLoaded = signal(false); // first successful config load happened?
// last known disk product_ok (survives transient overview fetch failures)
export const lastProductOk = signal(null);
+11
View File
@@ -0,0 +1,11 @@
// src/store/session.js
import { signal } from "@preact/signals";
export const session = signal({
authenticated: false,
username: null,
auth_required: true,
password_login_enabled: true,
users_configured: false,
checked: false,
});
+105
View File
@@ -0,0 +1,105 @@
/* Accounts page */
.page-accounts .filter-bar {
display: flex;
flex-wrap: wrap;
gap: 0.55rem 0.75rem;
align-items: center;
margin-bottom: var(--space-3);
}
.page-accounts label.inline {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: var(--muted);
font-size: 0.85rem;
}
.page-accounts label.inline input[type="search"],
.page-accounts label.inline input[type="text"] {
min-width: 10rem;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 7px;
color: var(--text);
padding: 0.3rem 0.5rem;
font: inherit;
}
.page-accounts .acc-summary {
margin-bottom: var(--space-3);
}
.table-wrap {
overflow: auto;
}
table.data {
width: 100%;
border-collapse: collapse;
font-size: 0.84rem;
}
table.data th,
table.data td {
border-bottom: 1px solid var(--border);
padding: 0.45rem 0.5rem;
text-align: left;
vertical-align: top;
}
table.data th {
color: var(--muted);
font-weight: 600;
font-size: 0.78rem;
position: sticky;
top: 0;
background: var(--panel);
z-index: 1;
}
table.data tbody tr:hover td {
background: rgba(255, 255, 255, 0.03);
}
table.data td.mono,
table.data .mono {
font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
font-variant-numeric: tabular-nums;
}
table.data td.ops {
white-space: nowrap;
}
.badge {
display: inline-block;
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.08rem 0.45rem;
font-size: 0.74rem;
}
.badge.ok {
color: var(--ok);
border-color: rgba(91, 212, 154, 0.45);
}
.badge.fail {
color: var(--danger);
border-color: rgba(212, 91, 91, 0.45);
}
.err-text {
color: var(--danger);
}
@media (max-width: 640px) {
.page-accounts label.inline input[type="search"] {
min-width: 8rem;
}
table.data {
font-size: 0.78rem;
}
}
+223
View File
@@ -0,0 +1,223 @@
* { box-sizing: border-box; }
html, body { margin: 0; min-height: 100%; background: var(--bg); color: var(--text); font-family: var(--font); }
.hidden { display: none !important; }
.hint { color: var(--muted); font-size: 0.9rem; }
.muted { color: var(--muted); }
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
/* ── App shell ─────────────────────────────────────────── */
.app-shell {
display: grid;
grid-template-columns: var(--sidebar-w) 1fr;
min-height: 100vh;
}
.sidebar {
background: var(--sidebar);
border-right: 1px solid var(--border);
position: sticky;
top: 0;
height: 100vh;
display: flex;
flex-direction: column;
padding: var(--space-4) var(--space-3);
grid-column: 1;
grid-row: 1;
}
.side-brand {
display: flex;
gap: 0.7rem;
align-items: center;
padding: 0.35rem 0.5rem var(--space-4);
}
.logo-dot {
width: 34px;
height: 34px;
border-radius: 10px;
background: linear-gradient(135deg, #5b9fd4, #3d7eb0 55%, #5bd49a);
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.08), 0 8px 20px rgba(91, 159, 212, 0.25);
}
.side-title {
font-weight: 700;
letter-spacing: 0.02em;
font-size: 0.98rem;
}
.side-link {
font-size: 0.75rem;
color: var(--muted);
}
.side-nav {
display: flex;
flex-direction: column;
gap: 0.3rem;
flex: 1;
}
.nav-item {
display: flex;
align-items: center;
gap: 0.55rem;
width: 100%;
text-align: left;
background: transparent;
color: var(--muted);
border: 1px solid transparent;
border-radius: 8px;
padding: 0.55rem 0.7rem;
cursor: pointer;
font: inherit;
text-decoration: none;
}
.nav-item:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.03);
text-decoration: none;
}
.nav-item.active {
color: var(--text);
background: rgba(91, 159, 212, 0.12);
border-color: rgba(91, 159, 212, 0.35);
}
.nav-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--border);
flex: 0 0 auto;
}
.nav-item.active .nav-dot {
background: var(--accent);
box-shadow: 0 0 0 3px rgba(91, 159, 212, 0.2);
}
.side-foot {
border-top: 1px solid var(--border);
padding-top: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.main-wrap {
min-width: 0;
padding: var(--space-4) 1.15rem var(--space-6);
/* Explicit placement so extra shell chrome (toggle/backdrop) cannot steal
grid tracks from sidebar + main — see button.nav-toggle note below. */
grid-column: 2;
grid-row: 1;
}
/* Higher specificity than .btn (components.css loads later and sets
display:inline-flex). Without this, nav-toggle stays in the 2-col grid as
cell (1,1), sidebar lands in the content column, and main-wrap is shoved
into a 220px-wide second row below the fold — "only menu visible". */
button.nav-toggle { display: none; }
.nav-backdrop { display: none; }
/* ── Login gate ────────────────────────────────────────── */
.login-gate {
min-height: 100vh;
display: grid;
place-items: center;
padding: var(--space-5);
background:
radial-gradient(ellipse at 20% 10%, rgba(91, 159, 212, 0.12), transparent 50%),
radial-gradient(ellipse at 80% 90%, rgba(91, 212, 154, 0.06), transparent 45%),
var(--bg);
}
.login-card {
width: min(420px, 100%);
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: var(--space-5) 1.4rem 1.25rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
box-shadow: var(--shadow-card);
}
.login-card h1 { margin: 0; font-size: 1.25rem; }
.login-card .actions { display: flex; gap: 0.5rem; }
.login-card .error {
color: var(--danger);
min-height: 1.2em;
margin: 0;
font-size: 0.9rem;
}
.brand-line a { color: var(--accent); }
/* ── Page chrome ───────────────────────────────────────── */
.page { display: block; }
.page-head {
display: flex;
flex-wrap: wrap;
gap: 0.75rem 1rem;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 0.9rem;
}
.page-head h1 {
margin: 0 0 0.25rem;
font-size: 1.3rem;
}
/* ── Toolbar helpers ───────────────────────────────────── */
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
align-items: center;
}
.toolbar.wrap { flex-wrap: wrap; }
/* ── Responsive ────────────────────────────────────────── */
@media (max-width: 900px) {
/* Block layout: position:fixed chrome does not reserve tracks (unlike grid). */
.app-shell {
display: block;
min-height: 100vh;
}
button.nav-toggle {
display: inline-flex;
position: fixed;
top: var(--space-3);
left: var(--space-3);
z-index: 30;
}
.sidebar {
position: fixed;
inset: 0 auto 0 0;
width: min(280px, 86vw);
transform: translateX(-105%);
transition: transform 0.18s ease;
z-index: 40;
height: 100vh;
box-shadow: none;
grid-column: auto;
grid-row: auto;
}
.app-shell.nav-open .sidebar {
transform: translateX(0);
box-shadow: 12px 0 40px rgba(0, 0, 0, 0.45);
}
.nav-backdrop {
display: block;
position: fixed;
inset: 0;
border: 0;
padding: 0;
margin: 0;
background: rgba(4, 8, 14, 0.45);
z-index: 35;
cursor: pointer;
}
.main-wrap {
padding: calc(var(--space-6) + var(--space-4)) var(--space-3) var(--space-5);
grid-column: auto;
grid-row: auto;
}
.page-head { gap: 0.55rem; }
.kpi-grid { grid-template-columns: 1fr 1fr; }
}
@media (max-width: 480px) {
.kpi-grid { grid-template-columns: 1fr; }
.page-head h1 { font-size: 1.15rem; }
}
+383
View File
@@ -0,0 +1,383 @@
/* ── Buttons ───────────────────────────────────────────── */
.btn {
background: var(--panel-2);
color: var(--text);
border: 1px solid var(--border);
border-radius: 7px;
padding: 0.42rem 0.8rem;
cursor: pointer;
font: inherit;
font-size: 0.88rem;
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
.btn:hover { border-color: #3a4d68; }
.btn-primary {
background: linear-gradient(180deg, #5b9fd4, #3d7eb0);
border-color: #4a8fc4;
color: #fff;
font-weight: 600;
}
.btn-primary:hover { filter: brightness(1.05); }
.btn-ghost { background: transparent; }
.btn-danger { border-color: rgba(212, 91, 91, 0.55); color: #f0a0a0; }
.btn-sm { padding: 0.22rem 0.5rem; font-size: 0.78rem; }
.btn-md { padding: 0.42rem 0.8rem; font-size: 0.88rem; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.btn.busy { opacity: 0.72; cursor: wait; }
/* ── Card ──────────────────────────────────────────────── */
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 0.9rem 1rem;
margin-bottom: 0.85rem;
}
.card.ok { border-color: rgba(91, 212, 154, 0.35); }
.card.danger { border-color: rgba(212, 91, 91, 0.45); }
/* ── Field ─────────────────────────────────────────────── */
.field {
display: flex;
flex-direction: column;
gap: 0.28rem;
font-size: 0.82rem;
color: var(--muted);
}
.field-label { color: var(--muted); }
.field.span2 { grid-column: 1 / -1; }
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.65rem 0.75rem;
}
@media (max-width: 640px) {
.field-grid { grid-template-columns: 1fr; }
.field-grid .span2 { grid-column: auto; }
}
input, select, textarea, .select {
background: var(--bg);
border: 1px solid var(--border);
color: var(--text);
border-radius: 7px;
padding: 0.45rem 0.55rem;
font: inherit;
width: 100%;
}
input:focus, select:focus, textarea:focus, .select:focus {
outline: none;
border-color: var(--accent-2);
}
/* ── Tabs ──────────────────────────────────────────────── */
.tabrow {
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
}
.tabrow .tab {
background: var(--panel-2);
color: var(--text);
border: 1px solid var(--border);
border-radius: 7px;
padding: 0.42rem 0.8rem;
cursor: pointer;
font: inherit;
font-size: 0.88rem;
}
.tabrow .tab:hover { border-color: #3a4d68; }
.tabrow .tab.active {
border-color: var(--accent);
color: var(--accent);
}
/* ── StatusDot ─────────────────────────────────────────── */
.status-dot {
display: inline-block;
width: 0.55rem;
height: 0.55rem;
border-radius: 999px;
background: var(--muted);
flex: 0 0 auto;
}
.status-dot.status-ok { background: var(--ok); box-shadow: 0 0 0 3px rgba(91, 212, 154, 0.15); }
.status-dot.status-warn { background: var(--warn); }
.status-dot.status-err { background: var(--danger); }
.status-dot.status-busy { background: var(--accent); box-shadow: 0 0 0 3px rgba(91, 159, 212, 0.18); }
.status-dot.status-idle { background: var(--muted); }
/* ── Chip ──────────────────────────────────────────────── */
.chip {
display: inline-flex;
align-items: center;
gap: 0.3rem;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.22rem 0.65rem;
font-size: 0.78rem;
color: var(--muted);
}
.chip.chip-ok, .chip.chip-hot { color: var(--ok); border-color: rgba(91, 212, 154, 0.4); }
.chip.chip-warn { color: var(--warn); border-color: rgba(212, 177, 91, 0.4); }
.chip.chip-err, .chip.chip-danger { color: #f0a0a0; border-color: rgba(212, 91, 91, 0.4); }
.chip.chip-info { color: var(--accent); border-color: rgba(91, 159, 212, 0.45); }
.chip.chip-mini { font-size: 0.7rem; padding: 0.14rem 0.5rem; }
.chip-row { display: flex; flex-wrap: wrap; gap: 0.4rem; }
/* ── KPI ───────────────────────────────────────────────── */
.kpi-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.55rem;
}
.kpi-grid.compact .kpi { min-height: 3.25rem; padding: 0.4rem 0.55rem; }
.kpi-grid.compact .kpi .kpi-value { font-size: 1.05rem; }
.kpi {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 0.55rem 0.7rem;
min-height: 4.25rem;
display: flex;
flex-direction: column;
gap: 0.15rem;
}
.kpi .kpi-label, .kpi .label {
font-size: 0.72rem;
color: var(--muted);
letter-spacing: 0.02em;
text-transform: uppercase;
}
.kpi .kpi-value, .kpi .value {
font-size: 1.35rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
}
.kpi .kpi-hint, .kpi .sub { font-size: 0.75rem; color: var(--muted); }
.kpi.ok { border-color: rgba(91, 212, 154, 0.35); }
.kpi.warn { border-color: rgba(212, 177, 91, 0.4); }
.kpi.danger { border-color: rgba(212, 91, 91, 0.45); background: rgba(212, 91, 91, 0.06); }
/* ── Bar ───────────────────────────────────────────────── */
.bars { display: flex; flex-direction: column; gap: 0.45rem; }
.bar-row {
display: grid;
grid-template-columns: 4.5rem 1fr auto;
gap: 0.5rem;
align-items: center;
}
.bar-row .bar-label { color: var(--muted); font-size: 0.78rem; }
.bar-track {
height: 0.55rem;
border-radius: 999px;
background: rgba(255, 255, 255, 0.06);
overflow: hidden;
}
.bar-fill {
height: 100%;
border-radius: 999px;
background: linear-gradient(90deg, var(--accent-2), var(--ok));
transition: width 0.35s ease;
}
.bar-fill.bar-warn { background: linear-gradient(90deg, var(--warn), #d48a5b); }
.bar-fill.bar-danger, .bar-fill.bar-err { background: linear-gradient(90deg, #a04040, var(--danger)); }
.bar-row .bar-value, .bar-row .bar-caption {
font-size: 0.78rem;
color: var(--muted);
font-variant-numeric: tabular-nums;
min-width: 3.5rem;
text-align: right;
}
/* ── Ops feedback (toast + banner + log) ───────────────── */
.ops-toast-host {
position: fixed;
top: 0.85rem;
right: 0.85rem;
left: auto;
z-index: 9999;
display: flex;
flex-direction: column;
gap: 0.4rem;
max-width: min(28rem, calc(100vw - 1.5rem));
width: min(28rem, calc(100vw - 1.5rem));
pointer-events: none;
}
@media (max-width: 480px) {
.ops-toast-host {
top: 0.55rem;
right: 0.55rem;
left: 0.55rem;
max-width: none;
width: auto;
}
}
.ops-toast {
pointer-events: auto;
padding: 0.55rem 0.75rem;
border-radius: 8px;
border: 1px solid var(--border);
background: var(--panel);
color: var(--text);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
font-size: 0.86rem;
line-height: 1.4;
animation: ops-toast-in 0.18s ease-out;
}
.ops-toast.ok { border-color: rgba(91, 212, 154, 0.45); }
.ops-toast.err { border-color: rgba(212, 91, 91, 0.55); color: #f0c0c0; }
.ops-toast.info { border-color: rgba(91, 159, 212, 0.45); }
.ops-toast.warn { border-color: rgba(220, 180, 80, 0.55); color: #f0e0a8; }
@keyframes ops-toast-in {
from { opacity: 0; transform: translateY(-6px); }
to { opacity: 1; transform: translateY(0); }
}
.ops-feedback {
margin: 0 0 0.65rem;
padding: 0.55rem 0.75rem;
border-radius: 8px;
border: 1px solid var(--border);
background: rgba(91, 159, 212, 0.08);
color: var(--text);
font-size: 0.86rem;
line-height: 1.4;
white-space: pre-wrap;
word-break: break-word;
}
.ops-feedback.ok { border-color: rgba(91, 212, 154, 0.4); background: rgba(91, 212, 154, 0.08); }
.ops-feedback.err { border-color: rgba(212, 91, 91, 0.45); background: rgba(212, 91, 91, 0.08); color: #f0c0c0; }
.ops-feedback.info { border-color: rgba(91, 159, 212, 0.4); }
.ops-feedback.warn { border-color: rgba(220, 180, 80, 0.5); background: rgba(220, 180, 80, 0.08); color: #f0e0a8; }
.ops-log-wrap {
margin: 0 0 0.65rem;
padding: 0.35rem 0.65rem;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(0, 0, 0, 0.12);
font-size: 0.82rem;
}
.ops-log-wrap > summary {
cursor: pointer;
color: var(--muted);
user-select: none;
}
.ops-log {
list-style: none;
margin: 0.4rem 0 0;
padding: 0;
max-height: 9rem;
overflow: auto;
}
.ops-log li {
display: grid;
grid-template-columns: 4.6rem 3.2rem 1fr;
gap: 0.4rem;
padding: 0.22rem 0;
border-top: 1px solid rgba(255, 255, 255, 0.04);
line-height: 1.35;
}
.ops-log .t { color: var(--muted); font-variant-numeric: tabular-nums; }
.ops-log .k { font-weight: 600; text-transform: uppercase; font-size: 0.72rem; letter-spacing: 0.02em; }
.ops-log .k.ok { color: #7ad7a8; }
.ops-log .k.err { color: #e0a0a0; }
.ops-log .k.warn { color: #e0d08a; }
.ops-log .k.info { color: #8ab8e0; }
.ops-log .m { word-break: break-word; }
/* ── Drawer ────────────────────────────────────────────── */
.drawer-backdrop {
position: fixed;
inset: 0;
background: rgba(4, 8, 14, 0.6);
z-index: 60;
display: flex;
justify-content: flex-end;
align-items: stretch;
}
.drawer {
background: var(--panel);
border-left: 1px solid var(--border);
width: min(560px, 92vw);
height: 100%;
display: flex;
flex-direction: column;
box-shadow: -18px 0 50px rgba(0, 0, 0, 0.45);
}
.drawer-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--border);
}
.drawer-title { font-weight: 650; font-size: 0.95rem; }
.drawer-body {
flex: 1;
overflow: auto;
padding: 0.9rem 1rem;
}
/* LogDetails — collapsed raw-response evidence (batch-2 IA) */
.log-details > summary {
cursor: pointer;
color: var(--muted);
font-size: 0.78rem;
padding: 0.2rem 0;
user-select: none;
}
.log-details > summary:hover { color: var(--text); }
.log-details[open] > summary { margin-bottom: 0.35rem; }
/* ProviderPoolStatus — строка статуса пула email_providers (batch-2 IA) */
.pool-status {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.35rem;
margin: 0.25rem 0 0.35rem;
}
.pool-status .pool-status-label {
color: var(--muted);
font-size: 0.78rem;
}
.pool-status .pool-chip {
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.08rem 0.5rem;
font-size: 0.74rem;
font-family: var(--mono);
color: var(--text);
background: var(--panel-2);
}
.pool-status .pool-chip.empty {
font-family: var(--font);
color: var(--muted);
background: transparent;
}
.pool-status .pool-tag {
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 0.05rem 0.4rem;
font-size: 0.72rem;
color: var(--muted);
}
.pool-status .pool-tag.can-clear {
color: var(--ok);
border-color: rgba(91, 212, 154, 0.45);
}
.pool-status .pool-tag.warn {
color: var(--warn);
border-color: rgba(212, 177, 91, 0.45);
}
+105
View File
@@ -0,0 +1,105 @@
/* Logs page (RunLogs / #/logs) */
.page-logs .run-header {
margin-top: 0.25rem;
}
.logs-paths {
margin: 0.15rem 0 0.5rem;
word-break: break-all;
font-size: 0.78rem;
}
.logs-log-panel {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-top: 0.5rem;
min-height: 0;
}
.log-toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 0.75rem;
align-items: center;
position: static;
flex: 0 0 auto;
background: var(--panel);
padding: 0.35rem 0;
}
.log-toolbar h2 {
margin: 0;
font-size: 0.95rem;
margin-right: auto;
}
.log-path-inline {
font-size: 0.78rem;
}
.logs-log {
min-height: 22rem;
max-height: calc(100vh - 16rem);
flex: 1 1 auto;
overflow: auto;
}
.page-logs label.inline {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: var(--muted);
font-size: 0.85rem;
}
.page-logs label.inline.check {
color: var(--text);
cursor: pointer;
}
.page-logs label.inline select,
.page-logs label.inline .field-control,
.page-logs label.inline select {
min-width: 6.5rem;
}
.run-history-wrap {
margin-top: var(--space-3);
}
.run-history-wrap summary {
cursor: pointer;
color: var(--muted);
font-size: 0.9rem;
}
.run-history {
margin-top: 0.35rem;
}
.run-history-list {
list-style: none;
margin: 0.4rem 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.78rem;
}
.run-history-list li {
color: var(--muted);
}
.mono {
font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
}
@media (max-width: 640px) {
.logs-log {
min-height: 14rem;
max-height: 60vh;
}
}
+309
View File
@@ -0,0 +1,309 @@
/* Resources page (nodes / mail / import) */
.page-resources .card {
margin-top: var(--space-3);
}
.resources-tab {
display: flex;
flex-direction: column;
gap: var(--space-3);
margin-top: var(--space-3);
}
.actions-bar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 0.75rem;
align-items: center;
}
.actions-bar .grow {
flex: 1 1 16rem;
min-width: 12rem;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 7px;
color: var(--text);
padding: 0.35rem 0.55rem;
font: inherit;
}
/* .chip-row определён в components.css (загружается позже, все три объявления перекрываются,
фактический gap — 0.4rem из components.css, а не 0.35rem отсюда). */
.chip.hot {
color: var(--accent);
border-color: rgba(91, 159, 212, 0.5);
}
.badge.pool {
color: var(--accent);
border-color: rgba(91, 159, 212, 0.45);
}
.badge.unknown {
color: var(--muted);
}
.import-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: var(--space-3);
}
.import-grid .card {
margin-top: 0;
display: flex;
flex-direction: column;
gap: 0.55rem;
}
.import-grid h2,
.resources-tab h2 {
margin: 0 0 0.25rem;
font-size: 1rem;
}
.import-grid textarea,
.mail-tab textarea {
width: 100%;
min-height: 5rem;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
padding: 0.5rem 0.6rem;
font: inherit;
resize: vertical;
}
.mail-form.grid,
.nodes-tab .grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.65rem 0.85rem;
}
.mail-form label,
.nodes-tab .grid > label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.82rem;
color: var(--muted);
}
.mail-form input,
.nodes-tab .grid input,
.nodes-tab .grid select,
.resources-tab label.inline input,
.resources-tab label.inline select {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 7px;
color: var(--text);
padding: 0.35rem 0.5rem;
font: inherit;
}
.mail-form .span2,
.nodes-tab .grid .span2,
.nodes-tab .grid .actions {
grid-column: 1 / -1;
}
.nodes-tab .grid .actions {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
}
.mail-toolbar {
margin-bottom: 0;
}
.mail-probe-kpis {
display: flex;
flex-wrap: wrap;
gap: 0.65rem 1rem;
margin: 0.5rem 0 0.75rem;
font-size: 0.85rem;
color: var(--muted);
}
.mail-probe-kpis strong {
color: var(--text);
font-weight: 600;
}
.mail-domain-chips {
display: flex;
flex-wrap: wrap;
gap: 0.45rem 0.75rem;
align-items: center;
}
.mail-domain-chips .chip,
.provider-multi .chip {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.2rem 0.65rem;
cursor: pointer;
user-select: none;
}
.provider-panel {
margin-bottom: 0.75rem;
}
.provider-panel-summary {
list-style: none;
cursor: default;
}
.provider-panel-summary::-webkit-details-marker {
display: none;
}
.provider-panel-toggle {
background: transparent;
border: 0;
color: var(--text);
font: inherit;
font-weight: 600;
padding: 0;
cursor: pointer;
}
.provider-panel-body {
margin-top: 0.65rem;
}
.hint.tight {
margin: 0.25rem 0 0;
font-size: 0.8rem;
}
.hint.warn {
color: #e0a060;
}
.mail-probe-controls {
margin: 0.35rem 0 0.75rem;
gap: 0.55rem;
}
.mail-probe-results .table-wrap {
overflow: auto;
max-height: 28rem;
border: 1px solid var(--border);
border-radius: 8px;
}
.mail-probe-results table.data-table {
width: 100%;
border-collapse: collapse;
font-size: 0.85rem;
}
.mail-probe-results table.data-table th,
.mail-probe-results table.data-table td {
padding: 0.35rem 0.5rem;
border-bottom: 1px solid var(--border);
text-align: left;
vertical-align: top;
}
.mail-probe-results table.data-table th {
position: sticky;
top: 0;
background: var(--panel-2);
color: var(--muted);
font-weight: 600;
}
.mail-probe-results tr.dead td {
background: rgba(212, 91, 91, 0.06);
}
.mail-probe-results tr.soft td {
background: rgba(212, 180, 91, 0.07);
}
.mail-probe-results .badge.ok {
color: #7dcea0;
}
.mail-probe-results .badge.bad {
color: #f0a0a0;
}
.mail-probe-results .badge.soft {
color: #e0c070;
}
.mail-probe-results td.muted {
color: var(--muted);
max-width: 22rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.resources-tab label.check {
display: flex;
align-items: center;
gap: 0.4rem;
color: var(--text);
font-size: 0.86rem;
}
.resources-tab label.inline {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: var(--muted);
font-size: 0.85rem;
}
.card.muted {
color: var(--muted);
}
@media (max-width: 800px) {
.import-grid,
.mail-form.grid,
.nodes-tab .grid {
grid-template-columns: 1fr;
}
}
/* Разделы вкладки Mail (batch-2 IA): конфиг vs эксплуатация */
.mail-section-title {
margin: 1.1rem 0 0.4rem;
font-size: 0.95rem;
font-weight: 600;
color: var(--text);
border-bottom: 1px solid var(--border);
padding-bottom: 0.3rem;
}
.mail-section-title .hint {
font-weight: 400;
}
/* Глобальный defaultDomains (раньше по копии в панелях CF / CloudMail, теперь в одном месте) */
.mail-global-domains h2 {
margin-top: 0;
}
.mail-global-domains .mail-domains-input {
display: block;
margin-top: 0.6rem;
}
.mail-global-domains .mail-domains-input input {
width: 100%;
}
+376
View File
@@ -0,0 +1,376 @@
/* Стили только для RunProgress (B7 выделен из run.css).
Используется только компонентом RunProgress на странице регистрации; страница логов не зависит от этих классов
(.run-header / .status-word / .meta-chips / .chip.mini остаются в run.css). */
/* run progress */
.run-progress {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
/* Определения .kpi-grid / .kpi / .bars / .bar-row / .bar-track / .bar-fill полностью в
components.css (загружается позже, построчно перекрывает одноимённые правила этого файла), здесь не дублируем.
legacy-алиасы .kpi .label/.value/.sub также перекрыты components.css;
Группа голых алиасов .bar-fill.ok/.warn/.danger не генерируется компонентами (Bar.jsx и
RunProgress генерируют только bar-ok/bar-warn/bar-err), удалено вместе с ними.
.bar-fill.bar-ok хоть и генерируется, но его background с components.css
Базовый linear-gradient(90deg, var(--accent-2), var(--ok)) у .bar-fill
Побайтово идентично — components.css задаёт модификаторы только для warn / danger|err, ok — это базовый
состояние, поэтому это правило тоже мёртвое.
.bar-caption аналогично: `.bar-row .bar-caption` в components.css имеет более высокую специфичность,
построчно перекрыл одно-классовые версии этого файла (caption встречается только внутри .bar-row). */
.step-rail {
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.55rem;
padding: 0.25rem 0;
}
.step {
display: inline-flex;
align-items: center;
gap: 0.3rem;
font-size: 0.75rem;
color: var(--muted);
}
.step::before {
content: "";
width: 0.6rem;
height: 0.6rem;
border-radius: 999px;
border: 1px solid var(--muted);
background: transparent;
}
.step.done {
color: var(--ok);
}
.step.done::before {
background: var(--ok);
border-color: var(--ok);
}
.step.active {
color: var(--accent);
font-weight: 650;
}
.step.active::before {
background: var(--accent);
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(91, 159, 212, 0.2);
animation: step-pulse 1.4s ease-in-out infinite;
}
.step.pending {
color: var(--muted);
}
@keyframes step-pulse {
0%,
100% {
box-shadow: 0 0 0 3px rgba(91, 159, 212, 0.2);
}
50% {
box-shadow: 0 0 0 5px rgba(91, 159, 212, 0.05);
}
}
@media (prefers-reduced-motion: reduce) {
.step.active::before {
animation: none;
}
.bar-fill {
transition: none;
}
}
.status-card {
background: linear-gradient(180deg, rgba(91, 159, 212, 0.08), transparent 70%),
var(--panel-2);
border: 1px solid var(--border);
border-radius: 9px;
padding: 0.75rem 0.85rem;
}
.status-title {
font-weight: 650;
margin-bottom: 0.3rem;
}
.status-body {
color: var(--muted);
font-size: 0.86rem;
line-height: 1.45;
white-space: pre-wrap;
margin: 0;
font-family: inherit;
background: transparent;
border: 0;
padding: 0;
}
.writes-wrap summary,
.timeline-wrap summary {
cursor: pointer;
color: var(--muted);
font-size: 0.8rem;
padding: 0.15rem 0;
}
.run-writes {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
padding: 0.3rem 0.4rem;
border: 1px dashed rgba(91, 212, 154, 0.25);
border-radius: 8px;
background: rgba(91, 212, 154, 0.03);
}
.run-writes .write-chip {
font-family: var(--mono);
font-size: 0.72rem;
color: var(--ok);
padding: 0.12rem 0.45rem;
border-radius: 999px;
background: rgba(91, 212, 154, 0.08);
}
.timeline {
list-style: none;
margin: 0.25rem 0 0;
padding: 0 0 0 0.7rem;
border-left: 2px solid rgba(91, 159, 212, 0.3);
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.timeline-item {
font-size: 0.76rem;
color: var(--text);
line-height: 1.35;
display: flex;
gap: 0.4rem;
align-items: baseline;
}
.timeline-item .src {
font-size: 0.66rem;
padding: 0.05rem 0.35rem;
border-radius: 999px;
background: var(--panel-2);
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.progress-log-hint {
margin: 0;
}
button.linkish {
background: none;
border: 0;
color: var(--accent);
cursor: pointer;
padding: 0;
font: inherit;
text-decoration: underline;
text-underline-offset: 2px;
}
button.linkish:hover {
color: var(--accent-2, var(--accent));
}
/* Сужение .kpi-grid до двух колонок на узких экранах обеспечивает @media (max-width: 900px) в base.css
(те же имена и значения, загружается позже), здесь не дублируем. */
/* ── Карточка статистики ошибок батча ──────────────────────────────────────────────── */
.failure-stats {
margin-top: 0.75rem;
padding: 0.75rem;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--panel-2);
}
.failure-stats-head {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 0.6rem;
}
.failure-stats-title {
font-weight: 600;
font-size: 0.85rem;
color: var(--text);
}
.failure-kpis {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.5rem;
margin-bottom: 0.7rem;
}
.failure-kpi {
padding: 0.45rem 0.5rem;
border-radius: 8px;
background: var(--panel);
border: 1px solid var(--border);
text-align: center;
}
.failure-kpi-value {
font-size: 1.25rem;
font-weight: 700;
line-height: 1.1;
color: var(--text);
}
.failure-kpi-label {
font-size: 0.68rem;
color: var(--muted);
margin-top: 0.15rem;
}
.failure-kpi-hint {
font-size: 0.62rem;
margin-top: 0.1rem;
}
.failure-kpi.warn .failure-kpi-value {
color: var(--warn);
}
.failure-kpi.danger .failure-kpi-value {
color: var(--danger);
}
.failure-kpi.ok .failure-kpi-value {
color: var(--ok);
}
.failure-breakdown {
margin-bottom: 0.6rem;
}
.failure-breakdown-bar {
display: flex;
width: 100%;
height: 12px;
border-radius: 6px;
overflow: hidden;
background: var(--panel);
}
.fseg {
height: 100%;
}
.fseg-err {
background: var(--danger);
}
.fseg-warn {
background: var(--warn);
}
.fseg-ok {
background: var(--ok);
}
.failure-legend {
display: flex;
flex-wrap: wrap;
gap: 0.4rem 0.7rem;
margin-top: 0.4rem;
font-size: 0.68rem;
color: var(--muted);
}
.failure-legend-item {
display: inline-flex;
align-items: center;
gap: 0.25rem;
}
.failure-legend-item b {
color: var(--text);
}
.fdot {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 2px;
}
.failure-empty {
margin: 0.3rem 0;
color: var(--ok);
}
.failure-spark {
margin: 0.5rem 0 0.6rem;
}
.failure-spark-title {
font-size: 0.62rem;
margin-bottom: 0.2rem;
}
.failure-spark-svg {
width: 100%;
height: 32px;
display: block;
}
.spark-ok {
fill: var(--ok);
opacity: 0.55;
}
.spark-fail {
fill: var(--danger);
}
.failure-reasons {
margin-top: 0.55rem;
border-top: 1px solid var(--border);
padding-top: 0.5rem;
}
.failure-reasons-title {
font-size: 0.7rem;
font-weight: 600;
color: var(--muted);
margin-bottom: 0.3rem;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.failure-reason-row {
display: flex;
justify-content: space-between;
gap: 0.5rem;
font-size: 0.72rem;
padding: 0.12rem 0;
}
.failure-reason-label {
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.failure-reason-count {
color: var(--danger);
font-weight: 600;
flex: 0 0 auto;
}
+277
View File
@@ -0,0 +1,277 @@
/* Оболочка страницы Register + общая со страницей логов: split-раскладка, панель формы, ops-фидбек, run-header, .log.
Стили RunProgress вынесены в run-progress.css (использует только страница регистрации).
.page-head / .page-head h1 / .toolbar определены глобально в base.css (загружается позже и перекрывает этот файл),
Здесь оставлен только gap .toolbar.wrap, не заданный в base.css. */
.toolbar.wrap {
flex-wrap: wrap;
gap: 0.5rem;
}
.split {
display: grid;
grid-template-columns: minmax(320px, 0.95fr) minmax(340px, 1.15fr);
gap: var(--space-4);
align-items: start;
}
.panel {
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: var(--space-4);
}
.form-panel {
max-height: calc(100vh - 7.5rem);
overflow: auto;
display: flex;
flex-direction: column;
gap: 0.85rem;
}
.progress-panel {
max-height: calc(100vh - 7.5rem);
overflow: auto;
}
.stack-form {
display: flex;
flex-direction: column;
gap: 0.85rem;
}
.provider-multi.mail-domain-chips,
.form-panel .mail-domain-chips {
display: flex;
flex-wrap: wrap;
gap: 0.45rem 0.75rem;
align-items: center;
}
.form-panel .mail-domain-chips .chip {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.2rem 0.65rem;
cursor: pointer;
color: var(--text);
font-size: 0.86rem;
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.form-panel .hint.tight {
margin: 0.35rem 0 0;
font-size: 0.8rem;
color: var(--muted);
}
.form-panel .hint.warn {
color: #e0a060;
}
/* Основа .field-grid в components.css (загружается позже, перекрывает построчно), здесь оставлен только .span2 ——
components.css определяет .field-grid .span2 только внутри @media (max-width: 640px),
На широких экранах эквивалентного правила нет, удаление вернёт кросс-колоночные поля в одну колонку. */
.field-grid .span2 {
grid-column: 1 / -1;
}
.info-box {
background: rgba(91, 159, 212, 0.08);
border: 1px dashed rgba(91, 159, 212, 0.3);
border-radius: 8px;
padding: 0.65rem 0.75rem;
color: var(--muted);
font-size: 0.84rem;
line-height: 1.45;
}
.form-foot-toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
padding-top: 0.35rem;
border-top: 1px solid var(--border);
align-items: center;
}
.form-foot-toolbar .link-hint {
margin-left: auto;
color: var(--muted);
font-size: 0.8rem;
text-decoration: none;
border-bottom: 1px dotted var(--border);
}
.form-foot-toolbar .link-hint:hover {
color: var(--accent);
border-bottom-color: var(--accent);
}
.advanced {
border: 1px solid var(--border);
border-radius: 9px;
padding: 0.35rem 0.6rem 0.6rem;
background: var(--panel-2);
}
.advanced summary {
cursor: pointer;
color: var(--muted);
font-size: 0.85rem;
padding: 0.2rem 0;
}
.advanced[open] {
border-color: rgba(91, 159, 212, 0.35);
}
.advanced .field-grid {
margin-top: 0.5rem;
}
label.check {
flex-direction: row;
align-items: center;
gap: 0.45rem;
color: var(--text);
font-size: 0.86rem;
padding-top: 0.45rem;
display: flex;
}
label.check.muted {
color: var(--muted);
}
label.check input {
width: auto;
}
/* ops feedback / log: внешний вид (цвета, рамки, отступы, шрифт) полностью задаётся components.css
определены и загружаются позже с перекрытием, здесь оставлены только правила, которых нет в components.css.
Учтите: margin-bottom у .ops-feedback / .ops-log-wrap тоже мёртвый ——
components.css shorthand `margin: 0 0 0.65rem` полностью перекрывает вертикальные отступы. */
.ops-feedback {
cursor: pointer;
}
/* .ops-feedback.ok в components.css задаёт только border-color / background,
нет color — цвет текста этого правила всё ещё действует, удалять нельзя. */
.ops-feedback.ok {
color: var(--ok);
}
/* .ops-log-wrap > summary в components.css уже задаёт cursor / color (селектор потомка;
.ops-log-wrap — это <details>, summary обязан быть его прямым потомком, оба варианта попадают в тот же узел),
Здесь только дополняется font-size, не заданный в components.css. */
.ops-log-wrap summary {
font-size: 0.85rem;
}
.ops-log {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.ops-log li {
font-size: 0.78rem;
align-items: baseline;
}
.ops-log .t {
font-family: var(--mono);
}
/* У .ops-log .k в components.css нет color, серый цвет по умолчанию даёт это правило
(три статусных цвета .k.ok/.err/.warn уже определены в components.css). */
.ops-log .k {
color: var(--muted);
}
.ops-log .m {
color: var(--text);
}
.run-header {
position: sticky;
top: 0;
z-index: 1;
background: var(--panel);
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.55rem 0.7rem;
border: 1px solid var(--border);
border-radius: 9px;
font-weight: 650;
}
.run-header .status-word {
letter-spacing: 0.03em;
font-size: 1.05rem;
}
.run-header .meta-chips {
display: flex;
gap: 0.35rem;
flex-wrap: wrap;
margin-left: auto;
}
.run-header[data-state="alive"] {
border-color: rgba(91, 212, 154, 0.35);
}
.run-header[data-state="stuck"],
.run-header-stuck {
background: rgba(212, 91, 91, 0.12);
border-color: rgba(212, 91, 91, 0.5);
}
.chip.mini {
font-size: 0.7rem;
padding: 0.14rem 0.5rem;
color: var(--muted);
}
/* .chip.chip-err / .chip.chip-danger определены в components.css (загружается позже,
color + border-color перекрываются), здесь не дублируем. */
.log {
background: #070b10;
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.65rem 0.75rem;
color: #c9d4e4;
font-size: 0.78rem;
line-height: 1.4;
overflow: auto;
white-space: pre-wrap;
word-break: break-word;
margin: 0;
}
.log.compact {
max-height: 8rem;
}
@media (max-width: 900px) {
.split {
grid-template-columns: 1fr;
}
.split > .progress-panel {
order: -1;
}
.form-panel,
.progress-panel {
max-height: none;
}
.field-grid {
grid-template-columns: 1fr;
}
}
+96
View File
@@ -0,0 +1,96 @@
/* Settings page */
.page-settings .settings-form.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.65rem 0.85rem;
margin-bottom: var(--space-3);
}
.page-settings .settings-form label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.82rem;
color: var(--muted);
}
.page-settings .settings-form .span2 {
grid-column: 1 / -1;
}
.page-settings .settings-section-title {
font-weight: 600;
color: var(--text);
margin-bottom: 0.25rem;
}
.page-settings .provider-pipeline .mail-domain-chips {
display: flex;
flex-wrap: wrap;
gap: 0.45rem 0.75rem;
margin-top: 0.45rem;
}
.page-settings .provider-pipeline .chip {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 999px;
padding: 0.2rem 0.65rem;
cursor: pointer;
color: var(--text);
font-size: 0.86rem;
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.page-settings .hint.tight {
margin: 0.25rem 0 0;
font-size: 0.8rem;
}
.page-settings .settings-form input,
.page-settings .settings-form select,
.page-settings .settings-form textarea {
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 7px;
color: var(--text);
padding: 0.35rem 0.5rem;
font: inherit;
}
.page-settings .card {
margin-bottom: var(--space-3);
}
.page-settings .card h2 {
margin: 0 0 0.55rem;
font-size: 1rem;
}
.page-settings label.inline {
display: inline-flex;
align-items: center;
gap: 0.4rem;
margin-right: 0.75rem;
color: var(--muted);
font-size: 0.85rem;
}
.page-settings label.inline input {
min-width: 14rem;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 7px;
color: var(--text);
padding: 0.35rem 0.5rem;
font: inherit;
}
@media (max-width: 700px) {
.page-settings .settings-form.grid {
grid-template-columns: 1fr;
}
}
+27
View File
@@ -0,0 +1,27 @@
:root {
--bg: #0b0f14;
--panel: #121a24;
--panel-2: #182231;
--text: #e8eef7;
--muted: #8b9bb4;
--accent: #5b9fd4;
--accent-2: #3d7eb0;
--danger: #d45b5b;
--ok: #5bd49a;
--warn: #d4b15b;
--border: #243044;
--sidebar: #0a1018;
--sidebar-w: 220px;
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 14px;
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 24px;
--space-6: 32px;
--font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--shadow-card: 0 18px 50px rgba(0, 0, 0, 0.35);
}
+12
View File
@@ -0,0 +1,12 @@
export function Bar({ label, value, max = 100, kind = "ok", class: cls = "" }) {
const pct = max > 0 ? Math.min(100, Math.round((value / max) * 100)) : 0;
return (
<div class={`bar-row ${cls}`}>
{label ? <div class="bar-label">{label}</div> : null}
<div class="bar-track" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
<div class={`bar-fill bar-${kind}`} style={{ width: `${pct}%` }} />
</div>
<div class="bar-value">{pct}%</div>
</div>
);
}
+22
View File
@@ -0,0 +1,22 @@
export function Button({
variant = "ghost",
size = "md",
busy = false,
type = "button",
class: cls = "",
children,
disabled,
...rest
}) {
return (
<button
type={type}
class={`btn btn-${variant} btn-${size} ${busy ? "busy" : ""} ${cls}`}
disabled={busy || !!disabled}
aria-busy={busy || undefined}
{...rest}
>
{children}
</button>
);
}
+7
View File
@@ -0,0 +1,7 @@
export function Card({ children, class: cls = "", ...rest }) {
return (
<div class={`card ${cls}`} {...rest}>
{children}
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
export function Chip({ kind = "default", children, class: cls = "", title, ...rest }) {
// Accept "mini" as alias for CSS class chip-mini
const extra = String(cls || "")
.split(/\s+/)
.filter(Boolean)
.map((c) => (c === "mini" ? "chip-mini" : c))
.join(" ");
return (
<span class={`chip chip-${kind} ${extra}`} title={title} {...rest}>
{children}
</span>
);
}
+21
View File
@@ -0,0 +1,21 @@
export function Drawer({ open, title, onClose, children, class: cls = "" }) {
if (!open) return null;
return (
<div class="drawer-backdrop" onClick={onClose}>
<div
class={`drawer ${cls}`}
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
>
<div class="drawer-head">
<div class="drawer-title">{title}</div>
<button type="button" class="btn btn-ghost btn-sm" onClick={onClose}>
Закрыть
</button>
</div>
<div class="drawer-body">{children}</div>
</div>
</div>
);
}
+8
View File
@@ -0,0 +1,8 @@
export function Field({ label, span2 = false, children, class: cls = "" }) {
return (
<label class={`field ${span2 ? "span2" : ""} ${cls}`}>
{label ? <span class="field-label">{label}</span> : null}
{children}
</label>
);
}
+9
View File
@@ -0,0 +1,9 @@
export function Kpi({ label, value, hint, class: cls = "" }) {
return (
<div class={`kpi ${cls}`}>
<div class="kpi-label">{label}</div>
<div class="kpi-value">{value}</div>
{hint ? <div class="kpi-hint hint">{hint}</div> : null}
</div>
);
}
+11
View File
@@ -0,0 +1,11 @@
// Collapsible raw-response log. Toast/banner carry the primary feedback;
// the raw JSON is demoted to expandable evidence (batch-2 IA decision).
export function LogDetails({ text, summary = "Детали ответа", compact = false }) {
if (!text) return null;
return (
<details class="log-details">
<summary>{summary}</summary>
<pre class={compact ? "log compact" : "log"}>{text}</pre>
</details>
);
}
+47
View File
@@ -0,0 +1,47 @@
// Shell-level sticky banner + ops log (legacy #ops-feedback / #ops-log).
// Mounted once in App.main-wrap so every page sees top actions.
import { useState } from "preact/hooks";
import {
stickyBanner,
opsLog,
clearStickyBanner,
} from "../store/feedback.js";
export function OpsFeedbackBar() {
const [logOpen, setLogOpen] = useState(false);
const banner = stickyBanner.value;
const logItems = opsLog.value;
return (
<>
{banner ? (
<div
class={`ops-feedback ${banner.kind || "info"}`}
role="status"
onClick={clearStickyBanner}
title="Кликните, чтобы убрать баннер"
>
{banner.message}
</div>
) : null}
<details
class="ops-log-wrap"
open={logOpen}
onToggle={(e) => setLogOpen(e.currentTarget.open)}
>
<summary>
ДействияЛоги <span class="hint">{logItems.length}</span>
</summary>
<ol class="ops-log" aria-live="polite">
{logItems.map((it, i) => (
<li key={i}>
<span class="t">{it.t}</span>
<span class={`k ${it.kind}`}>{it.kind}</span>
<span class="m">{it.m}</span>
</li>
))}
</ol>
</details>
</>
);
}
+13
View File
@@ -0,0 +1,13 @@
// Shared page header: title + hint on the left, toolbar slot on the right.
// toolbarClass lets LogsPage keep its `toolbar wrap` variant verbatim.
export function PageHeader({ title, hint, children, toolbarClass = "toolbar" }) {
return (
<header class="page-head">
<div>
<h1>{title}</h1>
{hint ? <p class="hint">{hint}</p> : null}
</div>
{children ? <div class={toolbarClass}>{children}</div> : null}
</header>
);
}
+37
View File
@@ -0,0 +1,37 @@
// ProviderPoolStatus — строка статуса текущего пула email_providers (batch-2 IA)
// Replaces the hint long block on Settings + Register: права записи в пул асимметричны между двумя страницами,
// Выражается одной строкой статуса + бейджами, а не правилами на каждой странице.
// Self-contained styles (components.css) — .badge lives in accounts.css and is
// not loaded on Settings / Register.
export function ProviderPoolStatus({
selected = [],
primaryProvider = "",
canClear = false,
hydrated = true,
dirty = false,
}) {
return (
<div class="pool-status">
<span class="pool-status-label">Текущий пул</span>
{selected.length ? (
selected.map((p) => (
<span key={p} class="pool-chip">
{p}
</span>
))
) : (
<span class="pool-chip empty">
пусто · одиночный канал {primaryProvider || "—"}
</span>
)}
<span class={`pool-tag ${canClear ? "can-clear" : ""}`}>
{canClear ? "Здесь можно очистить пул" : "Очистка пула здесь недоступна (страница настроек)"}
</span>
{!hydrated ? (
<span class="pool-tag warn">не загружено</span>
) : dirty ? (
<span class="pool-tag warn">не сохранено</span>
) : null}
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
export function Select({ options = [], value, onChange, class: cls = "", ...rest }) {
// options: [{ value, label }] or string[]
return (
<select
class={`select ${cls}`}
value={value}
onChange={(e) => onChange && onChange(e.currentTarget.value)}
{...rest}
>
{options.map((o) =>
typeof o === "string" ? (
<option key={o} value={o}>
{o}
</option>
) : (
<option key={o.value} value={o.value}>
{o.label}
</option>
),
)}
</select>
);
}
+4
View File
@@ -0,0 +1,4 @@
export function StatusDot({ kind = "idle", class: cls = "" }) {
// kind: ok | warn | err | busy | idle
return <span class={`status-dot status-${kind} ${cls}`} aria-hidden="true" />;
}
+19
View File
@@ -0,0 +1,19 @@
export function Tabs({ items, value, onChange }) {
// items: [{ id, label }]
return (
<div class="tabrow" role="tablist">
{items.map((it) => (
<button
key={it.id}
type="button"
role="tab"
class={`tab ${value === it.id ? "active" : ""}`}
aria-selected={value === it.id}
onClick={() => onChange(it.id)}
>
{it.label}
</button>
))}
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { toasts } from "../store/feedback.js";
export function ToastHost() {
return (
<div class="ops-toast-host" aria-live="polite">
{toasts.value.map((t) => (
<div key={t.id} class={`ops-toast ${t.kind}`}>
{t.message}
</div>
))}
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
export { Button } from "./Button.jsx";
export { Card } from "./Card.jsx";
export { Field } from "./Field.jsx";
export { Select } from "./Select.jsx";
export { Tabs } from "./Tabs.jsx";
export { StatusDot } from "./StatusDot.jsx";
export { Chip } from "./Chip.jsx";
export { Kpi } from "./Kpi.jsx";
export { Bar } from "./Bar.jsx";
export { ToastHost } from "./ToastHost.jsx";
export { OpsFeedbackBar } from "./OpsFeedbackBar.jsx";
export { Drawer } from "./Drawer.jsx";
export { PageHeader } from "./PageHeader.jsx";
export { LogDetails } from "./LogDetails.jsx";
export { ProviderPoolStatus } from "./ProviderPoolStatus.jsx";
+24
View File
@@ -0,0 +1,24 @@
import { defineConfig } from "vite";
import preact from "@preact/preset-vite";
import { resolve } from "node:path";
export default defineConfig({
plugins: [preact()],
base: "/",
root: resolve(__dirname),
publicDir: false,
build: {
outDir: "dist",
emptyOutDir: true,
sourcemap: true,
},
server: {
port: 5173,
proxy: {
"/api": {
target: "http://127.0.0.1:8787",
changeOrigin: true,
},
},
},
});
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from "vitest/config";
import preact from "@preact/preset-vite";
export default defineConfig({
plugins: [preact()],
test: {
environment: "jsdom",
globals: true,
include: ["src/**/*.test.{js,jsx}"],
},
});