From 01a58dd6ccb777413fbe9ea4a1313b08c1067868 Mon Sep 17 00:00:00 2001 From: vlad Date: Tue, 20 Oct 2026 20:54:10 +0300 Subject: [PATCH] feat: dashboard (stdlib, :8910, dark UI, cards+tables+actions) + secondno client fixes (chrome-fallback, full_cycle headless param) --- dashboard.py | 348 +++++++++++++++++++++++++++++++++++++++++++++ secondno/client.py | 21 ++- 2 files changed, 363 insertions(+), 6 deletions(-) create mode 100644 dashboard.py diff --git a/dashboard.py b/dashboard.py new file mode 100644 index 0000000..c5b35d4 --- /dev/null +++ b/dashboard.py @@ -0,0 +1,348 @@ +# -*- coding: utf-8 -*- +"""River-autoreg dashboard — single-file, stdlib only. + +Run: python dashboard.py [port] (default 8910) + +Shows: bank accounts (data/river_bank.jsonl), 2nd-no account pool +(data/secondno/state.json), used numbers, WorkOS Radar block countdown, +mail pool size, sidecar captcha health, reg log tail. + +Actions (POST): + /api/reg {"n":1,"phone":"secondno"} -> river_reg.py wave (detached) + /api/reg2no {"n":1} -> secondno_register.py (detached) + /api/complete {"phone":"secondno"} -> complete_pending.py (detached) + /api/reserve_test -> live 2nd-no reservation test (sync) + +Secrets are never rendered: passwords/keys are masked server-side. +""" +import json +import os +import re +import subprocess +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlparse + +ROOT = os.path.dirname(os.path.abspath(__file__)) +DATA = os.path.join(ROOT, "data") +SN_HOME = os.path.join(DATA, "secondno") +PY = sys.executable +SIDECAR = "http://127.0.0.1:8877/health" +RESERVE_LOG = os.path.join(DATA, "reserve_test.log") + + +def _mask(s, keep=2): + if not s: + return "" + s = str(s) + return s[:keep] + "*" * max(4, len(s) - keep * 2) + s[-keep:] if len(s) > keep * 2 + 2 else "***" + + +def read_jsonl(path): + out = [] + try: + for ln in open(path, encoding="utf-8"): + ln = ln.strip() + if ln: + try: + out.append(json.loads(ln)) + except Exception: + pass + except Exception: + pass + return out + + +def read_json(path, default=None): + try: + return json.load(open(path, encoding="utf-8")) + except Exception: + return default if default is not None else {} + + +def radar_state(): + p = os.path.join(DATA, "radar_block") + try: + until = int(open(p, encoding="utf-8").read().strip()) + except Exception: + return {"blocked": False, "until": 0, "left_s": 0} + left = until - int(time.time()) + return {"blocked": left > 0, "until": until, "left_s": max(0, left)} + + +def bank_stats(bank): + ok = sum(1 for b in bank if b.get("ok") and (b.get("api_key") or b.get("key"))) + pend = sum(1 for b in bank if not b.get("ok") and "radar" in str(b.get("stage", "")) + str(b.get("err", ""))) + fail = len(bank) - ok - pend + return {"total": len(bank), "ok": ok, "pending": pend, "failed": fail} + + +def sidecar_ok(): + try: + import urllib.request + with urllib.request.urlopen(SIDECAR, timeout=3) as r: + return r.status == 200 + except Exception: + return False + + +def snapshot(): + bank = read_jsonl(os.path.join(DATA, "river_bank.jsonl")) + rows = [] + for b in bank: + rows.append({ + "email": b.get("email", "?"), + "stage": b.get("stage", ""), + "ok": bool(b.get("ok")), + "err": str(b.get("err", ""))[:90], + "has_key": bool(b.get("api_key") or b.get("key")), + "key": _mask(b.get("api_key") or b.get("key"), 4), + "ts": b.get("ts") or b.get("time") or "", + }) + sn = read_json(os.path.join(SN_HOME, "state.json"), {}) + sn_accs = [] + for a in sn.get("accounts", []): + sn_accs.append({ + "email": a.get("email", "?"), + "pass": _mask(a.get("password") or a.get("pass", ""), 2), + "created": a.get("created") or a.get("ts") or "", + "reservations": len(a.get("reservations") or []) if isinstance(a.get("reservations"), list) else a.get("reservations", 0), + }) + used = read_json(os.path.join(SN_HOME, "used_numbers.json"), []) + mail_pool = 0 + try: + mail_pool = sum(1 for ln in open(os.path.join(DATA, "mail_pool.txt"), encoding="utf-8") if ln.strip()) + except Exception: + pass + log_tail = "" + for lf in ("reg2no.log", "reserve_test.log", "wave.log"): + p = os.path.join(DATA, lf) + try: + txt = open(p, encoding="utf-8", errors="ignore").read() + log_tail += f"--- {lf} ---\n" + "\n".join(txt.splitlines()[-12:]) + "\n" + except Exception: + pass + return { + "now": int(time.time()), + "radar": radar_state(), + "bank": rows, + "stats": bank_stats(bank), + "secondno": {"accounts": sn_accs, "used_numbers": list(used)[-20:], "used_count": len(used)}, + "mail_pool": mail_pool, + "sidecar": sidecar_ok(), + "log_tail": log_tail[-3000:], + } + + +def spawn(args, logfile): + env = dict(os.environ) + env.pop("PYTHONPATH", None) + env.setdefault("SYSTEMDRIVE", "C:") + f = open(os.path.join(DATA, logfile), "a", encoding="utf-8") + f.write(f"\n=== {time.strftime('%H:%M:%S')} {' '.join(args)} ===\n") + f.flush() + p = subprocess.Popen([PY] + args, cwd=ROOT, stdout=f, stderr=subprocess.STDOUT, + env=env, creationflags=getattr(subprocess, "DETACHED_PROCESS", 0)) + return p.pid + + +def reserve_test(): + """Sync reservation test against 2nd-no (no OTP wait): proves login+captcha+reserve.""" + accs = read_json(os.path.join(SN_HOME, "state.json"), {}).get("accounts", []) + if not accs: + return {"ok": False, "err": "no 2nd-no accounts (run secondno_register.py)"} + os.environ.setdefault("SECONDNO_HOME", SN_HOME) + sys.path.insert(0, ROOT) + try: + from secondno import SecondNo, get_solver + except Exception as e: + return {"ok": False, "err": f"import: {e}"} + try: + solver = get_solver() + except Exception: + solver = None + sn = SecondNo(solver=solver, headless=True) + try: + acc = accs[0] + sn.login(acc["email"], acc.get("password") or acc.get("pass", "")) + info = None + try: + info = sn.reuse_active(set(read_json(os.path.join(SN_HOME, "used_numbers.json"), []))) + except Exception: + pass + mode = "reuse" + if not info: + info = sn.get_number() + mode = "fresh" + if not info: + return {"ok": False, "err": "no reservable number (cap/used)"} + return {"ok": True, "mode": mode, "number": info.get("full"), "number_id": info.get("number_id")} + except Exception as e: + return {"ok": False, "err": str(e)[:200]} + finally: + try: + sn.close() + except Exception: + pass + + +HTML = """ + +River Autoreg Dashboard + +

