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
+174
View File
@@ -0,0 +1,174 @@
# -*- coding: utf-8 -*-
"""tokvi: ждём открытия суточной квоты SMTP (550) -> волна -> банк ключей."""
import fcntl
import json
import os
import socket
import subprocess
import sys
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")
D = "/root/tokvi"
PXURL = "http://127.0.0.1:18899"
PX = {"http": PXURL, "https": PXURL}
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0"
PROBE = [PROBE_EMAIL, PROBE_EMAIL2]
STATE = D + "/auto_state.json"
IPV6 = ",".join("http://%s:%s@%s:8888" % (PX_USER, PX_PASS, h)
for h in (PX_HOST1, PX_HOST2, PX_HOST3, PX_HOST4))
def log(m):
line = time.strftime("%F %T ") + str(m)
print(line, flush=True)
with open(D + "/auto.log", "a") as f:
f.write(line + "\n")
def st():
try:
return json.load(open(STATE))
except Exception:
return {}
def save(d):
json.dump(d, open(STATE, "w"))
def probe():
for addr in PROBE:
try:
r = creq.get("https://tokvi.ai/api/verification", params={"email": addr},
headers={"User-Agent": UA}, impersonate="chrome124",
timeout=25, proxies=PX)
j = r.json()
if j.get("success") is True:
return True, "quota_open", addr
return False, str(j.get("message") or "no_success")[:60], addr
except Exception:
log("probe exc " + type(addr).__name__)
time.sleep(3)
return False, "probe_fail", ""
def tunnel_alive():
try:
socket.create_connection(("127.0.0.1", 18899), 5).close()
return True
except Exception:
return False
def wave(tag):
px = PXURL if tunnel_alive() else IPV6
log("WAVE start %s px=%s" % (tag, "zte" if px == PXURL else "ipv6pool"))
env = dict(os.environ, PX=px, N="70", W="5",
MAILF=D + "/mails_all.txt", USEDF=D + "/used.txt",
CREDF=D + "/creds.jsonl", OUTF=D + "/wave_%s.jsonl" % tag)
try:
subprocess.run([sys.executable, D + "/tokvi_farm.py"], env=env,
cwd=D, timeout=2400, capture_output=True)
except subprocess.TimeoutExpired:
log("WAVE timeout")
p = D + "/wave_%s.jsonl" % tag
keys = []
if os.path.exists(p):
for l in open(p):
try:
r = json.loads(l)
except Exception:
continue
if r.get("key"):
keys.append(r)
log("WAVE done keys=%d" % len(keys))
return keys
def merge():
bank = {}
if os.path.exists(D + "/bank.jsonl"):
for l in open(D + "/bank.jsonl"):
try:
r = json.loads(l)
if r.get("key"):
bank[r["key"]] = r
except Exception:
pass
if os.path.exists(D + "/creds.jsonl"):
for l in open(D + "/creds.jsonl"):
try:
r = json.loads(l)
if r.get("key") and r["key"] not in bank:
bank[r["key"]] = {"key": r["key"], "mail": r.get("mail", ""),
"ts": int(time.time())}
except Exception:
pass
with open(D + "/bank.jsonl", "w") as f:
for v in bank.values():
f.write(json.dumps(v, ensure_ascii=False) + "\n")
return len(bank)
def main():
lk = open(D + "/.cron.lock", "w")
try:
fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
return
state = st()
ok, msg, _ = probe()
for _try in range(4):
if ok or "频繁" not in msg:
break
time.sleep(6)
ok, msg, _ = probe()
log("probe: %s | %s | tunnel=%s" % (ok, msg, tunnel_alive()))
if not ok:
return
t_end = time.time() + 2400
empty = 0
while time.time() < t_end and empty < 2:
tag = time.strftime("%Y%m%d_%H%M")
keys = wave(tag)
if keys:
empty = 0
state["last_wave"] = tag
state["total_waves"] = state.get("total_waves", 0) + 1
else:
empty += 1
ok2, msg2, _ = probe()
for _try in range(3):
if ok2 or "频繁" not in msg2:
break
time.sleep(5)
ok2, msg2, _ = probe()
if not ok2:
log("quota closed: " + msg2)
break
time.sleep(20)
state["bank"] = merge()
state["last_probe_ok"] = time.strftime("%F %T")
save(state)
log("merge bank=%d" % state["bank"])
if __name__ == "__main__":
main()
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""sync_tokvi.py — банк токви с фермы -> прод iishko: новые каналы, status, abilities, model_limits.
Запуск на ферме (отдельный VPS с root-SSH). Идемпотентно, печатает 'new keys: 0' когда нечего делать.
"""
import json
import os
import subprocess
import sys
BANK = "/root/tokvi/bank.jsonl"
PROD_KEYS = "/root/tokvi_keys.json"
SSHPROD = "/root/sshprod.sh"
MODELS = ("claude-opus-5,claude-opus-4-8,claude-fable-5,claude-fable-5-1,claude-sonnet-5,"
"gpt-6-astra,gpt-6.1-terra,gpt-5.6-sol,gpt-5.6-terra,gpt-5.6-luna,grok-4.6,gpt-5.5")
GROUPS = ["default", "premium", "t1", "t2", "t3", "t4"]
PRIO = 650
def prod(cmd, timeout=900):
p = subprocess.run(["bash", SSHPROD, cmd], capture_output=True, text=True, timeout=timeout)
return p.returncode, (p.stdout or "") + (p.stderr or "")
def main():
apply = "--apply" in sys.argv
bank = []
if os.path.exists(BANK):
for l in open(BANK, encoding="utf-8", errors="replace"):
l = l.strip()
if not l.startswith("{"):
continue
try:
r = json.loads(l)
except Exception:
continue
if r.get("key"):
bank.append(r)
if not bank:
print("new keys: 0 (bank empty)")
return
rc, out = prod("cat %s 2>/dev/null" % PROD_KEYS)
try:
cur = json.loads(out)
except Exception:
cur = []
have = {x["key"] for x in cur if x.get("key")}
new = [b for b in bank if b["key"] not in have]
if not new:
print("new keys: 0")
return
print("new keys: %d (bank %d, prod %d)" % (len(new), len(bank), len(have)))
if not apply:
return
nxt = 1
for x in cur:
try:
nxt = max(nxt, int(x["name"].split("-")[1]) + 1)
except Exception:
pass
for b in new:
cur.append({"name": "tokvi-%02d" % nxt, "key": b["key"], "mail": b.get("mail", "")})
nxt += 1
payload = json.dumps(cur, ensure_ascii=False)
rc, out = prod("cat > %s <<'EOFJSON'\n%s\nEOFJSON\necho WROTE; wc -c %s" % (PROD_KEYS, payload, PROD_KEYS))
print("write:", out.strip().splitlines()[-1:])
py = r'''
import sqlite3
DB="/opt/grok-gateway/new-api/one-api.db"
MODELS="%s".split(",")
GROUPS=%s
PRIO=%d
con=sqlite3.connect(DB,timeout=300); con.execute("pragma busy_timeout=300000"); cur=con.cursor()
cur.execute("update channels set status=1, auto_ban=0, priority=? where name like 'tokvi-%%'", (PRIO,))
cids=[r[0] for r in cur.execute("select id from channels where name like 'tokvi-%%'").fetchall()]
for cid in cids:
for m in MODELS:
for g in GROUPS:
cur.execute("""insert into abilities ("group",model,channel_id,enabled,priority,weight,tag)
values (?,?,?,1,?,1,'tokvi') on conflict("group",model,channel_id) do update set enabled=1,priority=?,weight=1""",(g,m,cid,PRIO,PRIO))
patched=0
for tid,ml in cur.execute("select id,coalesce(model_limits,'') from tokens where status=1").fetchall():
have=[x for x in ml.split(",") if x]; need=[m for m in MODELS if m not in have]
if need:
cur.execute("update tokens set model_limits=? where id=?",(",".join(have+need),tid)); patched+=1
cur.execute("update users set quota = used_quota + 20000000000 where quota - used_quota < 2000000000")
con.commit()
print("tokvi channels:", cur.execute("select status,count(*) from channels where name like 'tokvi-%%' group by 1").fetchall())
print("abilities:", cur.execute("select a.model,a.enabled,count(*) from abilities a join channels c on c.id=a.channel_id where c.tag='tokvi' group by 1,2").fetchall())
print("tokens patched:", patched)
con.close()
''' % (MODELS, GROUPS, PRIO)
rc, out = prod("python3 - <<'PYEOF'\n%s\nPYEOF" % py)
print("heal:", out.strip().replace("\n", " ")[:400])
rc, out = prod("systemctl restart new-api; sleep 8; systemctl is-active new-api")
print("restart:", out.strip())
if __name__ == "__main__":
main()
+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()