248 lines
9.4 KiB
Python
248 lines
9.4 KiB
Python
#!/usr/bin/env python3
|
||
"""inferx_autoreg.py — авторег аккаунтов InferX (model.inferx.net) и ключей ix_.
|
||
|
||
Флоу: GitHub OAuth -> Keycloak first-broker-login -> ключ из панели -> проверка chat-200 -> банк.
|
||
|
||
Запуск:
|
||
python inferx_autoreg.py [N] [START]
|
||
|
||
Env:
|
||
INFERX_POOL путь к JSONL с GitHub-кредами (login,password,totp,email) [обязательно]
|
||
INFERX_BANK путь к банку ключей (JSONL, append) default ./inferx_bank.jsonl
|
||
INFERX_PORT порт CDP Chrome default 9271
|
||
INFERX_PROFILE каталог профиля Chrome default ./cdpprof
|
||
INFERX_CHROME путь к chrome.exe default авто-поиск
|
||
INFERX_FIRST/LAST имя/фамилия для профиля Keycloak default Alex/Schneider
|
||
|
||
Зависимости: playwright (sync API), requests.
|
||
"""
|
||
import os, sys, time, json, base64, hmac, hashlib, struct, subprocess, urllib.request
|
||
|
||
from playwright.sync_api import sync_playwright
|
||
import requests
|
||
|
||
try:
|
||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||
except Exception:
|
||
pass
|
||
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
POOL = os.environ.get("INFERX_POOL", "")
|
||
BANK = os.environ.get("INFERX_BANK", os.path.join(HERE, "inferx_bank.jsonl"))
|
||
PORT = int(os.environ.get("INFERX_PORT", "9271"))
|
||
PROF = os.environ.get("INFERX_PROFILE", os.path.join(HERE, "cdpprof"))
|
||
FIRST = os.environ.get("INFERX_FIRST", "Alex")
|
||
LAST = os.environ.get("INFERX_LAST", "Schneider")
|
||
BASE = "https://model.inferx.net/endpoints/v1"
|
||
LOGIN_URL = "https://model.inferx.net/login?idp=github"
|
||
CATALOG = "https://model.inferx.net/catalog/endpoints"
|
||
|
||
CHROME_CANDIDATES = [
|
||
os.environ.get("INFERX_CHROME", ""),
|
||
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
|
||
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
|
||
os.path.expandvars(r"%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe"),
|
||
]
|
||
|
||
|
||
def log(*a):
|
||
print(*a, flush=True)
|
||
|
||
|
||
def find_chrome():
|
||
for c in CHROME_CANDIDATES:
|
||
if c and os.path.exists(c):
|
||
return c
|
||
return "chrome"
|
||
|
||
|
||
def totp(secret, t=None):
|
||
key = base64.b32decode(secret.upper() + '=' * ((8 - len(secret) % 8) % 8))
|
||
counter = struct.pack('>Q', int((t or time.time()) // 30))
|
||
h = hmac.new(key, counter, hashlib.sha1).digest()
|
||
o = h[-1] & 0x0F
|
||
return '%06d' % ((struct.unpack('>I', h[o:o + 4])[0] & 0x7FFFFFFF) % 1000000)
|
||
|
||
|
||
def cdp_up():
|
||
try:
|
||
urllib.request.urlopen("http://127.0.0.1:%d/json/version" % PORT, timeout=2).read()
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def start_chrome():
|
||
if cdp_up():
|
||
return
|
||
os.makedirs(PROF, exist_ok=True)
|
||
subprocess.Popen([find_chrome(), "--remote-debugging-port=%d" % PORT, "--user-data-dir=" + PROF,
|
||
"--no-first-run", "--no-default-browser-check",
|
||
"--disable-blink-features=AutomationControlled", "--window-size=1280,950", "about:blank"],
|
||
creationflags=getattr(subprocess, "DETACHED_PROCESS", 0) | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
|
||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True)
|
||
for _ in range(25):
|
||
time.sleep(1)
|
||
if cdp_up():
|
||
return
|
||
|
||
|
||
def qs(pg, sel):
|
||
"""query_selector с ретраем: после submit навигация рвёт execution context."""
|
||
for _ in range(3):
|
||
try:
|
||
return pg.query_selector(sel)
|
||
except Exception:
|
||
time.sleep(0.6)
|
||
return None
|
||
|
||
|
||
def test_key(key, models=("deepseek-v4.1-flash-1017", "glm-5.3-flash", "kimi-k3")):
|
||
last = None
|
||
for m in models:
|
||
try:
|
||
r = requests.post(BASE + "/chat/completions",
|
||
headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
|
||
json={"model": m, "messages": [{"role": "user", "content": "say OK"}], "max_tokens": 8},
|
||
timeout=45)
|
||
if r.status_code == 200:
|
||
return True, m
|
||
last = "%s:%s:%s" % (m, r.status_code, r.text[:60])
|
||
except Exception as e:
|
||
last = "%s:%s" % (m, type(e).__name__)
|
||
return False, last
|
||
|
||
|
||
def read_key(pg, ctx):
|
||
"""Полный ключ только из clipboard: в DOM он замаскирован (ix_***3c88)."""
|
||
try:
|
||
ctx.grant_permissions(['clipboard-read', 'clipboard-write'], origin='https://model.inferx.net')
|
||
except Exception:
|
||
pass
|
||
if '/catalog/endpoints' not in pg.url:
|
||
pg.goto(CATALOG, wait_until="domcontentloaded", timeout=90000)
|
||
time.sleep(3)
|
||
pg.evaluate("""(() => {
|
||
const c = Array.from(document.querySelectorAll('button, a, span'))
|
||
.find(b => /^\\s*copy\\s*$/i.test((b.innerText || '').trim()));
|
||
if (c) c.click();
|
||
})()""")
|
||
time.sleep(1)
|
||
try:
|
||
return (pg.evaluate("navigator.clipboard.readText()") or '').strip()
|
||
except Exception:
|
||
return ''
|
||
|
||
|
||
def one_account(pg, acct):
|
||
ctx = pg.context
|
||
try:
|
||
ctx.clear_cookies()
|
||
except Exception:
|
||
pass
|
||
pg.goto(LOGIN_URL, wait_until="domcontentloaded", timeout=90000)
|
||
for _ in range(8):
|
||
time.sleep(1.5)
|
||
if 'github.com' in pg.url:
|
||
break
|
||
if 'github.com' not in pg.url:
|
||
return {"login": acct['login'], "err": "no-github-redirect"}
|
||
if not qs(pg, '#login_field'):
|
||
return {"login": acct['login'], "err": "no-login-field"}
|
||
pg.fill('#login_field', acct['login'])
|
||
pg.fill('#password', acct['password'])
|
||
pg.click('input[type="submit"]')
|
||
time.sleep(5)
|
||
if qs(pg, '#app_totp') or qs(pg, 'input[name="otp"]'):
|
||
sel = '#app_totp' if qs(pg, '#app_totp') else 'input[name="otp"]'
|
||
pg.fill(sel, totp(acct['totp']))
|
||
pg.keyboard.press("Enter")
|
||
time.sleep(5)
|
||
if 'github.com' in pg.url and 'session' in pg.url:
|
||
return {"login": acct['login'], "err": "gh-login-failed"}
|
||
# authorize: РОВНО ОДИН клик, второй = access_denied
|
||
for _ in range(2):
|
||
txt = pg.inner_text("body")[:800].lower()
|
||
if 'authorize' in txt and 'inferx' in txt:
|
||
pg.evaluate("""(() => {
|
||
const c = Array.from(document.querySelectorAll('button, input[type=submit]'));
|
||
const b = c.find(x => /authorize/i.test((x.innerText || x.value || '')));
|
||
if (b) b.click();
|
||
})()""")
|
||
time.sleep(7)
|
||
else:
|
||
break
|
||
# Keycloak first-broker-login
|
||
for _ in range(4):
|
||
if qs(pg, 'input[name="firstName"], input[name="username"]'):
|
||
for name, val in (('username', acct['login']), ('email', acct.get('email', '')),
|
||
('firstName', FIRST), ('lastName', LAST)):
|
||
el = qs(pg, 'input[name="%s"]' % name)
|
||
if el and val:
|
||
try:
|
||
el.fill(val)
|
||
except Exception:
|
||
pass
|
||
pg.evaluate("""(() => {
|
||
const c = Array.from(document.querySelectorAll('button[type=submit], input[type=submit], button'));
|
||
const b = c.find(x => /submit|save|continue|do it/i.test((x.innerText || x.value || '')));
|
||
if (b) b.click();
|
||
})()""")
|
||
for _w in range(10):
|
||
time.sleep(2)
|
||
try:
|
||
if 'model.inferx.net' in pg.url and 'authn' not in pg.url:
|
||
break
|
||
except Exception:
|
||
pass
|
||
else:
|
||
break
|
||
for _ in range(12):
|
||
if 'model.inferx.net' in pg.url and 'authn' not in pg.url:
|
||
break
|
||
time.sleep(2)
|
||
if 'model.inferx.net' not in pg.url or 'authn' in pg.url:
|
||
return {"login": acct['login'], "err": "not-landed"}
|
||
key = read_key(pg, ctx)
|
||
if not key.startswith('ix_'):
|
||
return {"login": acct['login'], "err": "no-key", "clip": key[:40]}
|
||
ok, info = test_key(key)
|
||
return {"login": acct['login'], "key": key, "ok": ok, "model": info}
|
||
|
||
|
||
def main():
|
||
if not POOL:
|
||
log("INFERX_POOL не задан")
|
||
sys.exit(2)
|
||
n = int(sys.argv[1]) if len(sys.argv) > 1 else 5
|
||
start = int(sys.argv[2]) if len(sys.argv) > 2 else 0
|
||
pool = [json.loads(l) for l in open(POOL, encoding='utf-8') if l.strip()][start:start + n]
|
||
log("wave:", len(pool), "start", start)
|
||
start_chrome()
|
||
log("cdp:", cdp_up())
|
||
ok = 0
|
||
with sync_playwright() as p:
|
||
br = p.chromium.connect_over_cdp("http://127.0.0.1:%d" % PORT)
|
||
ctx = br.contexts[0]
|
||
pg = ctx.pages[0] if ctx.pages else ctx.new_page()
|
||
pg.bring_to_front()
|
||
for acct in pool:
|
||
t0 = time.time()
|
||
log("---", acct['login'])
|
||
try:
|
||
rec = one_account(pg, acct)
|
||
except Exception as e:
|
||
rec = {"login": acct['login'], "err": "EXC " + repr(e)[:120]}
|
||
rec['ts'] = int(time.time())
|
||
rec['sec'] = round(time.time() - t0, 1)
|
||
with open(BANK, 'a', encoding='utf-8') as f:
|
||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||
log(" ->", json.dumps({k: rec.get(k) for k in ('ok', 'err', 'model', 'sec')}, ensure_ascii=False))
|
||
if rec.get('ok'):
|
||
ok += 1
|
||
time.sleep(2)
|
||
log("OK keys:", ok, "/", len(pool))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |