#!/usr/bin/env python3 """Numes autoreg: GitHub OAuth -> account -> USD inference key -> bank. Usage: python reg.py --start 0 --count 3 [--headless 1] State: done.json (logins tried), bank.jsonl (keys ok), fail.jsonl (reasons) """ import argparse, json, os, re, sys, time, traceback from playwright.sync_api import sync_playwright import pyotp CHROME = os.environ.get("NUMES_CHROME", "C:/Program Files/Google/Chrome/Application/chrome.exe") ROOT = os.environ.get("NUMES_ROOT", os.path.dirname(os.path.abspath(__file__))) POOL = os.environ.get("NUMES_POOL", "gh_alive.jsonl") BANK = ROOT + "/bank.jsonl" FAIL = ROOT + "/fail.jsonl" DONE = ROOT + "/done.json" PROF = ROOT + "/prof" LOG = ROOT + "/wave.log" def log(*a): line = time.strftime("%H:%M:%S ") + " ".join(str(x) for x in a) print(line, flush=True) with open(LOG, "a", encoding="utf-8") as f: f.write(line + "\n") def load_json(path, default): try: with open(path, encoding="utf-8") as f: return json.load(f) except Exception: return default def append(path, obj): with open(path, "a", encoding="utf-8") as f: f.write(json.dumps(obj, ensure_ascii=False) + "\n") def pool(): out = [] with open(POOL, encoding="utf-8", errors="replace") as f: for line in f: line = line.strip() if line: try: out.append(json.loads(line)) except Exception: pass return out def body(page): try: return (page.inner_text("body") or "")[:4000] except Exception: return "" def shot(page, tag): try: p = f"{ROOT}/shots/{tag}.png" os.makedirs(ROOT + "/shots", exist_ok=True) page.screenshot(path=p) return p except Exception: return "" def wait_dash(page, timeout_ms=45000): """Ждём, пока окажемся на numes.ai (после OAuth).""" t0 = time.time() while (time.time() - t0) * 1000 < timeout_ms: url = page.url if "numes.ai" in url and "auth/login" not in url and "/auth/callback" not in url: return True page.wait_for_timeout(1200) return False def fill_profile_if_asked(page, acc): """Keycloak иногда просит дозаполнить профиль.""" try: if "auth.numes.ai" not in page.url: return if page.locator("input[name=firstName]").count(): login = acc["login"].replace(".", " ").title() first = login.split()[0][:20] or "Alex" last = (login.split()[-1] if len(login.split()) > 1 else "Baker")[:20] page.fill("input[name=firstName]", first) page.fill("input[name=lastName]", last) if page.locator("input[name=email]").count(): page.fill("input[name=email]", acc.get("email") or f"{acc['login']}@t-online.de") page.click("input[type=submit]") page.wait_for_timeout(4000) log("profile filled") except Exception as e: log("profile fill err", e) def do_login(page, acc): """Возвращает (ok, reason).""" login, pw = acc["login"], acc["password"] page.goto("https://numes.ai/auth/login", wait_until="domcontentloaded", timeout=90000) page.wait_for_timeout(2500) # GitHub broker try: page.get_by_text("Continue with GitHub", exact=True).click(timeout=20000) except Exception: page.locator("a:has-text('GitHub')").first.click(timeout=20000) page.wait_for_timeout(5000) if "github.com" in page.url and "/login" in page.url: page.fill("#login_field", login) page.fill("#password", pw) page.click("input[type=submit][name=commit]") page.wait_for_timeout(5500) # GitHub 2FA if "two-factor" in page.url or page.locator("#app_totp").count() or page.locator("input[name=app_otp]").count(): code = pyotp.TOTP(acc["totp"]).now() sel = "#app_totp" if page.locator("#app_totp").count() else "input[name=app_otp]" try: page.fill(sel, code) page.click("button[type=submit], input[type=submit]") page.wait_for_timeout(6000) log("2fa ok", login) except Exception as e: return False, f"2fa_fill_fail:{e}" if "verified-device" in page.url or "sessions/verified" in page.url: return False, "gh_device_verification" if "/session" in page.url and "github.com" in page.url: return False, "gh_login_failed" if page.locator("#signup-form, [data-testid=signup-form]").count() and "join" in page.url: return False, "gh_account_missing" # OAuth authorize screen if "/login/oauth/authorize" in page.url: clicked = False for sel in ('button[name=authorize][value="1"]', 'button:has-text("Authorize")'): try: page.click(sel, timeout=8000) clicked = True break except Exception: continue if not clicked: try: page.locator('button[name=authorize][value="1"]').dispatch_event("click") clicked = True except Exception: pass if not clicked: return False, "authorize_click_fail" page.wait_for_timeout(6000) fill_profile_if_asked(page, acc) if not wait_dash(page, 40000): return False, "no_dashboard:" + page.url[:120] log("logged in", login, page.url[:80]) return True, "ok" def create_key(page, acc): page.goto("https://numes.ai/dashboard/keys", wait_until="domcontentloaded", timeout=90000) page.wait_for_timeout(4000) if "auth/login" in page.url: return None, "session_lost" page.get_by_role("button", name=re.compile(r"^Create key$")).last.click(timeout=20000) page.wait_for_timeout(2500) dlg = page.locator("[role=dialog]").last # имя try: name_input = dlg.locator("input[name=name]") name_input.fill("") name_input.type("eni-" + acc["login"][:14], delay=25) except Exception as e: log("name fill err", e) # USD уже дефолт; Type=Inference дефолт page.wait_for_timeout(600) try: dlg.get_by_role("button", name=re.compile(r"^Create key$")).click(timeout=15000) except Exception: dlg.locator("form").first.evaluate("f => f.requestSubmit ? f.requestSubmit() : f.submit()") page.wait_for_timeout(6000) txt = body(page) m = re.search(r"(sk-numes-[A-Za-z0-9_\-]{20,})", txt) if not m: m = re.search(r"(sk-[A-Za-z0-9_\-]{30,})", txt) if not m: return None, "no_secret:" + txt[:200].replace("\n", " ") return m.group(1), "ok" def warm_key(key): """Один вызов на $0 модель для проверки ключа.""" import urllib.request payload = json.dumps({ "model": "z-ai/glm-5.3", "messages": [{"role": "user", "content": "ping"}], "max_tokens": 1200, }).encode() req = urllib.request.Request( "https://api.numes.ai/api/v1/chat/completions", data=payload, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}, ) try: with urllib.request.urlopen(req, timeout=120) as r: j = json.loads(r.read().decode()) return r.status, j.get("usage", {}).get("cost") except Exception as e: return None, str(e)[:120] def main(): ap = argparse.ArgumentParser() ap.add_argument("--start", type=int, default=0) ap.add_argument("--count", type=int, default=2) ap.add_argument("--headless", type=int, default=0) a = ap.parse_args() os.makedirs(ROOT, exist_ok=True) accs = [x for x in pool() if x.get("login") and x.get("password")] done = set(load_json(DONE, [])) todo = [x for x in accs if x["login"] not in done][a.start:a.start + a.count] log(f"wave start: pool={len(accs)} done={len(done)} todo={len(todo)}") with sync_playwright() as p: ctx = p.chromium.launch_persistent_context( PROF, executable_path=CHROME, headless=bool(a.headless), args=["--disable-dev-shm-usage", "--disable-gpu", "--no-first-run", "--no-default-browser-check"], viewport={"width": 1280, "height": 900}, ) page = ctx.pages[0] if ctx.pages else ctx.new_page() for acc in todo: login = acc["login"] log("--- try", login) try: ctx.clear_cookies() ok, reason = do_login(page, acc) if not ok: append(FAIL, {"login": login, "reason": reason, "ts": int(time.time())}) log("FAIL", login, reason) shot(page, "fail_" + re.sub(r"\W", "_", login)) done.add(login) continue key, kerr = create_key(page, acc) if not key: append(FAIL, {"login": login, "reason": "key:" + kerr, "ts": int(time.time())}) log("KEYFAIL", login, kerr[:120]) shot(page, "keyfail_" + re.sub(r"\W", "_", login)) done.add(login) continue code, cost = warm_key(key) append(BANK, {"gh": login, "email": acc.get("email"), "key": key, "http": code, "cost": cost, "ts": int(time.time())}) log("OK", login, "http", code, "cost", cost, "keylen", len(key)) done.add(login) save_key_file() except Exception as e: append(FAIL, {"login": login, "reason": "exc:" + str(e)[:200], "ts": int(time.time())}) log("EXC", login, str(e)[:200]) try: shot(page, "exc_" + re.sub(r"\W", "_", login)) except Exception: pass done.add(login) finally: with open(DONE, "w", encoding="utf-8") as f: json.dump(sorted(done), f) ctx.close() def save_key_file(): keys = [] try: with open(BANK, encoding="utf-8") as f: for line in f: if line.strip(): keys.append(json.loads(line)["key"]) except Exception: pass with open(ROOT + "/keys.txt", "w", encoding="utf-8") as f: f.write("\n".join(keys) + ("\n" if keys else "")) if __name__ == "__main__": main()