207 lines
9.5 KiB
Python
207 lines
9.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""browser_reg_ar.py — браузерная рега api-route.com (invisible Turnstile проходит сам).
|
|
usage: python browser_reg_ar.py [count]
|
|
"""
|
|
import json, os, random, re, string, subprocess, sys, time
|
|
from camoufox.sync_api import Camoufox
|
|
|
|
import os as _os
|
|
PROD_HOST = _os.environ.get("PROD_HOST", "root@127.0.0.1")
|
|
FARM_HOST = _os.environ.get("FARM_HOST", "root@127.0.0.1")
|
|
PX_USER = _os.environ.get("PX_USER", "")
|
|
PX_PASS = _os.environ.get("PX_PASS", "")
|
|
PX_HOST1 = _os.environ.get("PX_HOST1", "127.0.0.1")
|
|
PX_HOST2 = _os.environ.get("PX_HOST2", "127.0.0.1")
|
|
PX_HOST3 = _os.environ.get("PX_HOST3", "127.0.0.1")
|
|
PX_HOST4 = _os.environ.get("PX_HOST4", "127.0.0.1")
|
|
MAIL_LOCAL = _os.environ.get("MAIL_LOCAL", "user")
|
|
PROBE_EMAIL = _os.environ.get("PROBE_EMAIL", "probe@example.com")
|
|
PROBE_EMAIL2 = _os.environ.get("PROBE_EMAIL2", "probe2@example.com")
|
|
PROBE_EMAIL3 = _os.environ.get("PROBE_EMAIL3", "probe3@example.com")
|
|
|
|
|
|
BASE = "https://www.api-route.com"
|
|
_PORT = os.environ.get("AR_PORT", "8891")
|
|
_HOSTMAP = {"8891": PX_HOST1, "8892": PX_HOST2, "8893": PX_HOST3,
|
|
"8894": PX_HOST4, "8895": _os.environ.get("PX_HOST5", "127.0.0.1")}
|
|
PROXY = {"server": "http://%s:8901" % _HOSTMAP.get(_PORT, PX_HOST1),
|
|
"username": os.environ.get("PX_USER", ""), "password": os.environ.get("PX_PASS", "")}
|
|
TAGP = os.environ.get("AR_TAG", "br")
|
|
LOG = r"C:\Users\User\tmp\browser_reg.log"
|
|
BANK = r"C:\Users\User\tmp\panel_bank.jsonl"
|
|
|
|
|
|
def log(*a):
|
|
s = " ".join(str(x) for x in a)
|
|
print(s, flush=True)
|
|
open(LOG, "a", encoding="utf-8").write(time.strftime("%H:%M:%S ") + s + "\n")
|
|
|
|
|
|
def mk(n=8):
|
|
return "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(n))
|
|
|
|
|
|
def read_code(alias, wait=150, min_ts=0):
|
|
cmd = 'ssh -o ConnectTimeout=20 -o StrictHostKeyChecking=no " + PROD_HOST + " "python3 /root/pcode.py %s %d %d"' % (alias, wait, min_ts)
|
|
p = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=wait + 90)
|
|
out = (p.stdout or "") + (p.stderr or "")
|
|
m = re.search(r"CODE\s+([0-9A-Za-z]{4,8})", out)
|
|
return (m.group(1) if m else None), out.strip()[:100]
|
|
|
|
|
|
def one(idx=1):
|
|
user = "u" + mk(8)
|
|
pw = "Zx" + mk(10) + "!7"
|
|
alias = MAIL_LOCAL + "+%s%s@gmail.com" % (TAGP, mk(5))
|
|
ts = int(time.time())
|
|
log("=== account:", user, alias)
|
|
with Camoufox(headless=True, geoip=False, humanize=True, os=["windows"],
|
|
proxy=PROXY, locale="en-US") as br:
|
|
pg = br.new_page()
|
|
pg.set_default_timeout(45000)
|
|
pg.goto(BASE + "/register", wait_until="domcontentloaded")
|
|
time.sleep(3)
|
|
pg.fill("#register-username", user)
|
|
pg.fill("#register-email", alias)
|
|
pg.fill("#register-password", pw)
|
|
pg.fill("#register-password2", pw)
|
|
time.sleep(1)
|
|
# отправляем код (до 3 попыток, пока кнопка не станет "Resend")
|
|
sent = False
|
|
for attempt in range(3):
|
|
pg.evaluate("""() => {
|
|
const b=[...document.querySelectorAll('button')].find(x=>/send code/i.test(x.innerText||''));
|
|
if(b){b.scrollIntoView();b.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));b.click();}
|
|
}""")
|
|
for _ in range(8):
|
|
time.sleep(1.5)
|
|
txt = pg.evaluate("() => [...document.querySelectorAll('button')].map(b=>b.innerText.trim()).join('|')")
|
|
if re.search(r"resend|\d+s", txt):
|
|
sent = True
|
|
break
|
|
if sent:
|
|
break
|
|
try:
|
|
pg.get_by_role("button", name=re.compile("send code", re.I)).first.click(timeout=5000)
|
|
except Exception as e:
|
|
log("click retry err", type(e).__name__)
|
|
time.sleep(3)
|
|
log("send-code sent:", sent)
|
|
body = pg.evaluate("() => document.body.innerText.slice(0,300)").replace("\n", " | ")
|
|
log("after send-code:", body[:200])
|
|
code, info = read_code(alias, 150, ts)
|
|
if not code:
|
|
log("NOCODE", info)
|
|
return {"stage": "mail"}
|
|
log("code:", code)
|
|
pg.fill("#register-code", code)
|
|
time.sleep(2)
|
|
# ждём invisible turnstile
|
|
for i in range(12):
|
|
tok = pg.evaluate("() => { const e=document.querySelector('input[name=cf-turnstile-response]'); return e?e.value:''; }")
|
|
if tok and len(tok) > 30:
|
|
log("turnstile token len:", len(tok))
|
|
break
|
|
time.sleep(2)
|
|
pg.evaluate("""() => {
|
|
const b=[...document.querySelectorAll('button')].find(x=>/create account/i.test(x.innerText||''));
|
|
if(b){b.scrollIntoView();b.click();}
|
|
}""")
|
|
for i in range(20):
|
|
time.sleep(2)
|
|
if "/login" not in pg.url:
|
|
break
|
|
body = pg.evaluate("() => document.body.innerText.slice(0,400)").replace("\n", " | ")
|
|
log("after submit url:", pg.url, "| body:", body[:220])
|
|
if "register" in pg.url and ("error" in body.lower() or "invalid" in body.lower() or "失败" in body):
|
|
pg.screenshot(path=r"C:\Users\User\tmp\ar_fail.png")
|
|
return {"stage": "register", "info": body[:120]}
|
|
# идём на страницу API-ключей и создаём ключ через UI
|
|
pg.goto(BASE + "/api-keys", wait_until="domcontentloaded")
|
|
time.sleep(5)
|
|
if "/login" in pg.url:
|
|
log("session lost -> login fallback")
|
|
pg.fill("#login-username", alias)
|
|
pg.fill("#login-password", pw)
|
|
pg.evaluate("""() => {
|
|
const b=[...document.querySelectorAll('button')].find(x=>/sign in|log in|login|登录/i.test(x.innerText||''));
|
|
if(b){b.click();}
|
|
}""")
|
|
for i in range(15):
|
|
time.sleep(2)
|
|
if "/login" not in pg.url:
|
|
break
|
|
log("after login url:", pg.url)
|
|
if "/login" in pg.url:
|
|
return {"stage": "login", "info": pg.url}
|
|
pg.goto(BASE + "/api-keys", wait_until="domcontentloaded")
|
|
time.sleep(4)
|
|
txt = pg.evaluate("() => document.body.innerText.slice(0,600)").replace("\n", " | ")
|
|
log("api-keys page:", txt[:260])
|
|
# шаг 1: найти кнопку создания
|
|
created = pg.evaluate("""() => {
|
|
const btns=[...document.querySelectorAll('button')].map(b=>(b.innerText||'').trim()).filter(Boolean);
|
|
const b=[...document.querySelectorAll('button')].find(x=>/create|new key|add|generate|新建|创建/i.test(x.innerText||''));
|
|
if(b){b.scrollIntoView();b.click();return btns;}
|
|
return btns;
|
|
}""")
|
|
log("buttons:", json.dumps(created, ensure_ascii=True)[:200])
|
|
time.sleep(3)
|
|
ins = pg.evaluate("""() => [...document.querySelectorAll('input')].map(e=>({id:e.id,ph:e.placeholder||'',type:e.type}))""")
|
|
log("inputs:", json.dumps(ins, ensure_ascii=True)[:200])
|
|
name = "k" + mk(4)
|
|
sel = None
|
|
for i in ins:
|
|
if i.get("id"):
|
|
sel = "#" + i["id"]
|
|
break
|
|
if i.get("ph"):
|
|
sel = "input[placeholder='%s']" % i["ph"]
|
|
break
|
|
if sel:
|
|
try:
|
|
pg.fill(sel, name)
|
|
except Exception as e:
|
|
log("fill err", type(e).__name__)
|
|
pg.evaluate("""() => {
|
|
const b=[...document.querySelectorAll('button')].find(x=>/confirm|create|submit|确定|保存|save/i.test(x.innerText||''));
|
|
if(b){b.click();}
|
|
}""")
|
|
time.sleep(5)
|
|
body = pg.evaluate("() => document.body.innerText")
|
|
key = None
|
|
m = re.search(r"(sk-[A-Za-z0-9_\-]{20,})", body)
|
|
if m:
|
|
key = m.group(1)
|
|
if not key:
|
|
r2 = pg.evaluate("""async () => {
|
|
const out={};
|
|
for (const u of ['/api/user/token','/api/token/?p=1&size=10','/api/dist/token/list']) {
|
|
try { const r=await fetch(u); out[u]=[r.status,(await r.text()).slice(0,400)]; } catch(e){ out[u]=['err'] }
|
|
}
|
|
return out;
|
|
}""")
|
|
log("probe:", json.dumps(r2, ensure_ascii=True)[:420])
|
|
mm = re.search(r'"key"\s*:\s*"([A-Za-z0-9_\-]{20,})"', json.dumps(r2, ensure_ascii=True))
|
|
if mm:
|
|
key = mm.group(1)
|
|
log("key found:", bool(key), "| page:", pg.url)
|
|
if not key:
|
|
pg.screenshot(path=r"C:\Users\User\tmp\ar_nokey.png")
|
|
open(r"C:\Users\User\tmp\ar_tokenpage.txt", "w", encoding="utf-8").write(
|
|
json.dumps({"username": user, "password": pw, "email": alias}, ensure_ascii=True) + "\n---\n" + body[:2000])
|
|
rec = {"base": BASE, "username": user, "password": pw, "email": alias, "key": key,
|
|
"models": [], "ts": int(time.time())}
|
|
with open(BANK, "a", encoding="utf-8") as f:
|
|
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
return {"stage": "ok" if key else "nokey", "key": bool(key)}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
|
for i in range(n):
|
|
try:
|
|
log("RESULT", json.dumps(one(i + 1), ensure_ascii=True))
|
|
except Exception as e:
|
|
log("EXC", type(e).__name__, str(e)[:120])
|
|
time.sleep(3) |