Files
numes-autoreg/reg.py
T

432 lines
16 KiB
Python

#!/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, imaplib, json, os, re, ssl, subprocess, sys, time, traceback
from playwright.sync_api import sync_playwright
import pyotp
CHROME = "C:/Program Files/Google/Chrome/Application/chrome.exe"
ROOT = os.environ.get("NUMES_ROOT", "C:/Users/User/tmp/numes")
POOL = os.environ.get("NUMES_POOL", ROOT + "/pool_all.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)
IMAP_PRESET = {
"t-online.de": "secureimap.t-online.de",
"gmail.com": "imap.gmail.com",
"googlemail.com": "imap.gmail.com",
"outlook.com": "outlook.office365.com",
"hotmail.com": "outlook.office365.com",
"live.com": "outlook.office365.com",
"yahoo.com": "imap.mail.yahoo.com",
"gmx.de": "imap.gmx.net",
"web.de": "imap.web.de",
}
def mail_code(acc, timeout=150):
"""GitHub device-verification code from the account mailbox (IMAP)."""
addr = (acc.get("email") or "").strip()
pw = (acc.get("email_pw") or "").strip()
if not addr or not pw:
return ""
dom = addr.split("@")[-1].lower()
hosts = ([IMAP_PRESET[dom]] if dom in IMAP_PRESET else []) + \
["imap." + dom, "mail." + dom, dom]
t0 = time.time()
while time.time() - t0 < timeout:
for h in hosts:
try:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
M = imaplib.IMAP4_SSL(h, 993, ssl_context=ctx, timeout=20)
M.login(addr, pw)
M.select("INBOX", readonly=True)
typ, data = M.search(None, "FROM", '"github"')
ids = (data[0].split() if data and data[0] else [])[-4:]
for i in reversed(ids):
typ, msg = M.fetch(i, "(RFC822)")
raw = msg[0][1].decode("utf-8", "replace")
if "device" not in raw.lower() and "verification" not in raw.lower():
continue
m = re.search(r"\b(\d{6})\b", raw)
if m:
M.logout()
return m.group(1)
M.logout()
except Exception:
continue
time.sleep(8)
return ""
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
or ("github.com" in page.url and page.locator("input[name=value], #otp, input[autocomplete='one-time-code']").count())):
log("device verification, читаю почту", login)
code = mail_code(acc)
if not code:
return False, "gh_device_verification_no_code"
try:
sel = ("#otp" if page.locator("#otp").count() else
("input[name=value]" if page.locator("input[name=value]").count()
else "input[autocomplete='one-time-code']"))
page.fill(sel, code)
page.click("button[type=submit], input[type=submit]")
page.wait_for_timeout(7000)
log("device verification ok", login, code[:2] + "****")
except Exception as e:
return False, "dv_fill_fail:" + str(e)[:80]
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 proxy_list():
f = os.environ.get("NUMES_PROXY_FILE", "")
if not f or not os.path.exists(f):
return []
out = []
with open(f, encoding="utf-8", errors="replace") as fh:
for line in fh:
line = line.strip()
if line and not line.startswith("#") and ":" in line:
out.append(line)
return out
def egress(px, timeout=15):
if not px:
return ""
try:
r = subprocess.run(
["curl", "-s", "-m", str(timeout), "-x", "http://" + px, "https://api.ipify.org"],
capture_output=True, text=True, timeout=timeout + 8)
ip = (r.stdout or "").strip()
return ip if ip and len(ip) < 20 else ""
except Exception:
return ""
def run_account(page, acc, px):
login = acc["login"]
log("--- try", login, "px", px or "direct")
try:
ctx = page.context
ctx.clear_cookies()
ok, reason = do_login(page, acc)
if not ok:
append(FAIL, {"login": login, "reason": reason, "px": px, "ts": int(time.time())})
log("FAIL", login, reason)
shot(page, "fail_" + re.sub(r"\W", "_", login))
return False, login, "resp"
key, kerr = create_key(page, acc)
if not key:
append(FAIL, {"login": login, "reason": "key:" + kerr, "px": px, "ts": int(time.time())})
log("KEYFAIL", login, kerr[:120])
shot(page, "keyfail_" + re.sub(r"\W", "_", login))
return False, login, "resp"
code, cost = warm_key(key)
append(BANK, {"gh": login, "email": acc.get("email"), "key": key,
"http": code, "cost": cost, "px": px, "egress": egress(px),
"ts": int(time.time())})
log("OK", login, "http", code, "cost", cost, "keylen", len(key), "px", px or "direct")
save_key_file()
return True, login, "ok"
except Exception as e:
me = str(e)
status = "netfail" if any(k in me for k in ("ERR_", "net::", "Timeout", "timeout", "ECONN")) else "fail"
append(FAIL, {"login": login, "reason": "exc:" + me[:200], "px": px, "status": status,
"ts": int(time.time())})
log("EXC", login, me[:200], status)
try:
shot(page, "exc_" + re.sub(r"\W", "_", login))
except Exception:
pass
return False, login, status
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)
ap.add_argument("--no-proxy", 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]
px_all = [] if a.no_proxy else proxy_list()
log(f"wave start: pool={len(accs)} done={len(done)} todo={len(todo)} proxies={len(px_all)}")
for idx, acc in enumerate(todo):
if acc["login"] in done:
continue
status = "fail"
for attempt in range(3):
px = px_all[(a.start + idx + attempt) % len(px_all)] if px_all else None
prof = "%s_%d" % (PROF, (a.start + idx + attempt) % 120)
try:
with sync_playwright() as p:
args = ["--disable-dev-shm-usage", "--disable-gpu", "--no-first-run",
"--no-default-browser-check"]
if px:
# PAC: сайт через прокси, GitHub напрямую (свежий egress на OAuth = device verification)
host, _, port = px.rpartition(":")
pac = ("function FindProxyForURL(url, host) {\n"
" if (host == 'github.com' || shExpMatch(host, '*.github.com')\n"
" || shExpMatch(host, '*.githubusercontent.com')\n"
" || shExpMatch(host, '*.githubassets.com')\n"
" || shExpMatch(host, '*.githubapp.com')) return 'DIRECT';\n"
" return 'PROXY %s:%s';\n}\n" % (host, port))
pac_path = os.path.join(ROOT, "proxy_%d.pac" % ((a.start + idx + attempt) % 120))
with open(pac_path, "w", encoding="ascii") as pf:
pf.write(pac)
args.append("--proxy-pac-url=file:///" + pac_path.replace("\\", "/"))
ctx = p.chromium.launch_persistent_context(
prof,
executable_path=CHROME,
headless=bool(a.headless),
args=args,
viewport={"width": 1280, "height": 900},
)
page = ctx.pages[0] if ctx.pages else ctx.new_page()
try:
ok, login, status = run_account(page, acc, px)
finally:
try:
ctx.close()
except Exception:
pass
except Exception as e:
me = str(e)
status = "netfail" if any(k in me for k in ("ERR_", "net::", "Timeout", "ECONN")) else "fail"
log("LAUNCH_FAIL", acc["login"], me[:160], status)
append(FAIL, {"login": acc["login"], "reason": "launch:" + me[:200],
"px": px, "status": status, "ts": int(time.time())})
if status != "netfail":
break
if status != "netfail":
done.add(acc["login"])
else:
log("SKIP(done untouched)", acc["login"])
with open(DONE, "w", encoding="utf-8") as f:
json.dump(sorted(done), f)
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()