autoreg-kit: api-route + tokvi autoreg, health, new-api inject and gates

This commit is contained in:
Gothbreach
2026-11-01 00:47:13 +00:00
commit a56037f6cf
13 changed files with 1352 additions and 0 deletions
+272
View File
@@ -0,0 +1,272 @@
# -*- coding: utf-8 -*-
"""Волна tokvi.ai: email+код (без Turnstile) -> cookie-сессия -> токен unlimited -> ключ -> чат."""
import email
import imaplib
import json
import os
import random
import re
import string
import threading
import time
from curl_cffi import requests as creq
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")
DOM = "tokvi.ai"
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
H = {"User-Agent": UA, "Content-Type": "application/json"}
MAILS = os.environ.get("MAILF", "/root/wave_mails.txt")
USED = os.environ.get("USEDF", "/root/tokvi_used.txt")
CRED = os.environ.get("CREDF", "/root/tokvi_creds.jsonl")
OUT = os.environ.get("OUTF", "/root/tokvi_wave.jsonl")
LOCK = threading.Lock()
_PX = os.environ.get("PX", "").strip()
PROXIES = ([x.strip() for x in _PX.split(",") if x.strip()] if _PX
else [f"http://{PX_USER}:{PX_PASS}@{h}:8888" for h in (PX_HOST1, PX_HOST2, PX_HOST3, PX_HOST4)])
N_TOTAL = int(os.environ.get("N", "40"))
N_WORK = int(os.environ.get("W", "4"))
def rnd(n=10):
return "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(n))
def log(rec):
with LOCK:
open(OUT, "a", encoding="utf-8").write(json.dumps(rec, ensure_ascii=False) + "\n")
print(json.dumps(rec, ensure_ascii=False)[:240], flush=True)
def take_mail():
with LOCK:
used = set()
for f in (USED,):
if os.path.exists(f):
used |= {l.strip() for l in open(f) if l.strip()}
for line in open(MAILS, encoding="utf-8", errors="ignore"):
line = line.strip()
if not line or line.startswith("#") or ":" not in line:
continue
a, p = line.split(":", 1)
if a in used:
continue
open(USED, "a").write(a + chr(10))
return a, p
return None, None
def imap(addr, pw):
m = imaplib.IMAP4_SSL("secureimap.t-online.de", 993, timeout=45)
m.login(addr, pw)
m.select("INBOX", readonly=True)
return m
def wait_code(addr, pw, timeout=210):
t0 = time.time()
m = imap(addr, pw)
try:
typ, d = m.uid("SEARCH", None, "ALL")
uids = [int(x) for x in (d[0].split() if d and d[0] else [])]
base = max(uids, default=0)
while time.time() - t0 < timeout:
typ, d = m.uid("SEARCH", None, "UID %d:*" % (base + 1))
for u in [int(x) for x in (d[0].split() if d and d[0] else []) if int(x) > base]:
typ, md = m.uid("FETCH", str(u), "(RFC822)")
if not md or not md[0]:
continue
msg = email.message_from_bytes(md[0][1])
body = ""
if msg.is_multipart():
for p in msg.walk():
if p.get_content_type() in ("text/plain", "text/html"):
pl = p.get_payload(decode=True)
if pl:
body += pl.decode("utf-8", "ignore")
else:
pl = msg.get_payload(decode=True)
body = pl.decode("utf-8", "ignore") if pl else ""
txt = re.sub(r"<[^>]+>", " ", body)
txt = re.sub(r"[0-9a-fA-F]{16,}", " ", txt)
for pat in (r"\b([0-9]{6})\b", r"\b([0-9]{4,8})\b", r"\b([A-Za-z0-9]{6})\b"):
c = re.findall(pat, txt)
if c:
return max(set(c), key=c.count)
time.sleep(7)
finally:
try:
m.logout()
except Exception:
pass
return None
def try_key(key, prox=None):
px = {"http": prox, "https": prox} if prox else None
res = {}
try:
m = creq.get(f"https://{DOM}/v1/models", headers={"Authorization": "Bearer " + key,
"User-Agent": UA},
impersonate="chrome124", timeout=20, proxies=px)
res["models"] = m.status_code
mods = [x.get("id") for x in (m.json().get("data") or [])] if m.status_code == 200 else []
except Exception as e:
res["models"] = "err"
mods = []
if not mods:
try:
p = creq.get(f"https://{DOM}/api/pricing", headers={"User-Agent": UA},
impersonate="chrome124", timeout=15, proxies=px)
rows = p.json().get("data") or []
mods = [r.get("model_name") for r in rows
if not r.get("model_ratio") and not r.get("completion_ratio")]
except Exception:
mods = []
mods = [x for x in mods if x]
mods.sort(key=lambda x: (0 if "free" in x.lower() else 1, x))
res["have"] = len(mods)
for mdl in mods[:3]:
try:
cc = creq.post(f"https://{DOM}/v1/chat/completions",
headers={"Authorization": "Bearer " + key, "Content-Type": "application/json",
"User-Agent": UA},
json={"model": mdl, "messages": [{"role": "user", "content": "2+2=?"}],
"max_tokens": 12}, impersonate="chrome124", timeout=60, proxies=px)
if cc.status_code == 200:
try:
txt = (cc.json().get("choices") or [{}])[0].get("message", {}).get("content", "")
except Exception:
txt = cc.text[:40]
res["chat"] = "200 " + mdl
res["reply"] = str(txt)[:60]
break
res["chat"] = f"{cc.status_code} {mdl}"
res["chat_body"] = cc.text.replace("\n", " ")[:70]
except Exception as e:
res["chat"] = "exc " + type(e).__name__
return res
def one(idx):
last = None
for attempt in range(3):
rec = _one(idx, attempt)
if rec.get("key") or rec.get("skip") == "пул пуст":
return rec
last = rec
msg = str(rec.get("reg_msg") or rec.get("verif") or "")
if "Too many accounts" in msg:
time.sleep(50 + attempt * 20)
elif "频繁" in msg:
time.sleep(32)
else:
break
return last
def _one(idx, attempt=0):
rec = {"i": idx, "ts": int(time.time())}
addr, mpw = take_mail()
if not addr:
rec["skip"] = "пул пуст"
return rec
rec["mail"] = addr.split("@")[0][-6:]
prox = PROXIES[(idx + attempt * 3) % len(PROXIES)]
s = creq.Session(impersonate="chrome124", proxies={"http": prox, "https": prox})
rec["px"] = prox.split("@")[-1][:12]
user, pwd = "tv" + rnd(7), rnd(13)
try:
time.sleep(3 + (idx % 4) * 2)
v = s.get(f"https://{DOM}/api/verification", params={"email": addr},
headers={"User-Agent": UA}, timeout=25)
vj = v.json() if v.text.startswith("{") else {}
if not vj.get("success"):
rec["verif"] = str(vj.get("message"))[:60]
return rec
code = wait_code(addr, mpw)
if not code:
rec["code"] = "нет письма"
return rec
body = {"username": user, "password": pwd, "password2": pwd,
"email": addr, "verification_code": code}
r = s.post(f"https://{DOM}/api/user/register", headers=H, json=body, timeout=30)
j = r.json() if r.text.startswith("{") else {}
rec["reg"] = bool(j.get("success"))
if not rec["reg"]:
rec["reg_msg"] = str(j.get("message"))[:70]
return rec
lr = s.post(f"https://{DOM}/api/user/login", headers=H,
json={"username": user, "password": pwd}, timeout=25)
lj = lr.json() if lr.text.startswith("{") else {}
d = lj.get("data") or {}
uid = d.get("id") or (d.get("user") or {}).get("id")
rec["quota0"] = d.get("quota")
if not uid:
rec["login"] = "нет uid"
return rec
hh = dict(H, **{"New-Api-User": str(uid)})
if d.get("access_token"):
hh["Authorization"] = "Bearer " + d["access_token"]
s.post(f"https://{DOM}/api/token/", headers=hh,
json={"name": "k1", "remain_quota": 0, "unlimited_quota": True,
"expired_time": -1}, timeout=20)
lst = s.get(f"https://{DOM}/api/token/?p=1&size=20", headers=hh, timeout=20)
it = (lst.json().get("data") or {}) if lst.text.startswith("{") else {}
it = it.get("items") if isinstance(it, dict) else it
if not it:
rec["token"] = "нет токенов"
return rec
tid = max((i.get("id") or 0) for i in it)
k = s.post(f"https://{DOM}/api/token/{tid}/key", headers=hh, timeout=20)
key = (k.json().get("data") or {}).get("key", "") if k.text.startswith("{") else ""
if not key:
rec["token"] = "ключа нет"
return rec
rec["key"] = key[:4] + "…"
with LOCK:
open(CRED, "a", encoding="utf-8").write(json.dumps(
{"dom": DOM, "user": user, "pass": pwd, "mail": addr, "key": key},
ensure_ascii=False) + "\n")
rec.update(try_key(key, prox))
except Exception as e:
rec["exc"] = type(e).__name__ + ":" + str(e)[:50]
return rec
def main():
import concurrent.futures as cf
print(f"tokvi волна: {N_TOTAL} аккаунтов, {N_WORK} потоков", flush=True)
with cf.ThreadPoolExecutor(max_workers=N_WORK) as ex:
for rec in ex.map(one, range(N_TOTAL)):
log(rec)
rows = []
for l in open(OUT, encoding="utf-8"):
try:
rows.append(json.loads(l))
except Exception:
pass
keys = [r for r in rows if r.get("key")]
ok = [r for r in keys if str(r.get("chat", "")).startswith("200")]
print(f"\nИТОГ: аккаунтов {len(rows)} | ключей {len(keys)} | чат 200 {len(ok)}")
for r in ok:
print(" ", r.get("chat"), "|", r.get("reply"), "| ключ", r.get("key"))
if __name__ == "__main__":
main()