⚡ RIVER AUTOREG

river.ai · WorkOS · 2nd-no SMS +
+
+
+

Действия

+ + + + + + +
+

Аккаунты River

+
emailstageстатусkeyошибка
+

Пул 2nd-no.com

+
emailpassсоздан
+

Логи

+
+""" + + +class H(BaseHTTPRequestHandler): + def log_message(self, format, *args): + pass + + def _send(self, code, body, ctype="application/json"): + b = body.encode("utf-8") if isinstance(body, str) else body + self.send_response(code) + self.send_header("Content-Type", ctype + "; charset=utf-8") + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + u = urlparse(self.path).path + if u in ("/", "/index.html"): + self._send(200, HTML, "text/html") + elif u == "/api/state": + try: + self._send(200, json.dumps(snapshot(), ensure_ascii=False)) + except Exception as e: + self._send(500, json.dumps({"err": str(e)})) + else: + self._send(404, '{"err":"nf"}') + + def do_POST(self): + u = urlparse(self.path).path + n = int(self.headers.get("Content-Length") or 0) + try: + body = json.loads(self.rfile.read(n) or b"{}") + except Exception: + body = {} + try: + if u == "/api/reg2no": + cnt = max(1, min(10, int(body.get("n", 1)))) + pid = spawn(["secondno_register.py", str(cnt)], "reg2no.log") + self._send(200, json.dumps({"ok": True, "pid": pid, "log": "data/reg2no.log"})) + elif u == "/api/reg": + cnt = max(1, min(50, int(body.get("n", 1)))) + phone = body.get("phone", "secondno") + args = ["river_reg.py", str(cnt), "--phone", phone, "--imap-timeout", "780"] + pid = spawn(args, "wave.log") + self._send(200, json.dumps({"ok": True, "pid": pid, "log": "data/wave.log"})) + elif u == "/api/complete": + pid = spawn(["complete_pending.py", "--phone", body.get("phone", "secondno")], "wave.log") + self._send(200, json.dumps({"ok": True, "pid": pid, "log": "data/wave.log"})) + elif u == "/api/reserve_test": + self._send(200, json.dumps(reserve_test(), ensure_ascii=False)) + else: + self._send(404, '{"err":"nf"}') + except Exception as e: + self._send(500, json.dumps({"err": str(e)[:200]})) + + +def main(): + port = int(sys.argv[1]) if len(sys.argv) > 1 else 8910 + os.makedirs(DATA, exist_ok=True) + os.makedirs(SN_HOME, exist_ok=True) + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + print(f"river dashboard: http://127.0.0.1:{port}", flush=True) + srv.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/secondno/client.py b/secondno/client.py index e0bfd0b..335a869 100644 --- a/secondno/client.py +++ b/secondno/client.py @@ -141,10 +141,19 @@ class SecondNo: def _start(self): if self._pg is None: self._pw = sync_playwright().start() - self._browser = self._pw.chromium.launch( - headless=self.headless, channel="chrome", - args=["--no-sandbox", "--disable-blink-features=AutomationControlled", - "--window-position=2400,2400"]) + try: + self._browser = self._pw.chromium.launch( + headless=self.headless, channel="chrome", + args=["--no-sandbox", "--disable-blink-features=AutomationControlled", + "--window-position=2400,2400"]) + except Exception: + # channel="chrome" fails when SYSTEMDRIVE-ish env is broken + # (playwright resolves "undefined\Program Files\..."); use + # bundled chromium instead. + self._browser = self._pw.chromium.launch( + headless=self.headless, + args=["--no-sandbox", "--disable-blink-features=AutomationControlled", + "--window-position=2400,2400"]) ctx = self._browser.new_context(user_agent=UA, locale="en-US") self._pg = ctx.new_page() self._pg.add_init_script("Object.defineProperty(navigator,'webdriver',{get:()=>undefined})") @@ -345,14 +354,14 @@ def save_account(info: dict): json.dump(state, open(STATE_FILE, "w", encoding="utf-8"), indent=1) -def full_cycle(count=1, solver=None, inbox_factory=None): +def full_cycle(count=1, solver=None, inbox_factory=None, headless=True): """Register fresh account(s) and grab number(s). Returns list of dicts.""" if solver is None: from .captcha import get_solver solver = get_solver() out = [] for _ in range(count): - s = SecondNo(solver=solver) + s = SecondNo(solver=solver, headless=headless) try: inbox = inbox_factory() if inbox_factory else None creds = s.register(inbox=inbox)