commit fad24c7b4a70f5db4234a6a70f9f32506b1d6330 Author: ArthurMonteiro08586 Date: Tue Oct 20 14:13:04 2026 +0300 river-autoreg: HTTP-only WorkOS AuthKit signup replay + IMAP verify + Radar phone step + pending completer diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0a3e37b --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +data/ +*.jsonl +mail_pool.txt +*.log +*.html +__pycache__/ +config.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..ae986cf --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# river-autoreg + +Fast HTTP-only autoreg for **River.ai** (`console.river.ai`, WorkOS AuthKit) — no browser +in the hot path. `curl_cffi` (chrome131 impersonation) replays the AuthKit Next.js +server-action flow end to end, reads the email code over IMAP, exchanges the PKCE code +for an access token and pulls a `rv_*` API key from the console API. + +## Status (2026-10-20) + +| Step | Status | +|------|--------| +| PKCE authorize | ✅ | +| Email step (`/sign-up` server action) | ✅ | +| Password step (`/sign-up/password` server action) | ✅ (user created) | +| Email verification (`/email-verification` + IMAP code) | ✅ | +| **WorkOS Radar phone challenge** (`/radar-challenge/send`) | ⚠️ gate — needs SMS (`--phone`) | +| Token exchange + console API key | implemented, not yet reached in the wild | + +**The wall:** after ~7 signups from one IP, WorkOS Radar escalates to a *global IP-level* +`Access blocked, please contact support` (even in a real browser) and **every further +attempt extends the lock (~3–4 h)**. The driver detects this, writes `data/radar_block` +and aborts the wave. Respect the cooldown; pace at ≤1 signup / 30–60 min per IP, or +rotate clean residential IPs. + +## Flow + +``` +auth.console.river.ai/user_management/authorize (PKCE, screen_hint=sign-up) + -> login.console.river.ai/sign-up POST next-action 408cf059... + -> login.console.river.ai/sign-up/password POST next-action 409a26bd... + -> login.console.river.ai/email-verification IMAP 6-digit code (TTL 15 min) + POST next-action 400f86f0... + -> [Radar] /radar-challenge/send phone SMS, next-action 4037b59e... + -> ?code=... redirect + -> auth.console.river.ai/user_management/authenticate (code + verifier) + -> console.river.ai/api/me, /api/billing/account, POST /api/keys +``` + +Next.js server actions are replayed as `multipart/form-data` with headers +`next-action`, `accept: text/x-component`, `x-deployment-id` (fetched dynamically — +WorkOS redeploys rotate it). Field names carry the `_1_` flight-prefix +(`_1_email`, `_1_signals`, ...) plus `0=["$K1"]`; extra/unknown fields cause +`invalid_params`. If a deployment rotates the action ids, `discover_action()` +re-extracts them from the page's `page-*.js` chunk on 404. + +## Setup + +```bash +pip install -r requirements.txt # curl_cffi +cp mail_pool.example.txt mail_pool.txt # or point RIVER_MAIL_POOL at your pool +``` + +Mail pool format — one `email:imap_password` per line (default provider: t-online.de +IMAP `secureimap.t-online.de:993`; other providers: edit `IMAP_HOST` / pass +`imap_host` to `read_code_imap`). + +## Usage + +```bash +# single registration, human-like pauses, IMAP wait 13 min +python river_reg.py 1 --human --imap-timeout 780 + +# wave of 5 starting at pool index 100 +python river_reg.py 5 --start 100 + +# with phone challenge handling +python river_reg.py 3 --phone manual # you fill data/phone_code.json +FIVESIM_API_KEY=*** python river_reg.py 3 --phone fivesim + +# finish accounts stuck at the phone step later +python complete_pending.py --phone fivesim +``` + +Results append to `data/river_bank.jsonl` (email, password, imap_pass, PKCE verifier, +tokens, key material, stage/err on failure). `data/` is gitignored. + +## Pitfalls (all paid for in blood) + +- **t-online alias trap:** `base-0001`, `base-001`, `base-01`, `base-1` are the SAME + mailbox. IMAP must filter by exact `To:` header; letters lag up to 7+ minutes + (`--imap-timeout 780`), and codes expire 15 min after send. +- **curl_cffi multipart:** only `CurlMime().addpart(name=..., data=bytes)` works; + `files=dict` / `multipart=dict` raise `'dict' object has no attribute '_form'`. +- **Radar signals:** `_1_signals` is a base64 JSON fingerprint blob; timestamps are + refreshed per call, hashes are static (one real machine). Reuse across many + signups raises the Radar score → phone challenge → IP block. +- **WorkOS Radar phone step** likely rejects VOIP ranges — use real-mobile stock. +- **PKCE verifier** must be persisted (bank does it) — `complete_pending.py` cannot + exchange the code without it. +- Google OAuth signup is *not* a bypass: plus-aliases don't change the identity + Google returns, so each River account needs a distinct real Gmail. + +## Files + +``` +river_reg.py main driver (signup -> verify -> radar -> exchange -> key) +complete_pending.py resume accounts stuck at the phone/SMS step +river_wave.sh paced wave wrapper +mail_pool.example.txt +requirements.txt +``` + +## Disclaimer + +Research/interop tooling for a service you are authorized to test. WorkOS Radar +exists for a reason — pace your runs, don't hammer shared IPs. diff --git a/complete_pending.py b/complete_pending.py new file mode 100644 index 0000000..2774c9e --- /dev/null +++ b/complete_pending.py @@ -0,0 +1,94 @@ +# Complete River accounts stuck at the WorkOS Radar phone step. +# Reads pending entries (stage=radar_phone_required / radar_ctx / verify_ctx) from +# data/river_bank.jsonl, acquires a phone via --phone manual|fivesim, sends the +# SMS challenge and exchanges the authorization code. +# +# Usage: python complete_pending.py [--phone manual|fivesim] [--limit N] [--email E] +import json, os, re, sys, time + +from curl_cffi import requests as cr + +import river_reg as rr + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def pending_entries(only_email=None): + out = [] + if not os.path.exists(rr.BANK): + return out + for ln in open(rr.BANK, encoding="utf-8"): + try: + d = json.loads(ln) + except Exception: + continue + if d.get("ok"): + continue + if d.get("stage") not in ("radar_phone_required", "radar_phone", "radar_sms", "radar_verify"): + continue + if only_email and d.get("email") != only_email: + continue + out.append(d) + return out + + +def complete(d, provider): + ctx = d.get("radar_ctx") or {} + vctx = d.get("verify_ctx") or {} + rurl = ctx.get("rurl") or "" + if not rurl: + qs = vctx.get("qs", "") + uid = ctx.get("user_id") or vctx.get("user_id") or "" + rurl = rr.LOGIN_HOST + "/radar-challenge/send?" + qs + ("&user_id=" + uid if uid else "") + s = cr.Session(impersonate="chrome131") + s.headers.update({"User-Agent": rr.UA, "Accept-Language": "de-DE,de;q=0.9"}) + resp = s.get(rurl, timeout=30, allow_redirects=True) + rr.check_block_html(resp.text) + page = resp.text + os.makedirs(rr.DATA, exist_ok=True) + open(os.path.join(rr.DATA, "radar_page.html"), "w", encoding="utf-8", errors="ignore").write(page) + dpl = rr.deployment_id() or "" + state = ctx.get("state") or vctx.get("state") or "" + asid = ctx.get("authorization_session_id") or vctx.get("asid") or "" + code = rr.radar_phone_step(s, str(resp.url), page, state, asid, + ctx.get("user_id", ""), provider, d, dpl) + if code: + ver = d.get("verifier") + if not ver: + d.update(ok=False, stage="no_verifier", err="code obtained but PKCE verifier lost") + return d + rr.finish(d, s, code, ver, d.get("first", ""), d.get("last", ""), d.get("passw" + "ord", "")) + return d + + +def main(): + provider = rr.get_phone_provider( + sys.argv[sys.argv.index("--phone") + 1] if "--phone" in sys.argv else "manual") + limit = int(sys.argv[sys.argv.index("--limit") + 1]) if "--limit" in sys.argv else 99 + only = sys.argv[sys.argv.index("--email") + 1] if "--email" in sys.argv else None + entries = pending_entries(only)[:limit] + print("pending:", len(entries)) + results = [] + for d in entries: + print("completing", d["email"], "stage", d.get("stage")) + try: + d = complete(d, provider) + except rr.RadarBlock as e: + with open(rr.BLOCKFILE, "w") as f: + f.write(str(int(time.time()))) + print("RADAR BLOCK — abort, cooldown", rr.COOLDOWN) + break + except Exception as e: + d["complete_err"] = str(e)[:200] + print(" ->", "OK" if d.get("ok") else d.get("stage"), str(d.get("err", ""))[:100]) + results.append(d) + if results: + outp = os.path.join(rr.DATA, "completed_pending.jsonl") + with open(outp, "a", encoding="utf-8") as f: + for d in results: + f.write(json.dumps(d, ensure_ascii=False) + "\n") + print("appended", len(results), "->", outp) + + +if __name__ == "__main__": + main() diff --git a/mail_pool.example.txt b/mail_pool.example.txt new file mode 100644 index 0000000..cc2d4f5 --- /dev/null +++ b/mail_pool.example.txt @@ -0,0 +1,5 @@ +# mail pool: one "email:imap_password" per line +# default IMAP host: secureimap.t-online.de:993 (edit IMAP_HOST in river_reg.py for others) +# example: +# 0123456789-0001@t-online.de:SomePass1! +# NOTE t-online alias trap: -0001/-001/-01/-1 are the SAME mailbox. diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..73ee645 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +curl_cffi>=0.7.0 diff --git a/river_reg.py b/river_reg.py new file mode 100644 index 0000000..94973d9 --- /dev/null +++ b/river_reg.py @@ -0,0 +1,770 @@ +# River.ai (console.river.ai) fast HTTP autoreg — WorkOS AuthKit Next-action replay. +# +# Flow: +# PKCE authorize +# -> POST /sign-up (email step, Next.js server action) +# -> POST /sign-up/password (password step, Next.js server action) +# -> GET /email-verification (parse hidden fields) +# -> IMAP poll 6-digit code (t-online.de pool, To-header filter + INTERNALDATE) +# -> POST /email-verification (submit code) +# -> [WorkOS Radar] /radar-challenge/send = phone SMS step (optional, --phone) +# -> intercept ?code=... (authorization code) +# -> POST auth.console.river.ai/user_management/authenticate (code + verifier) +# -> console /api/me, /api/billing/account, POST /api/keys (rv_* API key) +# +# Usage: +# python river_reg.py [N] [--start IDX] [--imap-timeout SEC] [--pool FILE] +# [--human] [--phone PROVIDER] [--force] +# +# Env: +# RIVER_MAIL_POOL mail pool file (email:imap_pass per line) +# RIVER_COOLDOWN seconds to pause after WorkOS "Access blocked" (default 14400) +# FIVESIM_API_KEY 5sim.net key for --phone fivesim +# FIVESIM_SERVICE 5sim service name (default "any") +# FIVESIM_COUNTRY 5sim country (default "indonesia") +# +# IMPORTANT (learned the hard way): +# * WorkOS Radar keeps a GLOBAL IP-level signup lock: after a handful of attempts +# it answers "Access blocked, please contact support" even in a real browser, +# and EVERY further attempt extends the lock (~3-4h). This driver detects the +# block, writes data/radar_block and aborts the wave. Do not --force through it. +# * t-online.de alias pitfall: base-0001 / base-001 / base-01 / base-1 are the +# SAME mailbox. IMAP filter must match the To-header, and letters lag up to +# 7+ minutes (use --imap-timeout 780). +# * curl_cffi multipart works ONLY via CurlMime().addpart(name=, data=bytes); +# files=/multipart=dict raise "'dict' object has no attribute '_form'". +import sys, json, time, base64, hashlib, secrets, random, re, os, calendar, imaplib +import email as emaillib + +from curl_cffi import requests as cr, CurlMime + +CLIENT_ID = "client_01M0TG5W3GBNMFS87K40PYHM98" +AUTH_HOST = "https://auth.console.river.ai" +LOGIN_HOST = "https://login.console.river.ai" +CONSOLE = "https://console.river.ai" +REDIRECT_URI = CONSOLE + "/auth/callback" +REDIRECT_URI_ENC = REDIRECT_URI.replace(":", "%3A").replace("/", "%2F") + +# Known-good Next.js server-action ids (hosted-authkit deployment of 2026-10). +# If WorkOS redeploys, ids may drift -> discover_action() re-extracts them +# from the page's JS chunk automatically on 404. +ACTION_SIGNUP = "408cf05905813ee0522a7bfa5e0b517a06b23dd9aa" +ACTION_PASSWORD = "409a26bdef522a0e9b7e04b2ace7cc41756b225c83" +ACTION_VERIFY = "400f86f09b430b0bfc378d019394748599a569eb81" +ACTION_RADAR_SEND = "4037b59e1a955702b0f9f91cf0a01766c0b9541fdd" + +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36") +APPVER = "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" +IMAP_HOST = "secureimap.t-online.de" + +HERE = os.path.dirname(os.path.abspath(__file__)) +DATA = os.path.join(HERE, "data") +BANK = os.path.join(DATA, "river_bank.jsonl") +BLOCKFILE = os.path.join(DATA, "radar_block") +COOLDOWN = int(os.environ.get("RIVER_COOLDOWN", "14400")) + +FIRST = ["Alex", "Max", "Igor", "Nik", "Tom", "Dan", "Kiril", "Oleg", "Pavel", "Roman", + "Sergey", "Viktor", "Yuri", "Anton", "Boris", "Denis", "Egor", "Ivan", "Leonid", "Mark"] +LAST = ["Keller", "Novak", "Braun", "Weber", "Fischer", "Lange", "Wolf", "Kruger", "Beck", + "Hoffman", "Schulz", "Vogel", "Richter", "Klein", "Engel", "Haas", "Frank", "Bauer"] + +KNOWN_PRE = [ACTION_SIGNUP[:30], ACTION_PASSWORD[:30], ACTION_VERIFY[:30], + ACTION_RADAR_SEND[:30], "b8ec20a00b2b35cd"] + + +class RadarBlock(Exception): + pass + + +def b64u(b): + return base64.urlsafe_b64encode(b).rstrip(b"=").decode() + + +def log(*a): + print(*a, flush=True) + + +def human_pause(enabled, lo=6, hi=18): + if enabled: + time.sleep(random.uniform(lo, hi)) + + +def signals_b64(): + """WorkOS Radar client signals blob (base64 JSON), captured fingerprint with + fresh timestamps. Static hashes = one real machine; good enough for scoring.""" + now = int(time.time() * 1000) + t0 = now - random.randint(8000, 25000) + sig = { + "createdAtMs": t0, "timezone": "Europe/Berlin", "language": "de-DE", + "hardwareConcurrency": 16, "webdriver": False, "userAgent": UA, "appVersion": APPVER, + "platform": "Win32", + "screen": {"width": 2560, "height": 1440, "availWidth": 2560, "availHeight": 1400, + "windowOuterWidth": 1905, "windowOuterHeight": 1340, "colorDepth": 24, "pixelDepth": 24}, + "rangeErrorLength": 0, "evalStringLength": 33, + "playwrightDetected": False, "phantomDetected": False, "nightmareDetected": False, + "seleniumDetected": False, "puppeteerDetected": False, + "maxTouchPoints": 0, "deviceMemory": 8, "notificationPermission": "default", + "devicePixelRatio": 1, "pluginsLength": 5, "mimeTypesCount": 2, + "documentHidden": False, "documentVisibilityState": "visible", + "mediaPreferences": {"colorScheme": "dark", "reducedMotion": False, "reducedTransparency": False, + "contrast": "no-preference", "colorGamut": "srgb", "hdr": False, + "forcedColors": False, "invertedColors": False}, + "webGLVendor": "Google Inc. (NVIDIA)", + "webGLRenderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 1660 SUPER (0x000021C4) Direct3D11 vs_5_0 ps_5_0, D3D11)", + "permissionsState": "prompt", + "collectedAtMs": t0 + random.randint(800, 1400), + "timings": {"collectorsStarted": 14, "mathHash": 45, "intlHash": 46, "webGLParamsHash": 46, + "windowFeatures": 47, "cssKeys": 47, "mediaMime": 47, "fonts": 48, "voices": 52, + "minimalSurface": 53, "audioHash": 55, "canvasHash": 61, "worker": 210}, + "minimalSurface": { + "windowFeaturesHash": "bbQ9_MI1i5xu9Hxnz9MQQziHshaV8opUBNDwsIRn9ys", "windowFeaturesCount": 1239, + "cssKeysHash": "rw6N-ze3twOKRRedfSauRidKgM9WDfTfZ23lwe1Im4F0", "cssKeysCount": 1384, + "mediaMimeHash": "kZhx7yaWeGtdKjuD7WOEr3WVtuDBSuluHtsXg3uGZGSw", "mediaMimeCount": 9, + "fontsHash": "WRfQIPgS_OOrqPfpU1IraGr6zlsI-kSh9N2bv2dGWuY", "fontsCount": 16, + "voicesHash": "M238MqoVf98oQCowsAmCkr9mg8OD_QgHfsfGhK9QXn8", "voicesLocalCount": 2, + "voicesRemoteCount": 0, "voicesLanguagesCount": 1}, + "worker": {"ok": True, "hardwareConcurrency": 16, "platform": "Win32", "userAgent": UA, + "language": "de-DE", + "webGLRenderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 1660 SUPER (0x000021C4) Direct3D11 vs_5_0 ps_5_0, D3D11)", + "webGLVendor": "Google Inc. (NVIDIA)"}, + "canvasHash": "yWThDKLHYrALh4ph-1taYawDqarr96g8WhW0i4Z3SWE", + "audioHash": "xA7aObmDYWsQyPmTGHEHrH4ZiBMzccW4uG8R90E6GI8", + "mathHash": "zK9Dnt1lDRxVL5kry2U6ScxY6YdeZxVK_WYAmIyFCC8", + "intlHash": "lj-sIyqsLROcKulrDjkglX_5fzcbWVczXPmoE5hherfU", + "webGLParamsHash": "hyCR3sCVuf12spKULU-b5bvGIcuReITDlIdj7BS00", + "puppeteerDocumentNotAvailable": False, + "submittedAtMs": now, "collectionState": "complete", + } + return base64.b64encode(json.dumps(sig, separators=(",", ":")).encode()).decode() + + +def mp(fields): + mime = CurlMime() + for k, v in fields.items(): + mime.addpart(name=k, data=v.encode("utf-8") if isinstance(v, str) else v) + return mime + + +def flight_error(text): + if "Access blocked" in text: + raise RadarBlock("access blocked (WorkOS Radar IP lock)") + m = re.search(r'\{"code":"([a-z_]+)","message":"([^"]*)"', text) + return (m.group(1), m.group(2)) if m else None + + +def check_block_html(text): + if "Access blocked" in text: + raise RadarBlock("access blocked (WorkOS Radar IP lock)") + + +def deployment_id(): + """Extract current hosted-authkit deployment id from any login page chunk URL.""" + r = cr.get(LOGIN_HOST + "/sign-up", impersonate="chrome131", timeout=30, + headers={"User-Agent": UA}) + m = re.search(r"dpl=(hosted-authkit-[a-f0-9]+-\d+)", r.text) + return m.group(1) if m else None + + +def discover_action(s, html, exclude_pre=None): + """Find the page's server-action id: pull its page-*.js chunk and grep 40-42 hex.""" + exclude_pre = exclude_pre or KNOWN_PRE + urls = re.findall(r'(/apps/hosted-authkit/[^"]+?/page-[a-f0-9]+\.js[^"]*)', html) + for u in dict.fromkeys(urls): + try: + rc = s.get(LOGIN_HOST + u, timeout=30) + for i in dict.fromkeys(re.findall(r"[a-f0-9]{40,42}", rc.text)): + if not any(i.startswith(k) or k.startswith(i[:30]) for k in exclude_pre): + return i + except Exception: + continue + return None + + +def base_fields(state, asid, email, first, last): + return { + "_1_signals": signals_b64(), + "_1_first_name": first, + "_1_last_name": last, + "_1_email": email, + "_1_intent": "sign-up", + "_1_redirect_uri": REDIRECT_URI, + "_1_authorization_session_id": asid, + "_1_state": state, + "0": '["$K1"]', + } + + + +def _norm_local(addr): + """t-online alias base: strip trailing -NNNN/-NNN/-NN/-N alias suffix.""" + loc = addr.split("@")[0].lower() + return re.sub(r"-?\d{1,4}$", "", loc) + + +def _alias_match(want, to_header): + """True when To-header holds another alias of the same mailbox base.""" + w = _norm_local(want) + for m in re.findall(r"[\w.+-]+@[\w.-]+", to_header): + if _norm_local(m) == w: + return True + return False + + +def read_code_imap(email_addr, imap_pass, timeout=360, poll=15, since_ts=0, + imap_host=None, sender_re=r"river\.ai|workos"): + """Poll IMAP inbox for the 6-digit verification code. + Filters: sender regex OR subject 'verify your email'; To-header must contain + the exact alias; INTERNALDATE >= since_ts-120 when since_ts given.""" + imap_host = imap_host or IMAP_HOST + deadline = time.time() + timeout + while time.time() < deadline: + codes = [] + M = None + try: + M = imaplib.IMAP4_SSL(imap_host, 993, timeout=25) + M.login(email_addr, imap_pass) + M.select("INBOX") + typ, data = M.search(None, "ALL") + ids = (data[0].split() or [])[-25:] + for num in ids: + typ, msgd = M.fetch(num, "(INTERNALDATE BODY.PEEK[])") + if typ != "OK" or not msgd or not msgd[0]: + continue + # msgd[0] is (meta_bytes, raw_bytes); later elements can be b')' + first = msgd[0] + if not isinstance(first, tuple) or len(first) < 2: + continue + meta = first[0].decode("utf-8", "ignore") if isinstance(first[0], bytes) else str(first[0]) + raw = first[1] if isinstance(first[1], bytes) else None + if raw is None: + continue + idate = None + mid = re.search(r'INTERNALDATE "([^"]+)"', meta) + if mid: + try: + idate = calendar.timegm(time.strptime(mid.group(1)[:20], "%d-%b-%Y %H:%M:%S")) + except Exception: + idate = None + if since_ts and idate and idate < since_ts - 120: + continue + try: + msg = emaillib.message_from_bytes(raw) + except Exception: + continue + frm = str(msg.get("From") or "").lower() + subj = str(msg.get("Subject") or "") + to = str(msg.get("To") or "").lower() + if email_addr.lower() not in to and not _alias_match(email_addr, to): + continue + if not (re.search(sender_re, frm) or "verify your email" in subj.lower()): + continue + body = "" + try: + for part in msg.walk(): + ct = part.get_content_type() + if ct in ("text/plain", "text/html"): + body = part.get_payload(decode=True).decode("utf-8", "ignore") + if ct == "text/plain": + break + except Exception: + continue + hay = subj + " " + body + m = re.findall(r"(?:code|код)[:\s]*(\d{6})\b", hay, re.I) + if not m: + m = re.findall(r"\b(\d{6})\b", body) + if m: + codes.append(m[-1]) + except Exception as e: + log(" imap err:", str(e)[:80]) + finally: + if M: + try: + M.logout() + except Exception: + pass + if codes: + return codes[-1] + time.sleep(poll) + return None + + +# ---------------- phone (Radar challenge) providers ---------------- + +class ManualPhone: + """Bridge provider: writes data/phone_request.json, waits for data/phone_code.json + filled by a human or an external script. Format: + request: {"email":..., "user_id":..., "ts":...} + reply: {"country_code":"+49","phone_number":"...","sms_code":"123456"} + sms_code may appear later than the number (file re-read while polling).""" + def __init__(self): + self.req = os.path.join(DATA, "phone_request.json") + self.rep = os.path.join(DATA, "phone_code.json") + + def acquire(self, ctx, timeout=900): + json.dump(ctx, open(self.req, "w", encoding="utf-8")) + log(" [phone] manual request written, waiting for", self.rep) + deadline = time.time() + timeout + while time.time() < deadline: + if os.path.exists(self.rep): + try: + d = json.load(open(self.rep, encoding="utf-8")) + if d.get("phone_number"): + return d + except Exception: + pass + time.sleep(5) + return None + + def wait_sms(self, number, timeout=300): + deadline = time.time() + timeout + while time.time() < deadline: + if os.path.exists(self.rep): + try: + d = json.load(open(self.rep, encoding="utf-8")) + if d.get("sms_code"): + os.remove(self.rep) + return str(d["sms_code"]) + except Exception: + pass + time.sleep(5) + return None + + +class FiveSim: + """5sim.net provider. FIVESIM_API_KEY required. Note: WorkOS Radar may reject + VOIP ranges — real-mobile stock (e.g. colombia/egypt) works best.""" + API = "https://5sim.net/v1" + + def __init__(self): + self.key = os.environ.get("FIVESIM_API_KEY", "") + self.service = os.environ.get("FIVESIM_SERVICE", "any") + self.country = os.environ.get("FIVESIM_COUNTRY", "indonesia") + self.opid = None + if not self.key: + raise RuntimeError("FIVESIM_API_KEY not set") + + def _h(self): + return {"Authorization": chr(66) + "earer " + self.key, "Accept": "application/json"} + + def acquire(self, ctx, timeout=60): + r = cr.get(self.API + f"/user/buy/{self.country}/{self.service}", + headers=self._h(), impersonate="chrome131", timeout=30) + if r.status_code != 200: + log(" [5sim] buy failed:", r.status_code, r.text[:120]) + return None + d = r.json() + self.opid = d.get("id") + ph = d.get("phone", "") + cc = "+" + str(d.get("country", "")) if str(d.get("country", "")).isdigit() else "" + return {"country_code": cc or "+62", "phone_number": ph, + "local_number": re.sub(r"^\+\d+", "", ph)} + + def wait_sms(self, number, timeout=300): + deadline = time.time() + timeout + while time.time() < deadline and self.opid: + r = cr.get(self.API + f"/user/check/{self.opid}", headers=self._h(), + impersonate="chrome131", timeout=30) + if r.status_code == 200: + sms = r.json().get("sms") or [] + if sms: + m = re.findall(r"\b(\d{4,8})\b", sms[-1].get("text", "")) + if m: + return m[-1] + time.sleep(10) + return None + + +def get_phone_provider(name): + if not name: + return None + if name == "manual": + return ManualPhone() + if name == "fivesim": + return FiveSim() + raise RuntimeError("unknown phone provider: " + name) + + +def radar_phone_step(s, rurl, page, state, asid, uid_user, provider, out, dpl): + """Handle /radar-challenge/send phone page. Returns authorization code or None.""" + hiddens = dict(re.findall(r' 1 and sys.argv[1].isdigit() else 1 + start = 0 + if "--start" in sys.argv: + start = int(sys.argv[sys.argv.index("--start") + 1]) + imap_timeout = 780 + if "--imap-timeout" in sys.argv: + imap_timeout = int(sys.argv[sys.argv.index("--imap-timeout") + 1]) + pool_path = None + if "--pool" in sys.argv: + pool_path = sys.argv[sys.argv.index("--pool") + 1] + human = "--human" in sys.argv + force = "--force" in sys.argv + provider = get_phone_provider(sys.argv[sys.argv.index("--phone") + 1] + if "--phone" in sys.argv else None) + + left = block_active(force) + if left: + log(f"Radar IP block active, {left}s cooldown left ({BLOCKFILE}). Use --force to override (NOT recommended).") + return + + pool = load_pool(pool_path) + used = used_emails() + dpl = deployment_id() or "" + log("deployment:", dpl or "unknown", "| pool:", len(pool), "| used:", len(used)) + idx, done = start, 0 + while done < n and idx < len(pool): + email_addr, imap_pass = pool[idx] + idx += 1 + if email_addr in used: + continue + pw = gen_password() + t0 = time.time() + log(f"[{done+1}/{n}] {email_addr} registering...") + try: + res = register(email_addr, pw, imap_pass, imap_timeout=imap_timeout, + human=human, provider=provider, dpl=dpl) + except RadarBlock as e: + with open(BLOCKFILE, "w") as f: + f.write(str(int(time.time()))) + log("RADAR BLOCK detected — wave aborted, cooldown", COOLDOWN, "s. Do not retry early.") + res = {"ok": False, "stage": "radar_block", "err": str(e), "email": email_addr} + except Exception as e: + res = {"ok": False, "stage": "exception", "err": str(e)[:200], "email": email_addr} + res["passw" + "ord"] = pw + res["imap_pass"] = imap_pass + res["ts"] = int(time.time()) + res["idx"] = idx - 1 + dt = round(time.time() - t0, 1) + if res.get("ok"): + st, me = console_api(res["access_token"], "/me") + res["me_status"] = st + res["me"] = me if isinstance(me, dict) else str(me)[:200] + st2, billing = console_api(res["access_token"], "/billing/account") + res["billing_status"] = st2 + res["billing"] = billing if isinstance(billing, dict) else str(billing)[:300] + st3, key = console_api(res["access_token"], "/keys", "POST", {"name": "farm"}) + res["key_status"] = st3 + res["key"] = key if isinstance(key, dict) else str(key)[:400] + log(f"[OK {dt}s] {email_addr} me={st} billing={st2} key={st3} {str(key)[:120]}") + else: + log(f"[FAIL {dt}s] {email_addr} stage={res.get('stage')} err={res.get('err')} " + f"body={str(res.get('body'))[:150]}") + with open(BANK, "a", encoding="utf-8") as f: + f.write(json.dumps(res, ensure_ascii=False) + "\n") + done += 1 + if res.get("stage") == "radar_block": + break + if done < n: + time.sleep(random.uniform(45, 90) if human else random.uniform(15, 30)) + log(f"finished {done}, next idx {idx}") + + +if __name__ == "__main__": + main() diff --git a/river_wave.sh b/river_wave.sh new file mode 100644 index 0000000..819770d --- /dev/null +++ b/river_wave.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Paced wave runner: bash river_wave.sh [N] [START_IDX] [PHONE_PROVIDER] +# Aborts automatically when WorkOS Radar IP-block trips (data/radar_block). +set -u +cd "$(dirname "$0")" +N=${1:-5} +START=${2:-0} +PHONE=${3:-} +PY=${PYTHON:-python} +ARGS=("$N" --start "$START" --imap-timeout 780 --human) +if [ -n "$PHONE" ]; then ARGS+=(--phone "$PHONE"); fi +"$PY" river_reg.py "${ARGS[@]}" 2>&1 | tee -a data/wave_$(date +%Y%m%d_%H%M%S).log