# -*- coding: utf-8 -*- """wr_reg.py — авторег withruntime.com через реальный Chrome (CDP). usage: wr_reg.py send — открыть sign-in, ввести email, отправить код wr_reg.py verify — ввести код, дождаться сессии wr_reg.py key — создать API-ключ, вывести его wr_reg.py usage — GET /v1/usage сохранённым ключом wr_reg.py whoami — состояние страницы """ import json, os, re, subprocess, sys, time CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe" PROFDIR = r"C:\Users\User\tmp\wrprof" PORT = 9223 STATE = r"C:\Users\User\tmp\wr_state.json" KEYS = r"C:\Users\User\tmp\wr_keys.jsonl" BASE = "https://withruntime.com" PY = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe" ENV = dict(os.environ) def log(*a): print(*a, flush=True) def ensure_chrome(): import urllib.request try: urllib.request.urlopen("http://127.0.0.1:%d/json/version" % PORT, timeout=3).read() log("chrome: already up") return except Exception: pass os.makedirs(PROFDIR, exist_ok=True) args = [CHROME, "--remote-debugging-port=%d" % PORT, "--user-data-dir=" + PROFDIR, "--no-first-run", "--no-default-browser-check", "--disable-features=Translate", "--window-size=1280,900", "about:blank"] DETACHED = 0x00000008 | 0x00000200 subprocess.Popen(args, creationflags=DETACHED, close_fds=True) for _ in range(40): time.sleep(0.5) try: urllib.request.urlopen("http://127.0.0.1:%d/json/version" % PORT, timeout=2).read() log("chrome: launched") return except Exception: continue raise SystemExit("chrome launch failed") def page_new(p): ctx = p.contexts[0] if p.contexts else p.new_context() pages = [x for x in ctx.pages if x.url not in ("", "about:blank")] if pages: return ctx, pages[-1] for pg in ctx.pages: if pg.url == "about:blank": return ctx, pg return ctx, ctx.new_page() def kill_prof_chrome(): try: import psutil except Exception: return for pr in psutil.process_iter(["pid", "name", "cmdline"]): try: if pr.info["name"] and "chrome" in pr.info["name"].lower(): cl = " ".join(pr.info["cmdline"] or []) if "wrprof" in cl and str(pr.info["pid"]) != str(os.getpid()): pr.kill() except Exception: continue def connect(pw): last = None for attempt in range(4): try: ensure_chrome() br = pw.chromium.connect_over_cdp("http://127.0.0.1:%d" % PORT, timeout=15000) ctx, pg = page_new(br) pg.set_default_timeout(30000) return br, ctx, pg except Exception as e: last = e log("connect retry", attempt, str(e)[:120]) kill_prof_chrome() time.sleep(3) raise SystemExit("cdp connect failed: %s" % last) def main(): cmd = sys.argv[1] from playwright.sync_api import sync_playwright with sync_playwright() as pw: br, ctx, pg = connect(pw) if cmd == "whoami": log("URL:", pg.url) log("TEXT:", pg.inner_text("body")[:800]) return if cmd == "send": alias = sys.argv[2] pg.goto(BASE + "/sign-in", wait_until="domcontentloaded") time.sleep(2) pg.reload(wait_until="domcontentloaded") time.sleep(3) cw = pg.get_by_role("button", name="Continue with email") try: cw.click(no_wait_after=True, timeout=8000) except Exception as e: log("cw click fallback:", str(e)[:80]) cw.evaluate("e=>e.click()") time.sleep(2) form = pg.locator("form:has(input#cloud-email)") form.locator("input#cloud-email").fill(alias) time.sleep(0.5) btn = form.locator("button[type=submit]") log("btn text before:", btn.inner_text()) for i in range(40): if btn.get_attribute("disabled") is None: break time.sleep(1) log("tsr:", pg.eval_on_selector("input[name=cf-turnstile-response]", "e=>e.value.length") if pg.query_selector("input[name=cf-turnstile-response]") else "no-input") log("btn text:", btn.inner_text(), "disabled:", btn.get_attribute("disabled")) btn.click() time.sleep(5) log("URL:", pg.url) log("TEXT:", pg.inner_text("body")[:600]) return if cmd == "auto": alias = sys.argv[2] pg.goto(BASE + "/sign-in", wait_until="domcontentloaded") time.sleep(2) pg.reload(wait_until="domcontentloaded") time.sleep(3) cw = pg.get_by_role("button", name="Continue with email") try: cw.click(no_wait_after=True, timeout=8000) except Exception as e: log("cw click fallback:", str(e)[:80]) cw.evaluate("e=>e.click()") time.sleep(2) form = pg.locator("form:has(input#cloud-email)") form.locator("input#cloud-email").fill(alias) btn = form.locator("button[type=submit]") for i in range(110): try: tx = btn.inner_text() dis = btn.get_attribute("disabled") except Exception: tx, dis = "", None if "Sending" not in tx and dis is None: break time.sleep(1) log("sendbtn:", tx, "disabled:", dis) min_ts = int(time.time()) - 5 try: btn.click(no_wait_after=True, timeout=10000) log("clicked send") except Exception as e: log("click err:", str(e)[:120]) btn.evaluate("e=>e.click()") log("clicked send via js") ok = False for i in range(20): time.sleep(2) if "Check your email" in pg.inner_text("body"): ok = True break log("code_requested:", ok) if not ok: log("TEXT:", pg.inner_text("body")[:400]) return code = None for i in range(6): r = subprocess.run(["ssh", "-o", "ConnectTimeout=15", "root@144.31.34.147", "cd /root && timeout 60 python3 wr_code2.py '%s' %d 55" % (alias, min_ts)], capture_output=True, text=True, timeout=120) m = re.search(r"CODE=(\w{6})", r.stdout or "") if m: code = m.group(1) break log("code poll", i, (r.stdout or "").strip()[-80:]) time.sleep(5) log("code:", code) if not code: return codeel = pg.locator("input#cloud-code") codeel.click() codeel.fill(code) time.sleep(0.6) log("FIELDS:", pg.eval_on_selector_all("input", "els=>els.filter(e=>e.type!='hidden').map(e=>e.id+'='+e.value).join(' | ')")) codeel.press("Enter") time.sleep(9) log("URL:", pg.url) log("TEXT:", pg.inner_text("body")[:700]) try: ctx.storage_state(path=STATE) except Exception as e: log("state err", e) return if cmd == "finish": alias, code = sys.argv[2], sys.argv[3] pg.fill("input#cloud-email", alias) time.sleep(0.4) pg.fill("input#cloud-code", code) time.sleep(0.6) log("FIELDS:", pg.eval_on_selector_all("input", "els=>els.filter(e=>e.type!='hidden').map(e=>e.id+'='+e.value).join(' | ')")) pg.locator("input#cloud-code").press("Enter") time.sleep(9) log("URL:", pg.url) log("TEXT:", pg.inner_text("body")[:900]) try: ctx.storage_state(path=STATE) log("state saved") except Exception as e: log("state err", e) return if cmd == "type": code = sys.argv[2] log("URL:", pg.url) info = pg.eval_on_selector_all("input", "els=>els.map(e=>({id:e.id,type:e.type,ml:e.maxLength,name:e.name,ph:e.placeholder,vis:!!e.offsetParent}))") log("INPUTS:", json.dumps(info)) tgt = None for e in info: if e["vis"] and e["type"] != "email" and e["type"] != "hidden": tgt = e break if tgt is None: log("NO_CODE_INPUT"); return sel = ("#%s" % tgt["id"]) if tgt["id"] else "input[type=%s]:visible" % tgt["type"] el = pg.locator(sel).first el.click() el.type(code, delay=140) time.sleep(1) log("FILLED:", pg.eval_on_selector_all("input", "els=>els.map(e=>e.id+':'+e.value).join(' | ')")) clicked = False for b in pg.locator("button[type=submit]").all(): try: tx = b.inner_text().strip() if b.get_attribute("disabled") is None and tx.lower().startswith(("continue", "sign", "verif")): b.click(); clicked = True; log("clicked:", tx); break except Exception: pass if not clicked: try: pg.keyboard.press("Enter"); log("pressed Enter") except Exception: pass time.sleep(9) log("URL:", pg.url) log("TEXT:", pg.inner_text("body")[:800]) try: ctx.storage_state(path=STATE) log("state saved") except Exception as e: log("state err", e) return if cmd == "verify": code = sys.argv[2] log("URL:", pg.url) log("TEXT0:", pg.inner_text("body")[:300]) boxes = pg.locator("input:visible") n = boxes.count() log("visible inputs:", n) filled = False for i in range(n): el = boxes.nth(i) t = (el.get_attribute("type") or "").lower() ml = el.get_attribute("maxlength") if t in ("tel", "text", "number") and (ml in ("1", "6", None)): try: el.click() el.type(code, delay=120) filled = True log("typed into", i, t, ml) break except Exception as e: log("type err", i, e) if not filled: pg.keyboard.type(code, delay=120) time.sleep(6) log("URL:", pg.url) log("TEXT:", pg.inner_text("body")[:600]) ctx.storage_state(path=STATE) log("state saved") return if cmd == "key": pg.goto(BASE + "/account/keys", wait_until="domcontentloaded") time.sleep(4) log("URL:", pg.url) txt = pg.inner_text("body") log("TEXT:", txt[:800]) btns = pg.locator("button") labels = [btns.nth(i).inner_text().strip() for i in range(btns.count())] log("BUTTONS:", labels[:30]) return if cmd == "usage": key = json.load(open(KEYS))[-1]["key"] if os.path.exists(KEYS) else None r = subprocess.run(['curl', '-s', '-m', '25', '-H', 'Authorization: Bearer %s' % key, 'https://api.withruntime.com/v1/usage'], capture_output=True, text=True) log("HTTP_BODY:", r.stdout[:1500]) return raise SystemExit("unknown cmd") if __name__ == "__main__": main()