From d21f642bd365a2c122fa2e61c7f51046aad5357f Mon Sep 17 00:00:00 2001 From: reform Date: Tue, 3 Nov 2026 15:40:15 +0300 Subject: [PATCH] inferx-autoreg: GitHub OAuth via Keycloak, ix_ keys, new-api injection --- .gitignore | 11 ++ POST.md | 35 +++++++ README.md | 112 +++++++++++++++++++++ inferx_autoreg.py | 248 ++++++++++++++++++++++++++++++++++++++++++++++ inferx_watch.py | 112 +++++++++++++++++++++ inject_iishko.py | 103 +++++++++++++++++++ pick_gh.py | 50 ++++++++++ 7 files changed, 671 insertions(+) create mode 100644 .gitignore create mode 100644 POST.md create mode 100644 README.md create mode 100644 inferx_autoreg.py create mode 100644 inferx_watch.py create mode 100644 inject_iishko.py create mode 100644 pick_gh.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..95c2987 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# Банк ключей и профили браузера — не в репу +inferx_bank.jsonl +*_bank.jsonl +gh_alive_pick.json +gh_pool.jsonl +watch_state.json +cdpprof*/ +inject.sql +_watch.sql +*.log +__pycache__/ \ No newline at end of file diff --git a/POST.md b/POST.md new file mode 100644 index 0000000..fc7de80 --- /dev/null +++ b/POST.md @@ -0,0 +1,35 @@ +# Пост для канала (@AlStack) + +🦀 INFERX — FREE-ИНФЕРЕНС БЕЗ КАПЧИ, 23 КЛЮЧА ЗА ЧАС + +🩸 ЧТО ЭТО +[InferX](https://model.inferx.net/) — serverless GPU-инференс, OpenAI-совместимый, каталог из 31 модели открыт без ключа. Вход только через Keycloak (`dev4.inferx.net/authn`, realm `inferx`) с брокерами GitHub/Google. Капчи нет вообще. + +🩸 АБУЗ-ЦЕПОЧКА +1. `model.inferx.net/login?idp=github` → Keycloak → GitHub OAuth (`client_id Ov23liGv5PlgSqReHIdJ`) +2. Логин aged-GH из пула (24/25 живых: `POST github.com/session` → 302) +3. **Authorize — ровно ОДИН клик.** Второй клик = `access_denied`, аккаунт сгорает +4. Keycloak `first-broker-login`: username/email/firstName/lastName → Submit +5. Панель → `/catalog/endpoints` → кнопка Copy: в UI маска `ix_***3c88`, буфер отдаёт полный токен +6. Ключ живой сразу: `base https://model.inferx.net/endpoints/v1` + +🩸 ЧТО ДАЁТ КЛЮЧ +- deepseek-v4.1-flash-1017, 1M контекст — 200 за 1.3с +- deepseek-v4.1-flash, glm-5.3-flash, kimi-k3, qwen3.8-max, gpt-oss-20b — 200 +- deepseek-v4.1-flash-1017-basic — $0, но 429 «all replicas at capacity» +- FP8-мелкие (Qwen3.8-27B, gemma-4-31B) — 403, не в model_limits токена + +🩸 ЦИФРЫ +23 аккаунта / 23 ключа, 79% ASR (100% на живые GH), 13-48с на аккаунт. Залито в иишко 23 каналами `inferx-01..23`, 8 моделей, e2e 200 по 6 из них. + +🩸 ПОДВОДНЫЕ КАМНИ +- `GET /v1/models` → `401 tenant ... is not allowed on provider API`. Рабочий путь только `/endpoints/v1` +- Ключ тенант-скоупный, у каждого аккаунта свой +- Chrome на профиле умирает между прогонами — весь флоу гнать одним запуском +- Free-эндпоинты InferX забиты: 429 на `-basic` это норма, не бан + +🩸 РЕПА +[inferx-autoreg](https://git.reformboss.com/reform/inferx-autoreg) — регер, валидатор пула, инжект в шлюз, сторож. + +Репост 🔁 +@AlStack \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..298a045 --- /dev/null +++ b/README.md @@ -0,0 +1,112 @@ +# inferx-autoreg + +Авторег аккаунтов **InferX** (`model.inferx.net`) и ключей `ix_*` + заливка каналами в new-api. + +Флоу: GitHub OAuth → Keycloak `first-broker-login` → ключ из панели (clipboard) → проверка chat-200 → банк → инжект в шлюз. + +## Факты о цели + +| Что | Значение | +|---|---| +| Панель | `https://model.inferx.net` (маркетинг `www.inferx.net`; `inferx.ai`/`inferx.io` не резолвятся) | +| Вход | Keycloak `https://dev4.inferx.net/authn`, realm `inferx`, `client_id=infer_client`, `redirect_uri=https://model.inferx.net/auth/callback` | +| Брокеры | GitHub, Google | +| Капча | нет на всём флоу | +| GitHub OAuth app | `client_id=Ov23liGv5PlgSqReHIdJ` | +| Ключ | `ix_<64hex>`, тенант-скоупный (`tn-`), выдаётся сразу как onboarding-key | +| Рабочий base | `https://model.inferx.net/endpoints/v1` (в new-api — `.../endpoints` без `/v1`) | +| Не рабочий | `GET /v1/models` → `401 tenant ... is not allowed on provider API` (это не бан) | + +Модели с живым 200: `deepseek-v4.1-flash-1017` (1M ctx, ~1.3с), `deepseek-v4.1-flash`, `glm-5.3-flash` +(апстрим отдаёт `glm-5.3-flash-intl`), `kimi-k3`, `qwen3.8-max`, `gpt-oss-20b` (~0.4с). +`deepseek-v4.1-flash-1017-basic` помечен $0, но стабильно `429 all replicas at capacity`. +`Qwen3.8-27B-FP8`, `gemma-4-31B-it*` — 403, если имени нет в `tokens.model_limits` токена. + +## Установка + +```bash +python -m pip install playwright requests +python -m playwright install chromium # не обязательно, если используется системный Chrome +``` + +## Пул GitHub-кред + +JSONL, по строке на аккаунт: + +```json +{"login": "user", "password": "pass", "totp": "BASE32SECRET", "email": "user@example.com"} +``` + +Валидация (HTTP, без браузера): + +```bash +export INFERX_POOL=/path/gh_pool.jsonl +python pick_gh.py 50 /path/gh_pool.jsonl gh_alive_pick.json +``` + +`302` с `Location: https://github.com` = живой; `200` = пароль не подошёл. На aged-пуле выживает ~95%. + +## Регистрация + +```bash +export INFERX_POOL=/path/gh_alive_pick.json +export INFERX_BANK=/path/inferx_bank.jsonl +export INFERX_PORT=9271 +export INFERX_PROFILE=/path/cdpprof + +python inferx_autoreg.py 10 0 # 10 аккаунтов, начиная с индекса 0 +``` + +Пишет `{"login","key","ok","model","ts","sec"}` в банк. Замеры: 13-48с на аккаунт, +23/29 попыток (100% на живых GH-кредах, промахи — только мёртвые GH). + +## Инжект в new-api (PostgreSQL) + +```bash +export INFERX_SSH_HOST=root@prod-host +export INFERX_SSH_KEY=~/.ssh/id_ed25519 +export INFERX_BANK=/path/inferx_bank.jsonl + +python inject_iishko.py +``` + +Создаёт каналы `inferx-01..NN`: type=1, prio 700, группы `default,premium,t1,t2,t3,t4`, +`tag=inferx`, 8 моделей, затем abilities из `channels.models` и рестарт new-api. + +## Сторож + +```bash +export INFERX_SSH_HOST=root@prod-host +export INFERX_SSH_KEY=~/.ssh/id_ed25519 +python inferx_watch.py # молчит, если ничего не изменилось +``` + +`200` → канал включён, `401/402/403` → `status=2` + abilities off, `429`/таймаут → `flaky`, не трогаем. +Для крона: `no_agent`, каждые 30 минут. + +## Питфолы + +- **Authorize — ровно ОДИН клик.** Второй клик по странице GitHub = `access_denied`, аккаунт сгорает. +- **`Page.query_selector: Execution context was destroyed`** — элементные запросы сразу после submit с навигацией падают. + Обёрнуто в `qs()`; готовность ждать по `pg.url`, не по селектору. +- **Ключ только из clipboard.** В DOM он замаскирован (`ix_***3c88`), кнопка Copy отдаёт полный токен + (нужен `grant_permissions(['clipboard-read','clipboard-write'])`). +- **Chrome умирает между прогонами**, и один `--user-data-dir` держит только один порт — весь флоу одним прогоном. +- **Тенант создан ≠ ключ рабочий.** В прод лить только после chat-200 в апстриме. +- **`su postgres` не читает `/root`** — SQL-файл класть в `/tmp` и `chmod 644`. +- **new-api сам добавляет `/v1`** — в `base_url` канала должно быть `/endpoints`, иначе `/v1/v1/`. +- Прямых HTTP-эндпоинтов регистрации нет: Keycloak браузерный, curl-флоу не проходит. + +## Файлы + +| Файл | Назначение | +|---|---| +| `pick_gh.py` | HTTP-валидация пула GitHub-кред | +| `inferx_autoreg.py` | регер: CDP Chrome → OAuth → Keycloak → ключ → проверка | +| `inject_iishko.py` | каналы в new-api (PG) + abilities + рестарт | +| `inferx_watch.py` | health-сторож ключей/каналов | + +## Легальность + +Инструмент для работы в собственной лаборатории: аккаунты у провайдера, который сам раздаёт ключи +без капчи и верификации. Используй на свой риск и в рамках разрешённого тестирования. \ No newline at end of file diff --git a/inferx_autoreg.py b/inferx_autoreg.py new file mode 100644 index 0000000..682cbde --- /dev/null +++ b/inferx_autoreg.py @@ -0,0 +1,248 @@ +#!/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() \ No newline at end of file diff --git a/inferx_watch.py b/inferx_watch.py new file mode 100644 index 0000000..5b9c6ba --- /dev/null +++ b/inferx_watch.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""inferx_watch.py — health-сторож каналов InferX в new-api. + +Каждый ключ пробивается напрямую в апстрим (/endpoints/v1/chat/completions): + 200 -> alive -> канал status=1 + abilities enabled + 401/402/403 -> dead -> канал status=2 + abilities disabled + 429/таймаут -> flaky -> НЕ трогаем (free-эндпоинты InferX забиты, это норма) + +Печатает ТОЛЬКО при изменениях (годится для cron no_agent). + +Env: INFERX_BANK, INFERX_SSH_HOST, INFERX_SSH_KEY, INFERX_TAG (default inferx), + INFERX_STATE (default ./watch_state.json) +""" +import json, os, subprocess, sys, time + +import requests + +try: + sys.stdout.reconfigure(encoding='utf-8', errors='replace') +except Exception: + pass + +HERE = os.path.dirname(os.path.abspath(__file__)) +BANK = os.environ.get("INFERX_BANK", os.path.join(HERE, "inferx_bank.jsonl")) +STATE = os.environ.get("INFERX_STATE", os.path.join(HERE, "watch_state.json")) +HOST = os.environ.get("INFERX_SSH_HOST", "") +KEYFILE = os.environ.get("INFERX_SSH_KEY", "") +TAG = os.environ.get("INFERX_TAG", "inferx") +BASE = "https://model.inferx.net/endpoints/v1" +MODEL = "deepseek-v4.1-flash-1017" + + +def ssh(cmd, t=180): + r = subprocess.run(["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=20", + "-i", KEYFILE, HOST, cmd], + capture_output=True, text=True, timeout=t, encoding='utf-8', errors='replace') + return (r.stdout or "") + (r.stderr or "") + + +def probe(key): + try: + r = requests.post(BASE + "/chat/completions", + headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"}, + json={"model": MODEL, "messages": [{"role": "user", "content": "hi"}], "max_tokens": 4}, + timeout=40) + if r.status_code == 200: + return "alive" + if r.status_code in (401, 402, 403): + return "dead" + return "flaky" + except Exception: + return "flaky" + + +def main(): + keys, seen = [], set() + for line in open(BANK, encoding='utf-8'): + line = line.strip() + if not line: + continue + try: + d = json.loads(line) + except Exception: + continue + k = d.get('key', '') + if d.get('ok') and k.startswith('ix_') and k not in seen: + seen.add(k) + keys.append(k) + + old = {} + if os.path.exists(STATE): + try: + old = json.load(open(STATE, encoding='utf-8')) + except Exception: + old = {} + + new, changes = {}, [] + for i, k in enumerate(keys, 1): + st = probe(k) + new[k] = st + if old.get(k) != st: + changes.append(("%s-%02d" % (TAG, i), old.get(k), st)) + json.dump(new, open(STATE, 'w', encoding='utf-8'), indent=0) + if not changes: + return + + sql = [] + for i, k in enumerate(keys, 1): + name = "%s-%02d" % (TAG, i) + st = new[k] + if st == 'dead': + sql.append("update channels set status=2 where tag='%s' and name='%s';" % (TAG, name)) + sql.append("update abilities set enabled=false where channel_id in " + "(select id from channels where tag='%s' and name='%s');" % (TAG, name)) + elif st == 'alive': + sql.append("update channels set status=1 where tag='%s' and name='%s';" % (TAG, name)) + sql.append("update abilities set enabled=true where channel_id in " + "(select id from channels where tag='%s' and name='%s');" % (TAG, name)) + if sql and HOST and KEYFILE: + p = os.path.join(HERE, "_watch.sql") + open(p, 'w', encoding='utf-8').write("\n".join(sql) + "\n") + subprocess.run(["scp", "-o", "StrictHostKeyChecking=no", "-i", KEYFILE, p, HOST + ":/tmp/_watch.sql"], + capture_output=True, timeout=90) + ssh("chmod 644 /tmp/_watch.sql; su postgres -c 'psql -d newapi -q -f /tmp/_watch.sql' >/dev/null 2>&1; " + "systemctl restart new-api.service >/dev/null 2>&1") + print("INFERX WATCH %s: %d changes" % (time.strftime('%d.%m %H:%M'), len(changes))) + for n, a, b in changes: + print(" %s: %s -> %s" % (n, a or 'new', b)) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/inject_iishko.py b/inject_iishko.py new file mode 100644 index 0000000..48cc893 --- /dev/null +++ b/inject_iishko.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""inject_iishko.py — заливка ключей InferX каналами в new-api (PostgreSQL) на проде. + +Что делает: + 1. читает живой банк (ok=true, ключ ix_*) + 2. генерит SQL: delete/insert канала на каждый ключ + abilities из channels.models + 3. кладёт файл в /tmp на сервере (postgres не читает /root), применяет через su postgres + 4. рестарт new-api (кэш abilities) + +Env: + INFERX_BANK банк ключей (default ./inferx_bank.jsonl) + INFERX_SSH_HOST root@host (обязательно) + INFERX_SSH_KEY путь к приватному ключу (обязательно) + INFERX_BASE base_url канала (default https://model.inferx.net/endpoints) + INFERX_MODELS модели через запятую (default набор ниже) + INFERX_PRIO priority канала (default 700) + INFERX_TAG tag каналов (default inferx) + +Внимание: new-api сам добавляет /v1 к base_url, поэтому в канале /endpoints БЕЗ /v1. +Условие приёмки — chat/completions 200 и после инжекта, и в апстриме. +""" +import json, os, subprocess, sys, time + +try: + sys.stdout.reconfigure(encoding='utf-8', errors='replace') +except Exception: + pass + +HERE = os.path.dirname(os.path.abspath(__file__)) +BANK = os.environ.get("INFERX_BANK", os.path.join(HERE, "inferx_bank.jsonl")) +HOST = os.environ.get("INFERX_SSH_HOST", "") +KEYFILE = os.environ.get("INFERX_SSH_KEY", "") +BASE = os.environ.get("INFERX_BASE", "https://model.inferx.net/endpoints") +MODELS = [m.strip() for m in os.environ.get( + "INFERX_MODELS", + "deepseek-v4.1-flash-1017,deepseek-v4.1-flash,glm-5.3-flash,gpt-oss-20b," + "Qwen3.8-27B-FP8,kimi-k3,qwen3.8-max,gemma-4-31B-it-fp8").split(",") if m.strip()] +PRIO = int(os.environ.get("INFERX_PRIO", "700")) +TAG = os.environ.get("INFERX_TAG", "inferx") + + +def ssh(cmd, timeout=240): + r = subprocess.run(["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=20", + "-i", KEYFILE, HOST, cmd], + capture_output=True, text=True, timeout=timeout, encoding='utf-8', errors='replace') + return (r.stdout or "") + (r.stderr or "") + + +def main(): + if not HOST or not KEYFILE: + print("нужны INFERX_SSH_HOST и INFERX_SSH_KEY") + sys.exit(2) + keys, seen = [], set() + for line in open(BANK, encoding='utf-8'): + line = line.strip() + if not line: + continue + try: + d = json.loads(line) + except Exception: + continue + k = d.get('key', '') + if d.get('ok') and k.startswith('ix_') and k not in seen: + seen.add(k) + keys.append(k) + print("keys:", len(keys)) + if not keys: + sys.exit(0) + + models = ",".join(MODELS) + sql = [] + for i, k in enumerate(keys, 1): + name = "%s-%02d" % (TAG, i) + sql.append("delete from channels where name='%s';" % name) + sql.append( + "insert into channels (type,name,\"key\",base_url,models,\"group\",priority,weight,status," + "auto_ban,model_mapping,created_time,tag) values " + "(1,'%s','%s','%s','%s','default,premium,t1,t2,t3,t4',%d,0,1,0,'',%d,'%s');" + % (name, k, BASE, models, PRIO, int(time.time()), TAG)) + sql.append(""" +insert into abilities ("group",model,channel_id,enabled,priority,weight,tag) +select g.grp, trim(m.model), c.id, true, c.priority, 0, c.tag +from channels c +cross join lateral unnest(string_to_array(c."group",',')) g(grp) +cross join lateral unnest(string_to_array(c.models,',')) m(model) +where c.tag='%s' and c.status=1 and trim(m.model)<>'' +on conflict ("group",model,channel_id) do update set enabled=true, priority=excluded.priority; +""" % TAG) + + local = os.path.join(HERE, "inject.sql") + open(local, "w", encoding="utf-8").write("\n".join(sql)) + print("sql bytes:", os.path.getsize(local)) + r = subprocess.run(["scp", "-o", "StrictHostKeyChecking=no", "-i", KEYFILE, local, HOST + ":/tmp/inject.sql"], + capture_output=True, text=True, timeout=120, encoding='utf-8', errors='replace') + print("scp rc", r.returncode, (r.stderr or '').strip()[:120]) + out = ssh("chmod 644 /tmp/inject.sql; su postgres -c 'psql -d newapi -At -f /tmp/inject.sql' 2>&1 | tail -4; " + "su postgres -c \"psql -d newapi -At -c \\\"select id,name,status,priority from channels where tag='%s' order by id\\\"\" 2>&1" % TAG) + print(out[-900:]) + print("restart:", ssh("systemctl restart new-api.service; sleep 6; systemctl is-active new-api.service").strip()[:80]) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pick_gh.py b/pick_gh.py new file mode 100644 index 0000000..fa2492d --- /dev/null +++ b/pick_gh.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""pick_gh.py — HTTP-валидация пула GitHub-кред перед авторегом. + +Формат входа (JSONL): {"login": "...", "password": "...", "totp": "...", "email": "..."} +Проверка: GET github.com/login -> authenticity_token -> POST github.com/session. +302 c Location на github.com (не /session) = кред живой; 200 = пароль не подошёл. + +Запуск: python pick_gh.py [N] [файл_пула] [файл_выхода] +""" +import json, os, re, sys, time +import requests + +try: + sys.stdout.reconfigure(encoding='utf-8', errors='replace') +except Exception: + pass + +POOL = sys.argv[2] if len(sys.argv) > 2 else os.environ.get("INFERX_POOL", "gh_pool.jsonl") +OUT = sys.argv[3] if len(sys.argv) > 3 else os.path.join(os.path.dirname(os.path.abspath(__file__)), "gh_alive_pick.json") +N = int(sys.argv[1]) if len(sys.argv) > 1 else 25 +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36" + +accts = [json.loads(l) for l in open(POOL, encoding='utf-8') if l.strip()][:N] +alive = [] +for i, a in enumerate(accts, 1): + s = requests.Session() + s.headers.update({"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"}) + try: + r = s.get("https://github.com/login", timeout=25) + tok = re.search(r'name="authenticity_token" value="([^"]+)"', r.text) + if not tok: + print(i, a['login'], "no-token", r.status_code) + continue + r2 = s.post("https://github.com/session", + data={"commit": "Sign in", "authenticity_token": tok.group(1), + "login": a['login'], "password": a['password'], + "webauthn-conditional": "undefined", "javascript-support": "true", + "webauthn-support": "supported", "return_to": ""}, + timeout=30, allow_redirects=False) + loc = r2.headers.get('Location', '') + ok = r2.status_code in (301, 302) and '/session' not in loc + print(i, a['login'], r2.status_code, loc[:60], "ALIVE" if ok else "") + if ok: + alive.append(a) + except Exception as e: + print(i, a['login'], "ERR", type(e).__name__) + time.sleep(1.0) + +print("alive:", len(alive), [a['login'] for a in alive][:10]) +json.dump(alive, open(OUT, "w", encoding="utf-8"), ensure_ascii=False, indent=1) \ No newline at end of file