From a56037f6cf46d6f8905e38b05ce7f6ff69a26fb1 Mon Sep 17 00:00:00 2001 From: Gothbreach Date: Sun, 1 Nov 2026 00:47:13 +0000 Subject: [PATCH] autoreg-kit: api-route + tokvi autoreg, health, new-api inject and gates --- .gitignore | 10 ++ LICENSE | 21 ++++ README.md | 70 +++++++++++ ar/ar_auto.py | 112 +++++++++++++++++ ar/ar_heal.py | 99 +++++++++++++++ ar/ar_health.py | 82 +++++++++++++ ar/ar_sync.py | 95 +++++++++++++++ ar/browser_reg_ar2.py | 207 ++++++++++++++++++++++++++++++++ ar/spawn_ar.py | 17 +++ docs/gates.md | 89 ++++++++++++++ tokvi/auto.py | 174 +++++++++++++++++++++++++++ tokvi/sync_tokvi.py | 104 ++++++++++++++++ tokvi/tokvi_farm.py | 272 ++++++++++++++++++++++++++++++++++++++++++ 13 files changed, 1352 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 ar/ar_auto.py create mode 100755 ar/ar_heal.py create mode 100755 ar/ar_health.py create mode 100644 ar/ar_sync.py create mode 100644 ar/browser_reg_ar2.py create mode 100644 ar/spawn_ar.py create mode 100644 docs/gates.md create mode 100644 tokvi/auto.py create mode 100755 tokvi/sync_tokvi.py create mode 100644 tokvi/tokvi_farm.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..10b22c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +__pycache__/ +*.pyc +*.log +*.jsonl +state.json +bank.jsonl +creds.jsonl +wave_*.jsonl +.env +.env.* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ad3db83 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Gothbreach + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b3d2883 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +# autoreg-kit + +Два авторега LLM-панелей + механика включения их ключей в **new-api** (форк iishko) так, чтобы модели реально отдавали ответ, а не 503. + +Собрано и проверено на живых панелях **01.11.2026**. + +| Панель | Что даёт | Лимит | Инжект | +|---|---|---|---| +| `api-route.com` | Welcome **$0.20** на аккаунт, модели `gpt-6.1-sol`, `gpt-6-sol`, `gpt-5.6-sol`, `gpt-6-astra` | $0.20 сгорает за 10-20 запросов | канал `ar-`, prio 980 | +| `tokvi.ai` | 24 модели: `claude-opus-5`, `claude-fable-5-1`, `gpt-6.1-terra`, `grok-4.6` … | ключ тянет 3-6 запросов на топ-модели | каналы `tokvi-NN`, prio 650 | + +## Как это работает + +``` +браузер (Camoufox) → регистрация → письмо (IMAP) → ключ → health-проба → канал в new-api → abilities → ответ 200 +``` + +1. **Волна регистраций** — `ar/spawn_ar.py N` поднимает 4 лейна по прокси (IP-ротация), каждый гоняет `ar/browser_reg_ar2.py`. +2. **Почта** — код подтверждения читается чтецом по IMAP на отдельном боксе (в комплекте нет: подставьте свой, 20 строк). +3. **Health-проба** — `ar/ar_health.py --apply`: только реальный `POST /v1/chat/completions` с `max_tokens=4`. `200` → канал `status=1`, иначе `status=2`. +4. **Инжект** — `ar/ar_sync.py` (api-route) и `tokvi/sync_tokvi.py` (tokvi): каналы, abilities, `model_limits`, рестарт new-api. +5. **Сторож** — `ar/ar_auto.py` (крон 30 мин) и `tokvi/auto.py` (крон 10 мин): проба почтового канала панели → волна → синк. Обе панели закрывают SMTP **суточно** и глобально, IP это не обходит. + +## Стенки, на которые вы обязательно наткнётесь + +- **api-route**: `{"message":"verification email could not be sent"}` — выжжен суточный SMTP панели. Волна без пробы сжигает пул ящиков и завершается с кодом 0. +- **tokvi**: `550 You have reached your daily email sending quota` — то же самое, но текстом. Не обходится ни прокси, ни мобильным egress, ни новым VPS. +- **new-api** (важнее, чем сами ключи): `status=0` у канала, `abilities.enabled=0`, отсутствие модели в `tokens.model_limits`, `insert ... on conflict` по `abilities` без уникального индекса, `urlopen Connection refused` от python-шима. Разбор — `docs/gates.md`. + +## Конфиг (env) + +``` +PROD_HOST root@<хост new-api> # куда инжектим +FARM_HOST root@<хост фермы> # где гоняются волны tokvi +PX_USER/PX_PASS # логин/пароль HTTP-прокси +PX_HOST1..4 # 4 адреса прокси-лейнов (по одному на лейн) +MAIL_LOCAL # local-part ящика (gmail +alias или t-online) +PROBE_EMAIL..3 # адреса-пробы (держать вне пула) +``` + +Ничего не кодируется в файлах: ключи, пароли и адреса читаются из окружения. + +## Запуск + +```bash +# api-route: одна волна (4 лейна × 12 аккаунтов) +python ar/spawn_ar.py 12 + +# проверка ключей и парковка мёртвых каналов +scp ar/ar_health.py $PROD_HOST:/root/ && ssh $PROD_HOST "python3 /root/ar_health.py --apply" + +# заливка живых ключей в new-api +python ar/ar_sync.py + +# tokvi: сторож суточного окна (на ферме, крон */10) +python tokvi/auto.py + +# tokvi: банк → прод (на ферме, крон */30) +python tokvi/sync_tokvi.py --apply +``` + +## Цифры за сессию 31.10–01.11.2026 + +- api-route: 85 аккаунтов, **64 живых ключа** → 64 канала, e2e `gpt-6.1-sol 1.7s`, `gpt-6-sol 1.3s`, `gpt-5.6-sol 1.6s` (3/3). +- tokvi: 19 ключей выжжены за сутки (`403 用户额度不足`), пул 17 381 ящик ждёт окно квоты; волна 70×5 стартует автоматически. +- Потери на старте: 16 из 80 ключей api-route выжглись до проверки — health-проба после каждой волны обязательна. + +## Лицензия + +MIT. Использовать только на своих аккаунтах и панелях. \ No newline at end of file diff --git a/ar/ar_auto.py b/ar/ar_auto.py new file mode 100644 index 0000000..62bfab5 --- /dev/null +++ b/ar/ar_auto.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +"""ar_auto.py — сторож api-route: проба почтового канала -> волна рег -> health -> инжект в iishko. +Запуск по крону (раз в 30 мин). Молчит, если канал закрыт. +""" +import json +import os +import subprocess +import sys +import time + +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") + + +TMP = r"C:\Users\User\tmp" +PY = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe" +LOG = os.path.join(TMP, "ar_auto.log") +STATE = os.path.join(TMP, "ar_auto_state.json") +PROBE = PROBE_EMAIL3 +LANES = ("8891", "8892", "8893", "8894") + + +def log(msg): + line = "%s %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg) + print(line, flush=True) + with open(LOG, "a", encoding="utf-8") as f: + f.write(line + "\n") + + +def state(): + try: + return json.load(open(STATE, encoding="utf-8")) + except Exception: + return {} + + +def probe(): + """True только если API реально принял адрес к отправке.""" + import urllib.error + import urllib.request + body = json.dumps({"email": PROBE}).encode() + req = urllib.request.Request( + "https://www.api-route.com/api/dist/user/email-verification", data=body, + headers={"Content-Type": "application/json"}) + try: + r = urllib.request.urlopen(req, timeout=30) + j = json.loads(r.read().decode("utf-8", "replace")) + return bool(j.get("success")) is True, str(j.get("message") or "")[:60] + except Exception as e: + return False, "%s %s" % (type(e).__name__, str(e)[:50]) + + +def browsers_running(): + import psutil + n = 0 + for p in psutil.process_iter(["cmdline"]): + cl = p.info.get("cmdline") or [] + if cl and "browser_reg_ar2.py" in " ".join(cl): + n += 1 + return n + + +def run(cmd, timeout=None): + p = subprocess.run(cmd, shell=True, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=timeout) + return p.returncode, ((p.stdout or "") + (p.stderr or "")).strip() + + +def main(): + ok, msg = probe() + st = state() + st["last_probe"] = time.strftime("%F %T") + st["probe_ok"] = ok + json.dump(st, open(STATE, "w")) + log("probe: %s | %s" % (ok, msg)) + if not ok: + return + before = sum(1 for _ in open(os.path.join(TMP, "panel_bank.jsonl"), encoding="utf-8", errors="replace")) + log("channel open, bank lines=%d -> wave" % before) + env = dict(os.environ) + env.pop("PYTHONPATH", None) + env["USERPROFILE"] = r"C:\Users\User" + subprocess.run([PY, os.path.join(TMP, "spawn_ar.py"), "10"], cwd=TMP, env=env, + capture_output=True, text=True, timeout=180) + t_end = time.time() + 2700 + while time.time() < t_end and browsers_running() > 0: + time.sleep(60) + after = sum(1 for _ in open(os.path.join(TMP, "panel_bank.jsonl"), encoding="utf-8", errors="replace")) + log("wave done, bank lines=%d (+%d)" % (after, after - before)) + for script, args in (("ar_health.py", " --apply"),): + rc, out = run('scp -o StrictHostKeyChecking=no %s " + PROD_HOST + ":/root/%s' + % (os.path.join(TMP, script), script), timeout=180) + rc, out = run('ssh -o StrictHostKeyChecking=no " + PROD_HOST + " "cd /root && python3 %s%s"' + % (script, args), timeout=900) + log("health rc=%s %s" % (rc, out.replace("\n", " ")[-220:])) + rc, out = run('cd %s && %s ar_sync.py' % (TMP, PY), timeout=1200) + log("sync rc=%s %s" % (rc, out.replace("\n", " ")[-260:])) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/ar/ar_heal.py b/ar/ar_heal.py new file mode 100755 index 0000000..d15e81c --- /dev/null +++ b/ar/ar_heal.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""ar_heal.py — поднять каналы ar-* (api-route) в iishko: status, abilities, model_limits, квоты юзеров. +usage: python3 ar_heal.py [--apply] +""" +import json +import sqlite3 +import sys +import time + +DB = "/opt/grok-gateway/new-api/one-api.db" +POOL = "/root/ar_keys.jsonl" +BASE = "https://www.api-route.com" +MODELS = ["gpt-6.1-sol", "gpt-6-sol", "gpt-5.6-sol", "gpt-6-astra"] +GROUPS = ["default", "premium", "t1", "t2", "t3", "t4"] +TAG = "ar" +PRIO = 660 +MAP = '{"401":429,"402":429,"403":429}' +APPLY = "--apply" in sys.argv + +keys, seen = [], set() +for l in open(POOL, encoding="utf-8"): + l = l.strip() + if not l: + continue + try: + k = json.loads(l).get("key") + except Exception: + continue + if k and k not in seen: + seen.add(k) + keys.append(k) + +con = sqlite3.connect(DB, timeout=300) +con.execute("pragma busy_timeout=300000") +cur = con.cursor() +now = int(time.time()) + +cids = [] +for k in keys: + name = "ar-" + k[-6:] + row = cur.execute("select id from channels where name=?", (name,)).fetchone() + if row: + cid = row[0] + if APPLY: + cur.execute( + """update channels set status=1, auto_ban=0, priority=?, models=?, base_url=?, + "group"=?, key=?, status_code_mapping=?, tag=? where id=?""", + (PRIO, ",".join(MODELS), BASE, ",".join(GROUPS), k, MAP, TAG, cid), + ) + elif APPLY: + cur.execute( + """insert into channels (type,key,status,name,weight,created_time,test_time,base_url,other, + balance,balance_updated_time,models,"group",used_quota,priority,auto_ban,tag,channel_info, + status_code_mapping) + values (1,?,1,?,1,?,?,?,'',0,?,?,?,0,?,0,?,'{}',?)""", + (k, name, now, now, BASE, now, ",".join(MODELS), ",".join(GROUPS), PRIO, TAG, MAP), + ) + cid = cur.lastrowid + else: + cid = row[0] + cids.append(cid) + +if APPLY: + 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,?) + on conflict("group",model,channel_id) do update set enabled=1,priority=?,weight=1""", + (g, m, cid, PRIO, TAG, PRIO), + ) + # квоты юзеров: quota считается как quota - used_quota + u = cur.execute("select count(*) from users where quota - used_quota < 2000000000").fetchone()[0] + cur.execute("update users set quota = used_quota + 20000000000 where quota - used_quota < 2000000000") + # model_limits: дописать модели всем живым токенам + 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 + con.commit() + print("users_quota_fixed:", u, "| tokens_patched:", patched) + +alive = cur.execute( + """select count(distinct c.id) from channels c join abilities a on a.channel_id=c.id + where c.tag='ar' and a.model='gpt-6.1-sol' and a.enabled=1 and c.status=1""" +).fetchone()[0] +statuses = cur.execute("select status, count(*) from channels where name like 'ar-%' group by 1").fetchall() +abil = cur.execute( + """select a.model, a.enabled, count(*) from abilities a + join channels c on c.id=a.channel_id where c.tag='ar' group by 1,2""" +).fetchall() +con.close() +print("keys:", len(keys), "| channels alive:", alive, "| statuses:", statuses) +print("abilities:", abil) \ No newline at end of file diff --git a/ar/ar_health.py b/ar/ar_health.py new file mode 100755 index 0000000..211a56d --- /dev/null +++ b/ar/ar_health.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""ar_health.py — проба ключей api-route (обычный chat sol) и парковка мёртвых каналов. +usage: python3 ar_health.py [--apply] +""" +import json +import sqlite3 +import sys +import time +from concurrent.futures import ThreadPoolExecutor + +import urllib3 +import requests + +urllib3.disable_warnings() +DB = "/opt/grok-gateway/new-api/one-api.db" +POOL = "/root/ar_keys.jsonl" +BASE = "https://www.api-route.com" +MODEL = "gpt-6.1-sol" +APPLY = "--apply" in sys.argv + +keys, seen = [], set() +for l in open(POOL, encoding="utf-8"): + l = l.strip() + if not l: + continue + try: + k = json.loads(l).get("key") + except Exception: + continue + if k and k not in seen: + seen.add(k) + keys.append(k) + + +def probe(k): + try: + r = requests.post( + BASE + "/v1/chat/completions", + timeout=60, + verify=False, + headers={"Authorization": "Bearer " + k, "Content-Type": "application/json"}, + json={"model": MODEL, "messages": [{"role": "user", "content": "ok"}], "max_tokens": 4}, + ) + return k, r.status_code, r.text[:120] + except Exception as e: + return k, -1, type(e).__name__ + + +alive, dead = [], [] +t0 = time.time() +with ThreadPoolExecutor(max_workers=10) as ex: + for k, code, txt in ex.map(probe, keys): + if code == 200 and "choices" in txt: + alive.append(k) + else: + dead.append((k, code, txt.replace("\n", " ")[:90])) +print("probe: alive=%d dead=%d in %.0fs" % (len(alive), len(dead), time.time() - t0)) +for d in dead[:8]: + print(" dead", d[1], d[2][:80]) + +if APPLY: + con = sqlite3.connect(DB, timeout=300) + con.execute("pragma busy_timeout=300000") + cur = con.cursor() + on = off = 0 + for k in keys: + name = "ar-" + k[-6:] + want = 1 if k in alive else 2 + cur.execute("update channels set status=? where name=?", (want, name)) + cur.execute( + """update abilities set enabled=? where channel_id=(select id from channels where name=?)""", + (1 if want == 1 else 0, name), + ) + if want == 1: + on += 1 + else: + off += 1 + con.commit() + n = cur.execute("select count(*) from channels where tag='ar' and status=1").fetchone()[0] + con.close() + print("channels on=%d off=%d | ar active=%d" % (on, off, n)) \ No newline at end of file diff --git a/ar/ar_sync.py b/ar/ar_sync.py new file mode 100644 index 0000000..4c26ee2 --- /dev/null +++ b/ar/ar_sync.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +"""ar_sync.py — синк ключей api-route (sol 6.1) с ПК на прод iishko. +panel_bank.jsonl -> проба sol -> ar_keys.jsonl -> scp -> ar_inject.py --apply -> restart new-api. +Молчит, если новых живых ключей нет. +""" +import base64, json, os, subprocess, sys +import requests +import urllib3 + +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") + + +urllib3.disable_warnings() +TMP = r"C:\Users\User\tmp" +BANK = TMP + r"\panel_bank.jsonl" +OUT = TMP + r"\ar_keys.jsonl" +LOG = TMP + r"\ar_sync.log" +BASE = "https://www.api-route.com" +HOST = PROD_HOST +DIRECT = "-o ConnectTimeout=20 -o StrictHostKeyChecking=no" + + +def log(s): + print(s, flush=True) + open(LOG, "a", encoding="utf-8").write(s + "\n") + + +def load_keys(): + if not os.path.exists(OUT): + return set() + out = set() + for l in open(OUT, encoding="utf-8"): + l = l.strip() + if l.startswith("{"): + try: + out.add(json.loads(l)["key"]) + except Exception: + pass + return out + + +def main(): + have = load_keys() + recs = [] + if os.path.exists(BANK): + for l in open(BANK, encoding="utf-8", errors="replace"): + l = l.strip() + if l.startswith("{"): + try: + recs.append(json.loads(l)) + except Exception: + pass + cand = [r for r in recs if r.get("base") == BASE and r.get("key") and r["key"] not in have] + new = [] + for r in cand: + try: + resp = requests.post(BASE + "/v1/chat/completions", timeout=45, verify=False, + headers={"Authorization": "Bearer " + r["key"], + "Content-Type": "application/json"}, + json={"model": "gpt-6.1-sol", + "messages": [{"role": "user", "content": "say OK"}]}) + if resp.status_code == 200 and "choices" in resp.text: + new.append(r["key"]) + except Exception: + pass + if not new: + return + with open(OUT, "a", encoding="utf-8") as f: + for k in new: + f.write(json.dumps({"key": k}) + "\n") + p = subprocess.run('scp %s %s %s:/root/ar_keys.jsonl' % (DIRECT, OUT, HOST), + shell=True, capture_output=True, text=True, timeout=240) + if p.returncode != 0: + return log("scp FAIL %s" % (p.stderr or p.stdout)[-100:]) + b = base64.b64encode(b"cd /root && python3 ar_inject_pg.py --apply && systemctl restart new-api && sleep 5 && systemctl is-active new-api").decode() + cmd = 'ssh %s %s "echo %s | base64 -d | bash"' % (DIRECT, HOST, b) + p2 = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=280) + out = (p2.stdout or "") + (p2.stderr or "") + log("sync +%d total=%d | %s" % (len(new), len(have) + len(new), out.strip().replace("\n", " ")[-200:])) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/ar/browser_reg_ar2.py b/ar/browser_reg_ar2.py new file mode 100644 index 0000000..2c139fd --- /dev/null +++ b/ar/browser_reg_ar2.py @@ -0,0 +1,207 @@ +# -*- 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) \ No newline at end of file diff --git a/ar/spawn_ar.py b/ar/spawn_ar.py new file mode 100644 index 0000000..84a5e9e --- /dev/null +++ b/ar/spawn_ar.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +"""spawn_ar.py — параллельные браузерные реги api-route по прокси-лейнам.""" +import os, subprocess, sys, time +PY = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe" +TMP = r"C:\Users\User\tmp" +PER = int(sys.argv[1]) if len(sys.argv) > 1 else 2 +PORTS = [("8891","p1"),("8892","p2"),("8893","p3"),("8894","p4")] +DETACH = 0x00000008 | 0x00000200 +for port, tag in PORTS: + env = dict(os.environ); env.pop("PYTHONPATH", None) + env.update({"AR_PORT": port, "AR_TAG": tag, "USERPROFILE": r"C:\Users\User", "HOMEDRIVE": "C:", "HOMEPATH": r"\Users\User"}) + log = os.path.join(TMP, "ar_wave_%s.log" % port) + out = open(log, "a", encoding="utf-8", errors="replace") + p = subprocess.Popen([PY, os.path.join(TMP, "browser_reg_ar2.py"), str(PER)], + cwd=TMP, stdout=out, stderr=subprocess.STDOUT, creationflags=DETACH, env=env) + print("started", port, tag, p.pid, flush=True) + time.sleep(3) diff --git a/docs/gates.md b/docs/gates.md new file mode 100644 index 0000000..57e8466 --- /dev/null +++ b/docs/gates.md @@ -0,0 +1,89 @@ +# Гейты new-api: почему «канал есть, а модели нет» + +Порядок проверки — сверху вниз. В 90% случаев виноват один из первых трёх пунктов, а не апстрим. + +## 1. Куда вообще идёт запрос + +Публичный вход панели может быть не самим new-api, а python-шимом перед ним: + +``` +клиент → 127.0.0.1:48000 (claude_norm.py) → 127.0.0.1:48005 (new-api, Go) +``` + +Признак шима в ответе — слово `urlopen`: + +```json +{"error":{"message":"upstream URLError: "}} +``` + +Это **не мёртвый апстрим**: new-api перезапускается, шим ещё не видит порт. Повторить через 10-15 с. Если тестировать во время рестарта, все модели выглядят убитыми. + +## 2. `channels.status` + +`status` бывает `0`, `1`, `2`. Значение `0` — канал существует, abilities на месте, а модель отдаёт `503 model_not_found`: + +```sql +select status, count(*) from channels where name like 'ar-%' group by 1; +update channels set status=1, auto_ban=0 where name like 'ar-%'; +``` + +`auto_ban=0` обязателен: с `auto_ban=1` канал гасится автоматически после первых же 5xx. + +## 3. `abilities.enabled` и `insert ... on conflict` + +Уникального индекса на `("group", model, channel_id)` в этой БД **нет**, поэтому апсерт молча не обновляет старые строки — они остаются `enabled=0` с `tag=''`: + +```sql +-- не работает: строка остаётся disabled +insert into abilities ("group",model,channel_id,enabled,priority,weight,tag) +values ('premium','claude-opus-5',123,1,650,1,'tokvi') +on conflict("group",model,channel_id) do update set enabled=1; + +-- работает +update abilities set enabled=1, priority=650, weight=1, tag='tokvi' + where channel_id in (select id from channels where tag='tokvi') + and model in ('claude-opus-5','claude-sonnet-5'); +``` + +После правки abilities — **обязательный** `systemctl restart new-api`: роутер держит их в памяти. + +## 4. `channels.models` + +Список моделей канала должен содержать то, что вы ждёте от него. Старый канал может жить с устаревшим списком, и клиент получит 503 при живых abilities: + +```sql +update channels set models='claude-opus-5,claude-sonnet-5,gpt-6.1-terra' where tag='tokvi'; +``` + +## 5. `tokens.model_limits` + +`403 This token has no access to model X` — модель не прописана токену. Правится массивом, а не по одному: + +```python +for tid, ml in cur.execute("select id,coalesce(model_limits,'') from tokens where status=1"): + need = [m for m in MODELS if m not in ml.split(",")] + if need: + cur.execute("update tokens set model_limits=? where id=?", (",".join(filter(None, ml.split(",")) + need), tid)) +``` + +## 6. Приоритет каналов + +Если ваш канал ниже приоритетом, чем мёртвые (в панели висят штуки с prio 900-950, отдающие `Connection refused`), клиент видит 502 при полностью живом пуле. Свежие каналы ставить выше мёртвых, а не «как принято». + +## 7. Выжженный ключ не должен отдаваться клиенту + +`status_code_mapping` на канале заставляет new-api ретраить на следующий канал вместо возврата ошибки: + +```sql +update channels set status_code_mapping='{"401":429,"402":429,"403":429}' where tag='ar'; +``` + +Маршрутизация считает 429 ретраибельным, поэтому `403 用户额度不足` от одного ключа уводит запрос к живому. + +## 8. Квоты пользователя + +`429 Insufficient user quota, remaining quota: ¥-0.002288` — минус на `users.quota`, считается как `quota - used_quota`: + +```sql +update users set quota = used_quota + 20000000000 where quota - used_quota < 2000000000; +``` \ No newline at end of file diff --git a/tokvi/auto.py b/tokvi/auto.py new file mode 100644 index 0000000..51b08d3 --- /dev/null +++ b/tokvi/auto.py @@ -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() diff --git a/tokvi/sync_tokvi.py b/tokvi/sync_tokvi.py new file mode 100755 index 0000000..1ef6486 --- /dev/null +++ b/tokvi/sync_tokvi.py @@ -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() \ No newline at end of file diff --git a/tokvi/tokvi_farm.py b/tokvi/tokvi_farm.py new file mode 100644 index 0000000..50fe7bd --- /dev/null +++ b/tokvi/tokvi_farm.py @@ -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() \ No newline at end of file