diff --git a/GUIDE_RU.md b/GUIDE_RU.md index da1b194..be0042d 100644 --- a/GUIDE_RU.md +++ b/GUIDE_RU.md @@ -108,6 +108,37 @@ Radar-сигнатуры: `_1_signals` — base64 JSON-фингерпринт; 6. **Access-blocked детектор** должен смотреть только rendered-текст страницы: i18n-словари AuthKit содержат строку блока во всех языках → ложные срабатывания. +## Дашборд + +`python dashboard.py [port]` (по умолчанию 8910) — однофайловый stdlib-сервер, тёмный UI. +Открывается на `http://127.0.0.1:8910`. + +- **Карточки**: статистика банка (OK/pending/failed), countdown Radar-лока, размер пула + 2nd-no, сожжённые номера, mail pool, статус капчи (sidecar/2captcha/ready). +- **Действия**: рега 2nd-no акков, запуск river-волны (`--phone secondno`), + complete pending, reserve-тест (живой номер 2nd-no), captcha-тест (живой solve turnstile). +- **Таблицы**: аккаунты river-банка (email/stage/статус/key/ошибка), пул 2nd-no. +- **Логи**: хвост reg2no.log / reserve_test.log / wave.log. +- Авто-обновление каждые 15с (переключается). Секреты маскируются на сервере. + +## Капча (turnstile для 2nd-no резервов) + +Вендорный `secondno/captcha.py` даёт `CaptchaRouter` — пробует бэкенды по порядку с ретраями: + +1. **SidecarSolver** — локальный captcha-solver sidecar на `:8877` (БЕСПЛАТНО, ~14с/токен). + Health: `GET http://127.0.0.1:8877/health`. Поднимается отдельно. Приоритетный бэкенд. +2. **TwoCaptchaTurnstile** — 2captcha.com фолбэк. Источник ключа (первый матч): + - env `TWOCAPTCHA_API_KEY` + - env `RUCAPTCHA_KEY` + - `data/secondno/captcha_keys.json` (шаблон: `captcha_keys.example.json`) + + ВАЖНО: submit ТОЛЬКО через `in.php` (res.php → ERROR_EMPTY_METHOD); + баланс: POST `res.php {action:getbalance}`, значение в поле `request`. + +`get_solver()` возвращает роутер (sidecar → 2captcha фолбэк). Дашборд показывает +живой статус капчи (sidecar alive, баланс 2captcha) и имеет кнопку **🧩 Captcha-тест**, +которая решает реальный turnstile 2nd-no.com end-to-end. + ## Файлы ``` @@ -115,6 +146,8 @@ river_reg.py главный драйвер: signup → verify → radar complete_pending.py дожатие акков, застрявших на phone/SMS-шаге secondno_register.py рега акков 2nd-no.com для --phone secondno secondno/ вендорный клиент 2nd-no.com (2no.pl JSON-RPC + turnstile-солверы) +dashboard.py веб-дашборд (stdlib, :8910, тёмный UI, карточки/таблицы/действия) +captcha_keys.example.json шаблон конфига 2captcha-ключей (→ data/secondno/captcha_keys.json) river_wave.sh пейсинг-обёртка волны mail_pool.example.txt requirements.txt diff --git a/README.md b/README.md index 8fe107b..1ae48ba 100644 --- a/README.md +++ b/README.md @@ -73,8 +73,43 @@ python river_reg.py 3 --phone secondno # REUSE-FIRST reservation + OTP poll # finish accounts stuck at the phone step later python complete_pending.py --phone fivesim + +# dashboard (stdlib, dark UI, http://127.0.0.1:8910) +python dashboard.py # or: python dashboard.py 8910 ``` +## Captcha (turnstile for 2nd-no reservations) + +The vendored `secondno/captcha.py` provides a `CaptchaRouter` that tries backends +in order with retries: + +1. **SidecarSolver** — local captcha-solver sidecar at `:8877` (FREE, ~14s/token). + Health: `GET http://127.0.0.1:8877/health`. Start it separately (see your + captcha-solver sidecar setup). Preferred backend. +2. **TwoCaptchaTurnstile** — 2captcha.com fallback. Key source (first match wins): + - env `TWOCAPTCHA_API_KEY` + - env `RUCAPTCHA_KEY` + - `data/secondno/captcha_keys.json` (copy from `captcha_keys.example.json`) + + IMPORTANT: submit ONLY via `in.php` (res.php returns ERROR_EMPTY_METHOD); + balance check is POST `res.php {action:getbalance}`, balance in `request` field. + +`get_solver()` returns the router (sidecar → 2captcha fallback). The dashboard +shows live captcha status (sidecar alive, 2captcha balance) and has a +**🧩 Captcha-тест** button that solves a real 2nd-no turnstile end-to-end. + +## Dashboard + +`python dashboard.py [port]` (default 8910) — single-file stdlib server, dark UI. + +- **Cards**: bank stats (OK/pending/failed), Radar block countdown, 2nd-no pool size, + used numbers, mail pool, captcha status (sidecar/2captcha/ready). +- **Actions**: register 2nd-no accounts, launch river wave (`--phone secondno`), + complete pending, reserve-test (live 2nd-no number), captcha-test (live turnstile solve). +- **Tables**: river bank accounts (email/stage/status/key/err), 2nd-no account pool. +- **Logs**: tail of reg2no.log / reserve_test.log / wave.log. +- Auto-refresh every 15s (toggleable). Secrets are masked server-side. + Results append to `data/river_bank.jsonl` (email, password, imap_pass, PKCE verifier, tokens, key material, stage/err on failure). `data/` is gitignored. @@ -103,6 +138,8 @@ river_reg.py main driver (signup -> verify -> radar -> exchange -> key) complete_pending.py resume accounts stuck at the phone/SMS step secondno_register.py register 2nd-no.com accounts for --phone secondno secondno/ vendored 2nd-no.com client (2no.pl JSON-RPC + turnstile solvers) +dashboard.py web dashboard (stdlib, :8910, dark UI, cards/tables/actions) +captcha_keys.example.json 2captcha key config template (-> data/secondno/captcha_keys.json) river_wave.sh paced wave wrapper mail_pool.example.txt requirements.txt diff --git a/captcha_keys.example.json b/captcha_keys.example.json new file mode 100644 index 0000000..1a56d61 --- /dev/null +++ b/captcha_keys.example.json @@ -0,0 +1,6 @@ +{ + "keys": [ + {"key": "YOUR_2CAPTCHA_KEY_HERE", "label": "primary"}, + {"key": "BACKUP_KEY_HERE", "label": "backup"} + ] +} diff --git a/dashboard.py b/dashboard.py index c5b35d4..1071ed6 100644 --- a/dashboard.py +++ b/dashboard.py @@ -124,6 +124,13 @@ def snapshot(): log_tail += f"--- {lf} ---\n" + "\n".join(txt.splitlines()[-12:]) + "\n" except Exception: pass + # captcha subsystem status + try: + sys.path.insert(0, ROOT) + from secondno.captcha import captcha_status as _cs + cap = _cs() + except Exception as e: + cap = {"ready": False, "err": str(e)[:80]} return { "now": int(time.time()), "radar": radar_state(), @@ -132,6 +139,7 @@ def snapshot(): "secondno": {"accounts": sn_accs, "used_numbers": list(used)[-20:], "used_count": len(used)}, "mail_pool": mail_pool, "sidecar": sidecar_ok(), + "captcha": cap, "log_tail": log_tail[-3000:], } @@ -233,6 +241,7 @@ border-radius:4px;padding:5px;font:12px inherit} + @@ -255,7 +264,9 @@ function render(){ ['2nd-no акков',S.secondno.accounts.length,S.secondno.accounts.length?'ok':'warn'], ['номеров сожжено',S.secondno.used_count,''], ['mail pool',S.mail_pool,S.mail_pool?'ok':'err'], - ['sidecar капча',''+(S.sidecar?'жив':'мёртв'),S.sidecar?'ok':'err'], + ['капча sidecar',''+((S.captcha&&S.captcha.sidecar_alive)?'жив':'мёртв'),(S.captcha&&S.captcha.sidecar_alive)?'ok':'err'], + ['2captcha',(S.captcha&&S.captcha.has_2captcha_key)?('$'+S.captcha.balance_2captcha):'нет ключа',(S.captcha&&S.captcha.has_2captcha_key)?'ok':'warn'], + ['капча готова',''+((S.captcha&&S.captcha.ready)?'да':'нет'),(S.captcha&&S.captcha.ready)?'ok':'err'], ].map(c=>'
'+c[1]+'
'+c[0]+'
').join(''); document.getElementById('bankcount').textContent=st.total+' записей'; const tb=document.querySelector('#bank tbody'); @@ -273,6 +284,7 @@ async function act(a){ if(a==='reg'){body={n:+document.getElementById('nreg').value||1,phone:'secondno'}; if(S&&S.radar.blocked&&!confirm('Radar-лок активен ещё '+fmtLeft(S.radar.left_s)+'. Попытка продлит блок. Всё равно?'))return;} if(a==='reserve_test'&&!confirm('Живой резерв номера 2nd-no (тратит капчу если нет reuse). ОК?'))return; + if(a==='captcha_test'&&!confirm('Решить тестовый turnstile 2nd-no.com (тратит капчу). ОК?'))return; if(btn)btn.disabled=true; try{const r=await fetch('/api/'+a,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}); const j=await r.json();alert(JSON.stringify(j,null,1));}catch(e){alert('err: '+e);} @@ -329,6 +341,10 @@ class H(BaseHTTPRequestHandler): 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)) + elif u == "/api/captcha_test": + sys.path.insert(0, ROOT) + from secondno.captcha import test_solve + self._send(200, json.dumps(test_solve(), ensure_ascii=False)) else: self._send(404, '{"err":"nf"}') except Exception as e: @@ -339,7 +355,13 @@ 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) + # Prevent Windows SO_REUSEADDR double-bind (multiple instances on same port). + ThreadingHTTPServer.allow_reuse_address = False + try: + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + except OSError as e: + print(f"FATAL: port {port} busy ({e}). Kill stale dashboard instances first.", flush=True) + sys.exit(1) print(f"river dashboard: http://127.0.0.1:{port}", flush=True) srv.serve_forever() diff --git a/secondno/__init__.py b/secondno/__init__.py index 59e700e..6e28813 100644 --- a/secondno/__init__.py +++ b/secondno/__init__.py @@ -1,5 +1,8 @@ from .client import SecondNo, TempMailLol, GmailForwardInbox, full_cycle, SITEKEY, API, SITE -from .captcha import get_solver, TwoCaptchaTurnstile, SidecarSolver +from .captcha import (get_solver, get_sidecar, get_2captcha, test_solve, captcha_status, + TwoCaptchaTurnstile, SidecarSolver, CaptchaRouter) __all__ = ["SecondNo", "TempMailLol", "GmailForwardInbox", "full_cycle", - "get_solver", "TwoCaptchaTurnstile", "SidecarSolver", "SITEKEY", "API", "SITE"] + "get_solver", "get_sidecar", "get_2captcha", "test_solve", "captcha_status", + "TwoCaptchaTurnstile", "SidecarSolver", "CaptchaRouter", + "SITEKEY", "API", "SITE"] diff --git a/secondno/captcha.py b/secondno/captcha.py index 6662743..1f2407f 100644 --- a/secondno/captcha.py +++ b/secondno/captcha.py @@ -1,14 +1,25 @@ -"""Turnstile solvers for 2nd-no.com reservations. +"""Turnstile solvers for 2nd-no.com reservations (and any Cloudflare turnstile). -Two backends: -1. TwoCaptchaTurnstile — 2captcha.com, method=turnstile. +Backends (tried in order by CaptchaRouter): +1. SidecarSolver — local captcha-solver sidecar (POST {SIDECAR_URL}/solve). + FREE, ~14s/token, requires sidecar running with real_page support. + Health: GET {SIDECAR_URL}/health → 200. +2. TwoCaptchaTurnstile — 2captcha.com, method=turnstile. IMPORTANT: submit ONLY via in.php (res.php returns ERROR_EMPTY_METHOD); - balance check is POST res.php {action:getbalance}, balance lives in 'request' field. - Key source: env TWOCAPTCHA_API_KEY, or data/captcha_keys.json {"keys":[{"key":...,"label":...}]}. -2. SidecarSolver — local captcha-solver sidecar (POST {SIDECAR_URL}/solve), free, - requires the sidecar running with real_page support. + balance check is POST res.php {action:getbalance}, balance lives in 'request'. + Key source (first match wins): + env TWOCAPTCHA_API_KEY + env RUCAPTCHA_KEY + data/secondno/captcha_keys.json {"keys":[{"key":"...","label":"..."}]} + See captcha_keys.example.json for the template. -get_solver(): sidecar if reachable, else 2captcha if a key with balance exists. +CaptchaRouter: tries sidecar first; on failure/timeout falls back to 2captcha. +Retries each backend up to `retries` times before giving up. + +get_solver(): returns a CaptchaRouter (sidecar+2captcha fallback chain). +get_sidecar(): returns SidecarSolver only (no fallback). +get_2captcha(): returns TwoCaptchaTurnstile only (no fallback). +test_solve(sitekey, pageurl): quick smoke test — returns {"ok":bool,"backend":str,"elapsed":float}. """ from __future__ import annotations @@ -19,39 +30,58 @@ import urllib.parse import urllib.request HOME = os.environ.get("SECONDNO_HOME") or os.path.join( - os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data") + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "secondno") KEYS_FILE = os.path.join(HOME, "captcha_keys.json") SIDECAR_URL = os.environ.get("SIDECAR_URL", "http://127.0.0.1:8877") +# 2nd-no.com turnstile sitekey (used by test_solve default) +DEFAULT_SITEKEY = "0x4AAAAAAAh6YYTPTzEcN3Ep" +DEFAULT_PAGEURL = "https://2nd-no.com/" + def _load_2captcha_key(): - env_key = os.environ.get("TWOCAPTCHA_API_KEY", "").strip() - keys = [{"key": env_key, "label": "env"}] if env_key else [] + """Find first 2captcha key with balance > $0.05. Checks env then keys file.""" + candidates = [] + for env_var in ("TWOCAPTCHA_API_KEY", "RUCAPTCHA_KEY"): + v = os.environ.get(env_var, "").strip() + if v: + candidates.append({"key": v, "label": f"env:{env_var}"}) try: d = json.load(open(KEYS_FILE, encoding="utf-8")) - keys += d.get("keys") or ([d] if isinstance(d, dict) and d.get("key") else []) + if isinstance(d, dict): + candidates += d.get("keys") or ([d] if d.get("key") else []) + elif isinstance(d, list): + candidates += [k if isinstance(k, dict) else {"key": str(k)} for k in d] except Exception: pass - for k in keys: + for k in candidates: + key = k.get("key", "").strip() + if not key: + continue try: body = urllib.parse.urlencode( - {"key": k["key"], "action": "getbalance", "json": 1}).encode() + {"key": key, "action": "getbalance", "json": 1}).encode() req = urllib.request.Request("https://2captcha.com/res.php", data=body) r = json.loads(urllib.request.urlopen(req, timeout=20).read().decode()) bal = float(r.get("request", -1)) - print(f"[2captcha] {k.get('label', '?')} balance {bal}", flush=True) + label = k.get("label", "?") + print(f"[2captcha] {label} balance ${bal:.3f}", flush=True) if r.get("status") == 1 and bal > 0.05: - return k["key"] + return key except Exception as e: print("[2captcha] balance check err:", str(e)[:80], flush=True) return "" class TwoCaptchaTurnstile: + """2captcha.com turnstile solver. Submit via in.php, poll via res.php.""" + def __init__(self, key=None): self.key = key or _load_2captcha_key() if not self.key: - raise RuntimeError("no 2captcha key with balance") + raise RuntimeError( + "no 2captcha key with balance — set TWOCAPTCHA_API_KEY or RUCAPTCHA_KEY env, " + f"or add key to {KEYS_FILE} (see captcha_keys.example.json)") def _post(self, url, data, timeout=40): body = urllib.parse.urlencode(data).encode() @@ -67,7 +97,7 @@ class TwoCaptchaTurnstile: if d.get("status") != 1: raise RuntimeError(f"2captcha submit: {d}") task_id = d["request"] - print("[2captcha] task", task_id, flush=True) + print(f"[2captcha] task {task_id}", flush=True) deadline = time.time() + 240 while time.time() < deadline: time.sleep(8) @@ -81,7 +111,15 @@ class TwoCaptchaTurnstile: err = str(r.get("request", "")) if "NOT_READY" not in err: raise RuntimeError(f"2captcha get: {r}") - raise RuntimeError("2captcha timeout") + raise RuntimeError("2captcha timeout (240s)") + + def balance(self): + try: + r = self._post("https://2captcha.com/res.php", + {"key": self.key, "action": "getbalance", "json": 1}) + return float(r.get("request", -1)) if r.get("status") == 1 else -1 + except Exception: + return -1 class SidecarSolver: @@ -102,18 +140,147 @@ class SidecarSolver: def turnstile(self, sitekey, pageurl, action=None, proxy_url=None): import httpx + t0 = time.time() r = httpx.post(self.url + "/solve", json={ "type": "turnstile", "sitekey": sitekey, "url": pageurl, "real_page": True, "timeout_s": 180}, timeout=200) d = r.json() if not d.get("solved") or not d.get("token"): raise RuntimeError("sidecar turnstile fail: " + json.dumps(d)[:200]) - print("[sidecar] turnstile solved in", d.get("elapsed"), flush=True) + elapsed = round(time.time() - t0, 1) + print(f"[sidecar] turnstile solved in {elapsed}s", flush=True) return d["token"] -def get_solver(): +class CaptchaRouter: + """Tries backends in order with retries. Falls back on failure/timeout. + + backends: list of solver instances (SidecarSolver, TwoCaptchaTurnstile, ...). + retries: attempts per backend before moving to next. + """ + + def __init__(self, backends=None, retries=2): + self.backends = backends or [] + self.retries = retries + self.last_backend = None + self.last_error = None + + def turnstile(self, sitekey, pageurl, action=None, proxy_url=None): + errors = [] + for b in self.backends: + name = type(b).__name__ + for attempt in range(1, self.retries + 1): + try: + tok = b.turnstile(sitekey, pageurl, action=action, proxy_url=proxy_url) + if tok: + self.last_backend = name + self.last_error = None + return tok + errors.append(f"{name} attempt {attempt}: empty token") + except Exception as e: + msg = f"{name} attempt {attempt}: {str(e)[:120]}" + errors.append(msg) + print(f"[captcha-router] {msg}", flush=True) + if attempt < self.retries: + time.sleep(3) + self.last_backend = None + self.last_error = "; ".join(errors[-4:]) + raise RuntimeError(f"all captcha backends failed: {self.last_error}") + + def status(self): + """Return dict with backend health info (no secrets).""" + out = [] + for b in self.backends: + name = type(b).__name__ + info = {"backend": name, "alive": False} + if isinstance(b, SidecarSolver): + info["alive"] = b.alive() + info["url"] = b.url + elif isinstance(b, TwoCaptchaTurnstile): + info["alive"] = True # key loaded = alive + info["balance"] = round(b.balance(), 3) + out.append(info) + return out + + +def _build_backends(): + """Build ordered backend list: sidecar (if alive) → 2captcha (if key).""" + backends = [] s = SidecarSolver() if s.alive(): - return s + backends.append(s) + print("[captcha] sidecar alive at", s.url, flush=True) + try: + backends.append(TwoCaptchaTurnstile()) + print("[captcha] 2captcha key loaded", flush=True) + except RuntimeError as e: + print("[captcha] 2captcha unavailable:", str(e)[:80], flush=True) + return backends + + +def get_solver(): + """Returns CaptchaRouter with sidecar+2captcha fallback chain.""" + backends = _build_backends() + if not backends: + raise RuntimeError( + "no captcha backend available — start sidecar (:8877) or set TWOCAPTCHA_API_KEY") + return CaptchaRouter(backends=backends, retries=2) + + +def get_sidecar(): + """Returns SidecarSolver only (no fallback). Raises if not alive.""" + s = SidecarSolver() + if not s.alive(): + raise RuntimeError(f"sidecar not alive at {s.url}") + return s + + +def get_2captcha(): + """Returns TwoCaptchaTurnstile only (no fallback). Raises if no key.""" return TwoCaptchaTurnstile() + + +def test_solve(sitekey=None, pageurl=None): + """Quick smoke test — solve a turnstile and return result dict (no secrets).""" + sitekey = sitekey or DEFAULT_SITEKEY + pageurl = pageurl or DEFAULT_PAGEURL + t0 = time.time() + try: + router = get_solver() + tok = router.turnstile(sitekey, pageurl) + return { + "ok": True, + "backend": router.last_backend, + "elapsed": round(time.time() - t0, 1), + "token_len": len(tok) if tok else 0, + "token_preview": (tok[:8] + "..." + tok[-4:]) if tok and len(tok) > 16 else "***", + } + except Exception as e: + return { + "ok": False, + "elapsed": round(time.time() - t0, 1), + "err": str(e)[:200], + } + + +def captcha_status(): + """Return captcha subsystem status for dashboard (no secrets).""" + sidecar = SidecarSolver() + sc_alive = sidecar.alive() + has_2captcha = False + bal_2captcha = -1 + try: + tc = TwoCaptchaTurnstile() + has_2captcha = True + bal_2captcha = round(tc.balance(), 3) + except Exception: + pass + return { + "sidecar_alive": sc_alive, + "sidecar_url": sidecar.url, + "has_2captcha_key": has_2captcha, + "balance_2captcha": bal_2captcha, + "keys_file": KEYS_FILE, + "keys_file_exists": os.path.isfile(KEYS_FILE), + "ready": sc_alive or has_2captcha, + }