From 5a1403aa9834bd113e264555b13a9ca138143c9f Mon Sep 17 00:00:00 2001 From: reform Date: Sun, 15 Nov 2026 17:35:52 +0200 Subject: [PATCH] coarena autoreg: multikey farm + rotator shim --- README.md | 59 ++++++++++++ acct_usage.py | 77 ++++++++++++++++ bm.py | 204 +++++++++++++++++++++++++++++++++++++++++ coa_cron_wave.py | 99 ++++++++++++++++++++ coa_lot.py | 55 +++++++++++ coa_one.py | 219 ++++++++++++++++++++++++++++++++++++++++++++ coa_pool_sync.py | 179 ++++++++++++++++++++++++++++++++++++ coa_rot_watch.py | 71 +++++++++++++++ coa_shim.py | 227 ++++++++++++++++++++++++++++++++++++++++++++++ coa_sync.py | 106 ++++++++++++++++++++++ coa_sync_cron.py | 48 ++++++++++ coa_wave.py | 43 +++++++++ gh_oauth_check.py | 82 +++++++++++++++++ mixr_claim.py | 124 +++++++++++++++++++++++++ proxy_multi.py | 176 +++++++++++++++++++++++++++++++++++ 15 files changed, 1769 insertions(+) create mode 100644 README.md create mode 100644 acct_usage.py create mode 100644 bm.py create mode 100644 coa_cron_wave.py create mode 100644 coa_lot.py create mode 100644 coa_one.py create mode 100644 coa_pool_sync.py create mode 100644 coa_rot_watch.py create mode 100644 coa_shim.py create mode 100644 coa_sync.py create mode 100644 coa_sync_cron.py create mode 100644 coa_wave.py create mode 100644 gh_oauth_check.py create mode 100644 mixr_claim.py create mode 100644 proxy_multi.py diff --git a/README.md b/README.md new file mode 100644 index 0000000..8f77049 --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ +# coarena-autoreg + +Авторегистрация и ферма ключей на coarena.ai с купленных Google-аккаунтов + OpenAI-совместимый ротатор. + +## Что делает + +1. Берёт Google-аккаунты (`10 min - 10 day` почта с bulkmail.shop) и логинится через Google OAuth в coarena. +2. Забирает **до 10 ключей на аккаунт** (`/api/me/keys`) — потолок сервиса. +3. Складывает полные ключи `coa_<32hex>` в банк (`keys_bank2.jsonl`), фейлы — в `keys_fail.jsonl`. +4. Ротатор `coa_shim.py` поднимает один OpenAI-совместимый фронт на `:48960`, кольцует ключи, кулдаунит мёртвые, маппит имена моделей на реальный каталог coarena. +5. new-api (iishko) забирает этот фронт каналом `coa-gw-01`. + +## Каталог coarena (проверено GET /api/v1/models) + +``` +deepseek-v4-1-flash-1017 gemini-3-8-flash gemini-4-argon gemini-4-carbon +gpt-6-1-sol gpt-6-1-terra gpt-6-astra gpt-6-luna grok-4-7 kimi-k3-1-pro +``` + +claude-* у coarena отключён апстримом (`turned off`), glm/mimo/qwen3.8-max в каталоге отсутствуют — они в `MODELS_OFF` ротатора и отдают честный 400. + +## Файлы + +| Файл | Назначение | +|------|-----------| +| `coa_one.py` | воркер на один аккаунт: Chrome CDP → Google OAuth → 10 ключей | +| `coa_cron_wave.py` | порция аккаунтов для крона (N за прогон, воркеры, lock, state) | +| `coa_sync_cron.py` | сбор ключей из банка и заливка на прод-ротатор | +| `coa_shim.py` | прод-ротатор (OpenAI-совместимый, `/v1/chat/completions`) | +| `coa_wave.py`, `coa_lot.py`, `coa_pool_sync.py`, `acct_usage.py` | вспомогательные | +| `proxy_multi.py`, `coa_rot_watch.py` | прокси-слой и сторож | +| `bm.py` | закупка аккаунтов (bulkmail.shop API v2) | + +## Запуск + +```bash +export COA_HOME=/path/to/work +export COA_N=18 COA_WORKERS=3 COA_BUDGET=540 +python coa_cron_wave.py +``` + +Ротатор: + +```bash +COA_PORT=48960 COA_KEYS=/opt/coa-shim/coa_keys.txt python3 coa_shim.py +``` + +## Грабли (проверено) + +- Воркеров **не больше 3**: на 4 Chrome рвёт CDP, аккаунт сгорает (`not_logged`). +- Аккаунты живут часы — регистрировать надо сразу после покупки. +- Часть аккаунтов отдаёт `409 key_limit` (10 ключей уже выбраны) — это норма, пропускается. +- Имена моделей у coarena с дефисами: `gpt-6.1-sol` → `gpt-6-1-sol`; запрос с точкой даёт 404. +- `400 usage limits ... regain access on ` — ключ нельзя ретраить, только кулдаун до даты. +- Прокси обязателен: один IP быстро упирается в лимит регистраций. + +## Очередь/бюджет + +Куплено через `bm.py buy `; порог цены и выбор лота — скилл `bulkmail-cheapest-lot`. \ No newline at end of file diff --git a/acct_usage.py b/acct_usage.py new file mode 100644 index 0000000..a7783f5 --- /dev/null +++ b/acct_usage.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Замер суточного потребления coarena по АККАУНТАМ (не по ключам). + +Почему не по ключам: все 10 ключей одного аккаунта отдают ОДИН И ТОТ ЖЕ +`used_usd` (лимит $5/сутки общий на аккаунт). Выборка по ключам видит аккаунт +столько раз, сколько у него ключей, и завышает сумму в ~9 раз. + +Запуск: python acct_usage.py [N_аккаунтов] [путь_к_keys_bank.jsonl] +""" +import json +import random +import sys +import urllib.error +import urllib.request +from concurrent.futures import ThreadPoolExecutor + +PATH = sys.argv[2] if len(sys.argv) > 2 else r"C:/Users/User/tmp/coarena/keys_bank.jsonl" +N = int(sys.argv[1]) if len(sys.argv) > 1 else 120 + +rows = [] +bad = 0 +for line in open(PATH, encoding="utf8"): + line = line.strip() + if not line: + continue + try: + rows.append(json.loads(line)) + except Exception: + bad += 1 # живая волна дописывает файл, хвостовая строка рвётся + +by = {} +for r in rows: + by.setdefault(r["email"], []).append(r["key"]) +accts = list(by) +print("строк ok: %d | битых: %d | аккаунтов: %d" % (len(rows), bad, len(accts))) +random.seed(23) +sample = random.sample(accts, min(N, len(accts))) + + +def probe(acc): + req = urllib.request.Request("https://coarena.ai/api/v1/limits", + headers={"Authorization": "Bearer " + by[acc][0]}) + try: + with urllib.request.urlopen(req, timeout=25) as x: + d = json.loads(x.read().decode()) + t = (d.get("data") or {}).get("today") or {} + return float(t.get("used_usd") or 0), int(t.get("requests") or 0), None + except urllib.error.HTTPError as e: + return None, None, e.code + except Exception as e: + return None, None, type(e).__name__ + + +with ThreadPoolExecutor(max_workers=12) as ex: + res = list(ex.map(probe, sample)) +ok = [r for r in res if r[0] is not None] +errs = {} +for r in res: + if r[0] is None: + errs[r[2]] = errs.get(r[2], 0) + 1 +if not ok: + print("все пробы упали:", errs) + raise SystemExit(1) + +tot = sum(r[0] for r in ok) +reqs = sum(r[1] for r in ok) +zero = sum(1 for r in ok if r[0] == 0) +spent = sum(1 for r in ok if r[0] > 0) +capped = sum(1 for r in ok if r[0] >= 4.9) +avg = tot / len(ok) +print("выборка %d акк | ok %d | ошибки %s" % (len(sample), len(ok), errs)) +print("сумма used_usd: $%.2f | запросов: %d" % (tot, reqs)) +print("нулевых %d (%.0f%%) | с расходом %d | упёрлись в $5: %d" + % (zero, 100 * zero / len(ok), spent, capped)) +print("средний на аккаунт: $%.4f | медиана: $%.4f" % (avg, sorted(r[0] for r in ok)[len(ok) // 2])) +print("ЭКСТРАПОЛЯЦИЯ на %d аккаунтов: $%.0f/сутки (потолок $%d)" + % (len(accts), avg * len(accts), 5 * len(accts))) diff --git a/bm.py b/bm.py new file mode 100644 index 0000000..9327b5c --- /dev/null +++ b/bm.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""bulkmail.shоп API v2 — баланс / сток / покупка / восстановление выдачи. + +Дока: https://bulkmail.shop/v2-docs (+ openapi.yaml, postman.json, api-v2.md) +Auth: заголовок X-API-Key: sk_live_... (НЕ Bearer). +Ключ: env BM_KEY или KEY="..." в одном из локальных скриптов закупки. + +Запуск (Python311, без PYTHONPATH): + bm.py balance + bm.py stock [фильтр] # только in_stock, по возрастанию цены + bm.py buy # купить; строки восстанавливаются через /purchases + bm.py pull [order_id] # вытянуть ВСЕ выданные строки (история аккаунта) + bm.py domains [order_id] # состав доменов — проверка ПЕРЕД партией + +Питфолы, заложенные в код: + * POST /orders может НЕ содержать items — источник истины GET /purchases?order_id= + * третье поле строки бывает текстом-комментарием (email|pass|Đọc mail tại ...) + * FB-клоны отбрасываются по c_user=/xs=/datr=, а НЕ по числу полей +""" +import json +import os +import re +import sys +import urllib.error +import urllib.request + +BASE = "https://bulkmail.shop/api/v2" +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/141" +OUT = os.path.join(os.environ.get("BM_OUT_DIR", "C:/Users/User/tmp"), "bm_purchases.jsonl") +FB_MARKERS = ("c_user=", "xs=", "datr=", "EAAG", "EAAD") + + +def load_key(): + k = os.environ.get("BM_KEY") + if k: + return k.strip() + for p in ("C:/Users/User/tmp/bm_buy.py", "C:/Users/User/tmp/buy_batch.py"): + try: + t = open(p, encoding="utf8").read() + m = re.search(r'KEY\s*=\s*"([^"]+)"', t) + if m: + return m.group(1) + except FileNotFoundError: + pass + sys.exit("нет ключа: положи BM_KEY в env или KEY= в bm_buy.py") + + +def api(path, method="GET", body=None): + h = {"User-Agent": UA, "X-API-Key": KEY, "Accept": "application/json"} + data = None + if body is not None: + h["Content-Type"] = "application/json" + data = json.dumps(body).encode() + req = urllib.request.Request(BASE + path, headers=h, method=method, data=data) + try: + with urllib.request.urlopen(req, timeout=60) as r: + return r.status, json.loads(r.read().decode()) + except urllib.error.HTTPError as e: + try: + return e.code, json.loads(e.read().decode()) + except Exception: + return e.code, None + except Exception as e: + return 0, {"error": type(e).__name__} + + +def parse_lines(rows): + """rows — записи из /purchases. Вернёт [(email, password)] без FB-мусора.""" + out = [] + for r in rows: + ln = (r.get("data") if isinstance(r, dict) else r) or "" + if isinstance(ln, dict): + ln = ln.get("data") or "" + if any(m in ln for m in FB_MARKERS): + continue + parts = [p.strip() for p in str(ln).split("|")] + if len(parts) < 2 or "@" not in parts[0]: + continue + out.append((parts[0].lower(), parts[1])) + return out + + +def cmd_balance(): + st, d = api("/wallet/balance") + if st != 200 or not d: + sys.exit(f"HTTP {st}: {d}") + print(f"balance: ${d['data']['balance']:.6f}") + + +def cmd_stock(flt=""): + rows, page = [], 1 + while True: + st, d = api(f"/products?per_page=100&page={page}&in_stock=true&sort=price&order=asc") + if st != 200 or not d or not d.get("data"): + break + for i in d["data"]: + txt = f"{i.get('name','')} {i.get('description_text') or ''}".lower() + if not flt or flt.lower() in txt: + rows.append(i) + if page >= (d.get("meta") or {}).get("total_pages", 1): + break + page += 1 + rows.sort(key=lambda x: float(x.get("price") or 0)) + print(f"{'ID':<7}{'PRICE':<11}{'STOCK':<8}NAME") + for i in rows[:40]: + print(f"#{i['id']:<6}${float(i['price']):<10.6f}{i['stock_quantity']:<8}{i['name'][:52]}") + print(f"\nв наличии (фильтр '{flt}'): {len(rows)}") + + +def pull_rows(order_id=None): + rows, page = [], 1 + while True: + q = f"/purchases?per_page=100&page={page}" + (f"&order_id={order_id}" if order_id else "") + st, d = api(q) + if st != 200 or not d or not d.get("data"): + if page == 1: + sys.exit(f"HTTP {st}: {d}") + break + rows += d["data"] + if page >= (d.get("meta") or {}).get("total_pages", 1): + break + page += 1 + return rows, (d.get("meta") or {}).get("total", len(rows)) if d else len(rows) + + +def cmd_buy(pid, qty): + pid, qty = int(pid), int(qty) + st, p = api(f"/products/{pid}") + if st != 200 or not p: + sys.exit(f"лот недоступен: HTTP {st}") + pr = p["data"] + cost = float(pr["price"]) * qty + print(f"лот #{pid} ${float(pr['price']):.6f} x{qty} = ${cost:.4f} | stock={pr['stock_quantity']}") + if (pr.get("stock_quantity") or 0) < qty: + sys.exit(f"мало на складе: {pr['stock_quantity']}") + st, d = api("/orders", "POST", {"product_id": pid, "quantity": qty}) + if st not in (200, 201) or not d or not d.get("success"): + sys.exit(f"заказ не прошёл: HTTP {st} {d}") + o = d["data"] + oid = o.get("order_id") or o.get("id") + print(f"order {oid} status={o.get('status')} balance_after=${o.get('balance_remaining', '?')}") + # items может отсутствовать ИЛИ быть списком строк — источник истины /purchases + rows, total = pull_rows(oid) + pairs = parse_lines(rows) + with open(OUT, "a", encoding="utf8") as f: + for em, pw in pairs: + f.write(json.dumps({"order": oid, "product": pid, "email": em, "password": pw}, + ensure_ascii=False) + "\n") + print(f"выдано по meta.total={total}, распознано пар: {len(pairs)} -> {OUT}") + if total and len(pairs) != total: + print(f"ВНИМАНИЕ: {total - len(pairs)} строк отброшено (FB-маркеры или битый формат)") + for em, _ in pairs[:5]: + print(" ", em) + + +def cmd_pull(order_id=None): + rows, total = pull_rows(order_id) + pairs = parse_lines(rows) + with open(OUT, "a", encoding="utf8") as f: + for em, pw in pairs: + f.write(json.dumps({"email": em, "password": pw}, ensure_ascii=False) + "\n") + print(f"meta.total={total} | распознано {len(pairs)} -> {OUT}") + + +def cmd_domains(order_id=None): + """Состав доменов в выдаче — проверка ПЕРЕД партией. + + Один product_id в разных партиях отдаёт разные домены, и мёртвый домен + (0 ключей на десятках адресов) обнуляет всю партию. Купить 3 шт, вызвать + `bm.py domains`, и партию брать только из лота с подтверждённым доменом. + """ + rows, total = pull_rows(order_id) + pairs = parse_lines(rows) + from collections import Counter + c = Counter(em.split("@")[-1] for em, _ in pairs) + print(f"meta.total={total} | распознано {len(pairs)}") + for d, n in c.most_common(): + print(f" {d:<32} {n}") + if len(c) > 1: + print("ВНИМАНИЕ: домены смешаны — класс подтверждать пробой coa_one.py на 2-3 адресах") + + +if __name__ == "__main__": + for s in (sys.stdout, sys.stderr): + try: + s.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + KEY = load_key() + if len(sys.argv) < 2: + sys.exit(__doc__) + c = sys.argv[1] + if c == "balance": + cmd_balance() + elif c == "stock": + cmd_stock(sys.argv[2] if len(sys.argv) > 2 else "") + elif c == "buy" and len(sys.argv) == 4: + cmd_buy(sys.argv[2], sys.argv[3]) + elif c == "pull": + cmd_pull(sys.argv[2] if len(sys.argv) > 2 else None) + elif c == "domains": + cmd_domains(sys.argv[2] if len(sys.argv) > 2 else None) + else: + sys.exit(__doc__) diff --git a/coa_cron_wave.py b/coa_cron_wave.py new file mode 100644 index 0000000..ea91619 --- /dev/null +++ b/coa_cron_wave.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Cron-порция волны coarena: берёт следующие N аккаунтов из очереди. + +Запускается cron'ом каждые 10 минут. State: cron_state.json +Останавливается, когда очередь исчерпана (пишет cron_done.flag). +""" +import json +import os +import subprocess +import sys +import time + +BASE = "C:/Users/User/tmp/coarena" +PYEXE = r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe" +S = r"C:/Users/User/AppData/Local/hermes/skills/autoreg/coarena-autoreg/scripts/coa_one.py" +STATE = BASE + "/cron_state.json" +LOCKF = BASE + "/cron.lock" +QUEUE = BASE + "/order_cron.txt" +LOG = BASE + "/cron_wave.log" + +N = int(os.environ.get("COA_N", "18")) # аккаунтов за прогон +TIME_BUDGET = int(os.environ.get("COA_BUDGET", "540")) # секунд на прогон +WORKERS = int(os.environ.get("COA_WORKERS", "3")) + + +def log(msg): + with open(LOG, "a", encoding="utf8") as f: + f.write("%s %s\n" % (time.strftime("%H:%M:%S"), msg)) + + +def take_lock(): + import os as _os + try: + if _os.path.exists(LOCKF) and time.time() - _os.path.getmtime(LOCKF) < 900: + return False + open(LOCKF, "w").write(str(_os.getpid())) + return True + except Exception: + return True + + +def main(): + if not take_lock(): + print("locked, skip") + return + queue = [int(l) for l in open(QUEUE) if l.strip()] + st = {"pos": 0, "done": 0, "keys_start": 0} + if os.path.exists(STATE): + try: + st = json.load(open(STATE)) + except Exception: + pass + + if st["pos"] >= len(queue): + open(BASE + "/cron_done.flag", "w").write("done") + log("очередь исчерпана (%d/%d)" % (st["pos"], len(queue))) + return + + chunk = queue[st["pos"]: st["pos"] + N] + env = dict(os.environ) + env["COA_HOME"] = BASE + env["COA_CHROME_UP"] = "C:/Users/User/tmp/agentrouter/chrome_up.py" + env["OA_PORT_BASE"] = "8100" + env.pop("PYTHONPATH", None) + env["PYTHONIOENCODING"] = "utf-8" + + import concurrent.futures as cf + + def run(i): + try: + r = subprocess.run([PYEXE, "-u", S, str(i)], env=env, timeout=280, + capture_output=True, text=True, errors="replace") + return (i, r.returncode) + except Exception as e: + return (i, type(e).__name__) + + t0 = time.time() + ok = 0 + with cf.ThreadPoolExecutor(WORKERS) as ex: + futs = {ex.submit(run, i): i for i in chunk} + for fut in cf.as_completed(futs, timeout=TIME_BUDGET + 120): + i, rc = fut.result() + if rc == 0: + ok += 1 + log("idx=%d rc=%s" % (i, rc)) + # отмечаем прогресс сразу — при обрыве не потеряем + st["pos"] = queue.index(i) + 1 + st["done"] = st.get("done", 0) + 1 + json.dump(st, open(STATE, "w")) + + log("порция готова: %d/%d ok, %.0fs, pos=%d/%d" % (ok, len(chunk), time.time() - t0, st["pos"], len(queue))) + + +if __name__ == "__main__": + try: + pass + except Exception: + pass + main() \ No newline at end of file diff --git a/coa_lot.py b/coa_lot.py new file mode 100644 index 0000000..52f6e8d --- /dev/null +++ b/coa_lot.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""coa_lot.py — прогон НОВОГО лота БЕЗ резюма по idx. + +Зачем: coa_wave.py резюмит по idx из keys_bank/keys_fail, поэтому новый банк, +у которого idx начинается с нуля, он считает «уже сделанным» и запускает 0 задач. +coa_lot гоняет range(N) вслепую — для новых лотов и повторных проходов по фейлам. + +Env: + COA_HOME каталог coarena (default C:/Users/User/tmp/coarena) + COA_PY python (default Python311) + COA_CHROME_UP chrome_up.py (default /ctxdev/chrome_up.py) + OA_PORT_BASE база портов (default 9400); порт = base + idx, уникальный на воркер + COA_OFFSET смещение для профилей/портов, чтобы не драться с прошлыми банками + CTX_CHROME_PROXY напр. http://127.0.0.1:8899 (ZTE) — убирает Google challenge +""" +import os +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor + +BASE = os.environ.get("COA_HOME", "C:/Users/User/tmp/coarena") +PY = os.environ.get("COA_PY", r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe") +BANK = os.environ.get("COA_BANK_FILE", BASE + "/gmail_bank.jsonl") +ENV = dict(os.environ) +ENV.pop("PYTHONPATH", None) +ENV["PYTHONIOENCODING"] = "utf-8" + + +def run_one(idx): + try: + r = subprocess.run([PY, BASE + "/coa_one.py", str(idx), BANK], cwd=BASE, env=ENV, + timeout=420, capture_output=True, text=True) + return idx, r.returncode, (r.stderr or "")[-140:] + except Exception as e: # timeout / спавн + return idx, -1, str(e)[:140] + + +def main(): + global BANK + total = int(sys.argv[1]) if len(sys.argv) > 1 else 10 + workers = int(sys.argv[2]) if len(sys.argv) > 2 else 3 + if len(sys.argv) > 3: + BANK = sys.argv[3] + if not os.path.isabs(BANK): + BANK = os.path.join(BASE, BANK) + ok = 0 + with ThreadPoolExecutor(workers) as ex: + for idx, rc, err in ex.map(run_one, range(total)): + ok += rc == 0 + print("idx=%d rc=%d %s" % (idx, rc, err.strip()[:60]), flush=True) + print("LOT DONE attempts=%d/%d" % (ok, total)) + + +if __name__ == "__main__": + main() diff --git a/coa_one.py b/coa_one.py new file mode 100644 index 0000000..7c1b5ed --- /dev/null +++ b/coa_one.py @@ -0,0 +1,219 @@ +# One coarena account -> one working coa_ key. Usage: python coa_one.py +# Env: COA_HOME (dir with gmail_bank.jsonl, default C:/Users/User/tmp/coarena) +# COA_CHROME_UP (chrome_up.py path), COA_PY (python exe), OA_PORT_BASE (default 9400) +import json +import os +import subprocess +import sys +import time + +import psutil +from playwright.sync_api import sync_playwright + +BASE = os.environ.get("COA_HOME", "C:/Users/User/tmp/coarena") +PY = os.environ.get("COA_PY", r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe") +CHROME_UP = os.environ.get("COA_CHROME_UP", "C:/Users/User/tmp/ctxdev/chrome_up.py") +PORT_BASE = int(os.environ.get("OA_PORT_BASE", "9400")) +BANK = BASE + "/keys_bank.jsonl" +FAIL = BASE + "/keys_fail.jsonl" +NL2 = chr(10) + "---" + chr(10) +PROXY_FILE = "C:/Users/User/tmp/proxfarm/proxies_https.txt" + + +ZTE = "http://127.0.0.1:8899" # мобильный 89.209.x — проходит Google + + +def proxy_candidates(idx, n=3): + """Список прокси: сначала свой по idx, затем следующие по кругу.""" + import socket + try: + pool = [l.strip() for l in open(PROXY_FILE, encoding="utf8") if l.strip()] + except FileNotFoundError: + pool = [] + out = [] + if pool: + for k in range(n): + out.append("http://" + pool[(idx + k) % len(pool)]) + try: + s = socket.create_connection(("127.0.0.1", 8899), timeout=3) + s.close() + out.append(ZTE) + except Exception: + pass + return out + + +def proxy_works(px, timeout=6): + """Прокси реально тянет HTTPS к Google?""" + import socket + try: + host, _, port = px.replace("http://", "").rpartition(":") + s = socket.create_connection((host, int(port)), timeout=timeout) + s.settimeout(timeout) + s.sendall(b"CONNECT www.google.com:443 HTTP/1.1" + chr(13) + chr(10) + + b"Host: www.google.com:443" + chr(13) + chr(10) + chr(13) + chr(10)) + resp = s.recv(200) + s.close() + return b" 200" in resp + except Exception: + return False + + +def pick_working_proxy(idx): + for px in proxy_candidates(idx, 3): + if proxy_works(px): + return px + return "" + + +def log(msg): + with open(BASE + "/wave.log", "a", encoding="utf8") as fh: + fh.write(time.strftime("%H:%M:%S ") + msg + "\n") + + +def kill_chrome(tag): + """Stale chrome on the same profile = ECONNREFUSED on every later step.""" + for pr in psutil.process_iter(["pid", "cmdline"]): + cmd = " ".join(pr.info["cmdline"] or []) + if "chrome.exe" in cmd and tag in cmd: + try: + pr.kill() + except Exception: + pass + + +def boot(prof, port, proxy=""): + env = dict(os.environ) + env["CTX_CHROME_PROF"] = prof + env["CTX_CDP_PORT"] = str(port) + if proxy: + env["CTX_CHROME_PROXY"] = proxy + env.pop("PYTHONPATH", None) + try: + subprocess.run([PY, CHROME_UP], env=env, timeout=120, capture_output=True) + except Exception: + pass + import urllib.request + for _ in range(40): + try: + with urllib.request.urlopen("http://127.0.0.1:%d/json/version" % port, timeout=3) as r: + if r.status == 200: + return True + except Exception: + time.sleep(1) + return False + + +def main(): + idx = int(sys.argv[1]) + rec = [json.loads(l) for l in open(BASE + "/gmail_bank.jsonl", encoding="utf8") if l.strip()][idx] + prof, port = "%s/prof/%d" % (BASE, idx), PORT_BASE + idx + os.makedirs(prof, exist_ok=True) + kill_chrome(prof) + px = pick_working_proxy(idx) + boot(prof, port, px) + out = {"email": rec["email"], "key": None, "ok": False, "stage": "start", "idx": idx, "proxy": px} + try: + with sync_playwright() as p: + ctx = p.chromium.connect_over_cdp("http://127.0.0.1:%d" % port).contexts[0] + page = ctx.pages[0] if ctx.pages else ctx.new_page() + # ШАГ 1: прямой логин в Google (форма OAuth-попапа не принимает ввод) + page.goto("https://accounts.google.com/ServiceLogin?hl=en", wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(2500) + if page.locator("input[name=identifier], input[type=email]").count(): + el = page.wait_for_selector("input[name=identifier], input[type=email]", state="visible", timeout=30000) + el.click() + el.type(rec["email"], delay=35) + page.wait_for_timeout(500) + el.press("Enter") + page.wait_for_timeout(6000) + pw = page.wait_for_selector("input[name=Passwd], input[type=password]:not([name=hiddenPassword])", state="visible", timeout=30000) + pw.click() + pw.type(rec["password"], delay=35) + page.wait_for_timeout(500) + pw.press("Enter") + page.wait_for_timeout(8000) + out["stage"] = "g_logged" + # ШАГ 2: coarena OAuth по готовой сессии + page.goto("https://coarena.ai/account/api/keys", wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(3000) + if page.locator("text=Continue with Google").count(): + page.locator("text=Continue with Google").first.click() + page.wait_for_timeout(7000) + if len(ctx.pages) > 1: + page = ctx.pages[-1] + for sel in ("div[data-identifier]", "li:has-text('@')", "div[role=link]:has-text('@')"): + try: + loc = page.locator(sel).first + if loc.count() and loc.is_visible(): + loc.click() + page.wait_for_timeout(6000) + break + except Exception: + pass + for sel in ("button:has-text('Continue')", "button:has-text('Продолжить')", "button:has-text('Allow')"): + try: + loc = page.locator(sel).first + if loc.count() and loc.is_visible(): + loc.click() + page.wait_for_timeout(5000) + break + except Exception: + pass + page.wait_for_timeout(4000) + if "coarena.ai" not in page.url: + page.goto("https://coarena.ai/account/api/keys", wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(2500) + out["stage"] = "at_keys" + body = page.evaluate("() => document.body.innerText.slice(0,120)") + if "Sign in" in body and "Continue with Google" in body: + out["stage"] = "not_logged" + else: + # МУЛЬТИКЛЮЧ: до 10 ключей за прогон (coarena лимит 10/аккаунт) + keys = [] + last_err = "" + for _ki in range(10): + res = page.evaluate("""async () => { + const r = await fetch('/api/me/keys', {method:'POST', headers:{'Content-Type':'application/json'}, + body: JSON.stringify({name:'ii-' + Math.random().toString(36).slice(2,8), acceptModelApiTerms:'2026-11-04'})}); + return {s: r.status, t: await r.text()}; + }""") + if res["s"] == 201: + try: + tok = json.loads(res["t"]).get("token") + except Exception: + tok = None + if tok and "\\u2026" not in tok and "..." not in tok: + keys.append(tok) + page.wait_for_timeout(600) + else: + last_err = "masked" + break + else: + last_err = "s=%s %s" % (res["s"], res["t"][:70]) + break + out["keys"] = keys + if keys: + out["key"], out["ok"], out["stage"] = keys[0], True, "key" + out["stage"] = "keyx%d" % len(keys) + elif last_err: + out["stage"] = "key_fail:%s" % last_err + try: + with open(BASE + "/key_fail_body.txt", "a", encoding="utf8") as fh: + fh.write("%s [%s] %s" % (rec["email"], res["s"], res["t"][:1500]) + NL2) + except Exception: + pass + except Exception as e: + out["stage"] = "err:" + str(e)[:100] + finally: + kill_chrome(prof) + with open(BANK if out["ok"] else FAIL, "a", encoding="utf8") as fh: + for _k in (out.get("keys") or [None]): + rec_out = dict(out) + rec_out["key"] = _k + fh.write(json.dumps(rec_out, ensure_ascii=False) + "\n") + log("%s %s key=%s px=%s" % (out["email"], out["stage"], bool(out["key"]), (px or "direct")[:26])) + + +if __name__ == "__main__": + main() diff --git a/coa_pool_sync.py b/coa_pool_sync.py new file mode 100644 index 0000000..221628a --- /dev/null +++ b/coa_pool_sync.py @@ -0,0 +1,179 @@ +"""Sync coarena keys from keys_bank.jsonl into the rotator pool, verify, report. + +Usage: + python coa_pool_sync.py # sync + verify whole pool + python coa_pool_sync.py --restart # also restart the rotator (single instance) + python coa_pool_sync.py --home D:/coa # override working dir + +Why a script and not hand-editing: coa_keys.txt is read ONCE at rotator start, so +new keys need a restart, and hand-appending breaks the `name|coa_…` line format or +the `coarena-%03d` numbering — load_keys() then silently drops the key. + +Exit codes: 0 = ok, 1 = nothing alive / pool file missing. +""" +import json +import os +import re +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor + +import requests + +HOME = os.environ.get("COA_HOME", "C:/Users/User/tmp/coarena") +BANK = os.path.join(HOME, "keys_bank.jsonl") +KEYSF = os.path.join(HOME, "coa_keys.txt") +ALIVEF = os.path.join(HOME, "coa_keys_alive.txt") +LIMITS = "https://coarena.ai/api/v1/limits" +ROT = os.path.join(HOME, "coa_rot3.py") +ROT_PORT = int(os.environ.get("COA_ROT_PORT", "16446")) +PY = os.environ.get("COA_PY", r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe") +KEY_RE = re.compile(r"^coa_[A-Za-z0-9]{20,}$") + + +def read_bank(path): + """Tolerant read: a live wave appends to this file and the tail line is often torn.""" + out = [] + if not os.path.exists(path): + return out + for line in open(path, encoding="utf8", errors="replace"): + line = line.strip() + if not line: + continue + try: + d = json.loads(line) + except Exception: + continue + k = (d.get("key") or "").strip() + if KEY_RE.match(k): + out.append(k) + return out + + +def read_pool(path): + lines, keys = [], set() + if os.path.exists(path): + for line in open(path, encoding="utf8", errors="replace"): + line = line.rstrip("\n") + if "|" not in line: + continue + k = line.split("|", 1)[1].strip() + if not KEY_RE.match(k): + continue + lines.append(line) + keys.add(k) + return lines, keys + + +def verify(keys): + def one(k): + for _ in range(2): + try: + r = requests.get(LIMITS, headers={"Authorization": "Bearer " + k}, timeout=25) + if r.status_code == 200: + return k, 200 + if r.status_code == 401: + return k, 401 + except Exception: + pass + time.sleep(2) + return k, 0 + + alive = [] + with ThreadPoolExecutor(8) as ex: + for k, st in ex.map(one, keys): + if st == 200: + alive.append(k) + return alive + + +def rotator_pids(): + """Marker is assembled at runtime so this script never matches its own cmdline.""" + marker = "coa_" + "rot3" + pids = [] + try: + import psutil + except ImportError: + return pids + for p in psutil.process_iter(["pid", "cmdline"]): + cmd = " ".join(p.info.get("cmdline") or []) + if marker in cmd and p.info["pid"] != os.getpid(): + pids.append(p.info["pid"]) + return pids + + +def listener_pid(): + try: + import psutil + except ImportError: + return None + for c in psutil.net_connections("tcp"): + if c.laddr and c.laddr.port == ROT_PORT and c.status == "LISTEN": + return c.pid + return None + + +def restart_rotator(): + for pid in rotator_pids(): + try: + import psutil + psutil.Process(pid).kill() + print("killed rotator", pid, flush=True) + except Exception: + pass + time.sleep(2) + env = dict(os.environ) + env.pop("PYTHONPATH", None) + env["PYTHONIOENCODING"] = "utf-8" + env["COA_ROT_PORT"] = str(ROT_PORT) + logf = open(os.path.join(HOME, "rot3.log"), "a") + DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP + p = subprocess.Popen([PY, "-u", "coa_rot3.py"], cwd=HOME, env=env, + creationflags=DETACHED, stdout=logf, stderr=subprocess.STDOUT, + close_fds=False) + print("started rotator", p.pid, flush=True) + for _ in range(20): + time.sleep(2) + if listener_pid() == p.pid: + print("listening on", ROT_PORT, flush=True) + return True + print("WARN: port", ROT_PORT, "not bound by", p.pid, "(listener:", listener_pid(), ")", flush=True) + return False + + +def main(): + home = None + if "--home" in sys.argv: + home = sys.argv[sys.argv.index("--home") + 1] + base = home or HOME + bank = os.path.join(base, "keys_bank.jsonl") + keysf = os.path.join(base, "coa_keys.txt") + + bank_keys = list(dict.fromkeys(read_bank(bank))) + lines, have = read_pool(keysf) + new = [k for k in bank_keys if k not in have] + with open(keysf, "a", encoding="utf8") as f: + n = len(lines) + for k in new: + n += 1 + f.write("coarena-%03d|%s\n" % (n, k)) + print("bank=%d pool_before=%d added=%d pool_after=%d" + % (len(bank_keys), len(have), len(new), len(have) + len(new)), flush=True) + + all_keys = list(dict.fromkeys(read_pool(keysf)[1])) + if not all_keys: + print("FAIL: pool empty", flush=True) + return 1 + alive = verify(all_keys) + with open(os.path.join(base, "coa_keys_alive.txt"), "w", encoding="utf8") as f: + f.write("\n".join(alive)) + print("alive=%d/%d" % (len(alive), len(all_keys)), flush=True) + + if "--restart" in sys.argv: + restart_rotator() + return 0 if alive else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/coa_rot_watch.py b/coa_rot_watch.py new file mode 100644 index 0000000..028a2d4 --- /dev/null +++ b/coa_rot_watch.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Сторож ротатора coarena (порт 16446). + +Ставить в ~/AppData/Local/hermes/scripts/ и гонять кроном no_agent каждую МИНУТУ: + cronjob_manage action=create name=coa-rotator-watch schedule=1m no_agent=true \ + script=coa_rot_watch.py deliver=local + +Молчит, когда порт открыт (no_agent → пустой stdout = ничего не отправлено). +Печатает строку только при реальном старте или провале старта. +""" +import os +import socket +import subprocess +import time + +BASE = "C:/Users/User/tmp/coarena" +PYEXE = r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe" +PORT = 16446 + + +def port_open(port, host="127.0.0.1", timeout=3): + s = socket.socket() + s.settimeout(timeout) + try: + s.connect((host, port)) + return True + except Exception: + return False + finally: + s.close() + + +def main(): + if port_open(PORT): + return # здоров — тишина + + # добить зависшие/зомби-экземпляры, иначе они делят пул и порт + try: + import psutil + for p in psutil.process_iter(["name", "cmdline"]): + c = " ".join(p.info.get("cmdline") or []) + if (p.info.get("name") or "").lower() == "python.exe" and "coa_rot3" in c: + try: + p.kill() + except Exception: + pass + time.sleep(1) + except Exception: + pass + + env = dict(os.environ) + env.pop("PYTHONPATH", None) # PYTHONPATH hermes venv ломает импорты + env["PYTHONIOENCODING"] = "utf-8" + log = open(BASE + "/rot3.log", "ab") + pr = subprocess.Popen( + [PYEXE, "-u", "coa_rot3.py"], cwd=BASE, env=env, + stdout=log, stderr=log, + creationflags=0x00000008 | 0x00000200, # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP + close_fds=True, + ) + for _ in range(20): + time.sleep(1) + if port_open(PORT): + print("rotator started pid=%s port=%s" % (pr.pid, PORT)) + return + # старт не удался — это сигнал, а не тишина: крон доставит строку + print("rotator FAILED to start pid=%s — смотреть %s/rot3.log" % (pr.pid, BASE)) + + +if __name__ == "__main__": + main() diff --git a/coa_shim.py b/coa_shim.py new file mode 100644 index 0000000..d3c1127 --- /dev/null +++ b/coa_shim.py @@ -0,0 +1,227 @@ +"""Coarena rotator for prod (2.27.98.196): OpenAI-compatible front, rotates keys, cools daily caps.""" +import http.server, json, os, socketserver, threading, time, urllib.error, urllib.request + +UP = "https://coarena.ai/api/v1" +KEYSF = os.environ.get("COA_KEYS", "/opt/coa-shim/coa_keys.txt") +PORT = int(os.environ.get("COA_PORT", "48960")) +LOCK = threading.Lock() +STATE = {} + +MODELS_OFF = {"gpt-6-1-sol", "gpt-6-1-terra", "gpt-6-astra", "gpt-6-luna", + "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-astra", "gpt-6-luna", + "gemini-4-argon", "gemini-4-carbon", "mimo-v2.6-pro", "mimo-v2-6-pro", + "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", + "claude-fable-5", "claude-fable-5-1", "claude-fable-5-2"} +ALIAS = {"glm-5.3": "glm-5-3-flash", "kimi-k3": "kimi-k3-1-pro", "mimo-v2.6-pro": "mimo-v2-6-pro", + "kimi-k3.1-pro": "kimi-k3-1-pro", "minimax-m3.1-flash": "minimax-m3-1-flash"} +LAST_GOOD = {} +FAIL_UNTIL = {} +LG_FILE = os.environ.get("COA_LG", "/opt/coa-shim/last_good.json") + + +def load_lg(): + global LAST_GOOD + try: + LAST_GOOD = json.load(open(LG_FILE)) + except Exception: + LAST_GOOD = {} + + +def save_lg(): + try: + json.dump(LAST_GOOD, open(LG_FILE, "w")) + except Exception: + pass + + +def load_keys(): + ks = [] + for line in open(KEYSF, encoding="utf8"): + line = line.strip() + if "|" in line: + name, k = line.split("|", 1) + if k.startswith("coa_"): + ks.append((name, k)) + return ks + + +KEYS = load_keys() +IDX = {"i": 0} +print("keys", len(KEYS), flush=True) + + +def pick_key(): + now = time.time() + with LOCK: + n = len(KEYS) + for off in range(n): + i = (IDX["i"] + off) % n + name, k = KEYS[i] + if STATE.get(k, {}).get("cool", 0) < now: + IDX["i"] = (i + 1) % n + return name, k + return min(KEYS, key=lambda p: STATE.get(p[1], {}).get("cool", 0)) + + +def cool(k, seconds=3600): + with LOCK: + STATE.setdefault(k, {})["cool"] = time.time() + seconds + + +class H(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def send_json(self, code, body): + if isinstance(body, str): + body = body.encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + try: + self.wfile.write(body) + except Exception: + pass + + def do_OPTIONS(self): + self.send_json(204, b"") + + def _pick(self, model): + now = time.time() + lg = LAST_GOOD.get(model) + if lg: + with LOCK: + for name, k in KEYS: + if k == lg and STATE.get(k, {}).get("cool", 0) < now: + return name, k + return pick_key() + + def _proxy(self, method): + ln = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(ln) if ln else None + model = "" + if body and method == "POST": + try: + model = json.loads(body).get("model") or "" + except Exception: + model = "" + if model in MODELS_OFF: + self.send_json(400, json.dumps({"error": { + "message": "%s is turned off on the Coarena Model API right now." % model, + "type": "invalid_request_error", "param": "model", "code": "model_off"}})) + return + path = self.path[3:] if self.path.startswith("/v1") else self.path + stream = False + if body: + try: + stream = bool(json.loads(body).get("stream")) + except Exception: + pass + up_model = ALIAS.get(model, model).replace(".", "-") if model else "" + if model and FAIL_UNTIL.get(model, 0) > time.time(): + self.send_json(429, json.dumps({"error": { + "message": "%s: coarena quota exhausted for now, retry later" % model, + "type": "rate_limit_error", "code": "pool_capped"}})) + return + up_body = None + if body and up_model != model: + up_body = json.dumps({**json.loads(body), "model": up_model}).encode() + elif body: + up_body = body + last = (500, b'{"error":{"message":"no keys"}}') + tries = 0 + while tries < 20: + tries += 1 + name, k = self._pick(model) + data_body = up_body if up_body is not None else body + req = urllib.request.Request(UP + path, data=data_body, method=method, + headers={"Authorization": "Bearer " + k, + "Content-Type": "application/json", + "User-Agent": "Mozilla/5.0"}) + try: + r = urllib.request.urlopen(req, timeout=120) + if model: + with LOCK: + LAST_GOOD[model] = k + save_lg() + if stream: + self.send_response(r.status) + self.send_header("Content-Type", r.headers.get("Content-Type", "text/event-stream")) + self.send_header("Cache-Control", "no-cache") + self.end_headers() + while True: + chunk = r.read1(4096) if hasattr(r, "read1") else r.read(4096) + if not chunk: + break + self.wfile.write(chunk) + self.wfile.flush() + return + d = r.read() + self.send_json(r.status, d) + return + except urllib.error.HTTPError as e: + code = e.code + data = e.read() + if code == 429: + import calendar + txt = data[:200].decode("utf-8", "replace").lower() + now_t = time.time() + gm = time.gmtime(now_t) + if "daily free limit" in txt or "quota" in txt: + midnight = calendar.timegm((gm.tm_year, gm.tm_mon, gm.tm_mday + 1, 0, 0, 0)) + cool(k, max(60, midnight - now_t + 60)) + else: + cool(k, 120) + last = (code, data) + continue + if code in (401, 403): + cool(k, 21600) + last = (code, data) + continue + if code == 400 and (b"usage limits" in data or b"regain access" in data): + import re + m2 = re.search(rb"regain access on (\d{4}-\d{2}-\d{2})", data) + if m2: + import calendar + y, mo, d = map(int, m2.group(1).decode().split("-")) + cool(k, max(3600, calendar.timegm((y, mo, d, 0, 0, 0)) - time.time() + 60)) + else: + cool(k, 86400) + last = (429, data) + continue + if code == 400 and b"does not exist" in data[:200]: + cool(k, 600) + last = (code, data) + continue + self.send_json(code, data) + return + except Exception as e: + last = (502, json.dumps({"error": {"message": type(e).__name__}}).encode()) + if model: + FAIL_UNTIL[model] = time.time() + 180 + self.send_json(last[0], last[1]) + + def do_GET(self): + if self.path.rstrip("/") in ("/health", "/healthz"): + now = time.time() + alive = sum(1 for _, k in KEYS if STATE.get(k, {}).get("cool", 0) < now) + self.send_json(200, json.dumps({"ok": True, "keys": len(KEYS), "alive": alive})) + return + self._proxy("GET") + + def do_POST(self): + self._proxy("POST") + + +class T(socketserver.ThreadingMixIn, http.server.HTTPServer): + daemon_threads = True + allow_reuse_address = True + + +if __name__ == "__main__": + load_lg() + print("listen", PORT, "last_good", len(LAST_GOOD), flush=True) + T(("127.0.0.1", PORT), H).serve_forever() \ No newline at end of file diff --git a/coa_sync.py b/coa_sync.py new file mode 100644 index 0000000..713376a --- /dev/null +++ b/coa_sync.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Keep a budgeted key pool honest in iishko/new-api. + +Probes GET /api/v1/limits per channel key (spends no budget), parks channels whose +remaining daily USD is exhausted and revives them after the 00:00 UTC reset. +Dry run by default; writes nothing to the gateway without --apply. + +Usage (on the prod host): + python3 coa_sync.py # dry run: prints park/revive/keep counts + python3 coa_sync.py --apply # writes channels/abilities + purges guard_hold +Cron: + */15 * * * * root cd /root && /usr/bin/python3 coa_sync.py --apply >> /var/log/coa_sync.log 2>&1 +""" +import json +import subprocess +import sys +import time +import urllib.request +from concurrent.futures import ThreadPoolExecutor + +LIMITS = "https://coarena.ai/api/v1/limits" +LOG = "/var/log/coa_sync.log" +NAME_LIKE = "coarena-%" +FLOOR = 0.05 +APPLY = "--apply" in sys.argv + + +def sh(sql_text): + """Run SQL as postgres via a uniquely named file (a foreign /tmp/*.sql may execute instead).""" + path = "/tmp/coa_sync_q_%d.sql" % time.time_ns() + with open(path, "w") as fh: + fh.write(sql_text) + subprocess.run(["chmod", "644", path], capture_output=True) + p = subprocess.run(["su", "postgres", "-c", "psql -d newapi -At -F '|' -f " + path], + capture_output=True, text=True, timeout=180) + return p.stdout.strip(), p.stderr.strip() + + +out, err = sh("select id, name, key, status from channels where name like '%s' order by id;" % NAME_LIKE) +rows = [] +for line in out.splitlines(): + parts = line.split("|") + if len(parts) >= 4: + rows.append({"id": int(parts[0]), "name": parts[1], "key": parts[2], "status": int(parts[3])}) +print("channels", len(rows), flush=True) +if err: + print("psql warn", err[:160], flush=True) + + +def limits(row): + req = urllib.request.Request(LIMITS, headers={"Authorization": "Bearer " + row["key"], + "User-Agent": "Mozilla/5.0"}) + try: + with urllib.request.urlopen(req, timeout=25) as x: + d = json.loads(x.read())["data"] + used = (d.get("today") or {}).get("used_usd") or 0 + cap = d.get("usd_per_day") or 0 + return row, round(cap - used, 3) + except Exception as e: + return row, "err:" + type(e).__name__ + + +res = [] +with ThreadPoolExecutor(max_workers=8) as ex: + for row, left in ex.map(limits, rows): + res.append((row, left)) + +park, revive, keep, unknown = [], [], 0, 0 +for row, left in res: + if isinstance(left, str): + unknown += 1 + continue + if left <= FLOOR: + if row["status"] == 1: + park.append(row) + elif row["status"] != 1: + revive.append(row) + else: + keep += 1 + +print("park", len(park), "revive", len(revive), "keep", keep, "unknown", unknown, flush=True) + +stmts = [] +for row in park: + stmts.append("update channels set status=2 where id=%d;" % row["id"]) + stmts.append("update abilities set enabled=false where channel_id=%d;" % row["id"]) +for row in revive: + stmts.append("update channels set status=1 where id=%d;" % row["id"]) + stmts.append("update abilities set enabled=true where channel_id=%d;" % row["id"]) +stmts.append("delete from guard_hold where channel_id in (select id from channels where name like '%s');" % NAME_LIKE) + +if APPLY and stmts: + o, e = sh("\n".join(stmts) + "\n") + print("applied", len(stmts), "stmts", (o or "")[-90:], (e or "")[:90], flush=True) + # new-api caches abilities ~60s; restart only when the live set actually changed. + if park or revive: + subprocess.run(["systemctl", "restart", "new-api.service"], capture_output=True) + +line = "%s park=%d revive=%d keep=%d unknown=%d apply=%s" % ( + time.strftime("%Y-%m-%d %H:%M:%S"), len(park), len(revive), keep, unknown, APPLY) +try: + with open(LOG, "a") as fh: + fh.write(line + "\n") +except Exception: + pass +print(line) diff --git a/coa_sync_cron.py b/coa_sync_cron.py new file mode 100644 index 0000000..ab4a63a --- /dev/null +++ b/coa_sync_cron.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Сбор coarena-ключей и заливка на прод-шим (coa-shim). Молчит, если новых нет.""" +import json +import os +import subprocess + +BASE = r"C:/Users/User/tmp/coarena" +OUT = os.path.join(BASE, "coa_keys_sync.txt") +SSH = ["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=25", + "-i", r"C:/Users/User/.ssh/id_ed25519", "root@2.27.98.196"] + +keys = [] +seen = set() +for f in ("keys_bank2.jsonl", "keys_bank.jsonl"): + p = os.path.join(BASE, f) + if not os.path.exists(p): + continue + for line in open(p, encoding="utf8"): + line = line.strip() + if not line: + continue + try: + r = json.loads(line) + except Exception: + continue + if not isinstance(r, dict): + continue + k = r.get("key") + if not k or not str(k).startswith("coa_") or k in seen: + continue + seen.add(k) + keys.append("%s|%s" % ((r.get("email") or "coa")[:30], k)) + +if len(keys) == int(open(os.path.join(BASE, ".last_sync_count")).read()) if os.path.exists(os.path.join(BASE, ".last_sync_count")) else -1: + print("no new keys") + raise SystemExit + +open(OUT, "w", encoding="utf8").write("\n".join(keys) + "\n") +scp = subprocess.run(["scp", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=25", + "-i", r"C:/Users/User/.ssh/id_ed25519", OUT, "root@2.27.98.196:/opt/coa-shim/coa_keys.txt"], + capture_output=True, text=True, timeout=120) +if scp.returncode: + print("scp fail", (scp.stderr or "")[-100:]) + raise SystemExit(1) +r = subprocess.run(SSH + ["systemctl restart coa-shim && sleep 3 && curl -s -m 5 http://127.0.0.1:48960/health"], + capture_output=True, text=True, timeout=90) +open(os.path.join(BASE, ".last_sync_count"), "w").write(str(len(keys))) +print("synced", len(keys), (r.stdout or "").strip()[:120]) \ No newline at end of file diff --git a/coa_wave.py b/coa_wave.py new file mode 100644 index 0000000..38646d8 --- /dev/null +++ b/coa_wave.py @@ -0,0 +1,43 @@ +# Wave over gmail_bank.jsonl: python coa_wave.py +# Resume is by idx from keys_bank.jsonl / keys_fail.jsonl; >3 workers = Chrome fights itself. +import json +import os +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor + +BASE = os.environ.get("COA_HOME", "C:/Users/User/tmp/coarena") +PY = os.environ.get("COA_PY", r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe") +env = dict(os.environ) +env.pop("PYTHONPATH", None) +env["PYTHONIOENCODING"] = "utf-8" + + +def run_one(idx): + try: + r = subprocess.run([PY, BASE + "/coa_one.py", str(idx)], cwd=BASE, env=env, + timeout=420, capture_output=True, text=True) + return idx, r.returncode, (r.stderr or "")[-160:] + except Exception as e: + return idx, -1, str(e)[:160] + + +def main(): + total = int(sys.argv[1]) if len(sys.argv) > 1 else 50 + workers = int(sys.argv[2]) if len(sys.argv) > 2 else 3 + done = set() + for f in ("keys_bank.jsonl", "keys_fail.jsonl"): + p = os.path.join(BASE, f) + if os.path.exists(p): + for line in open(p, encoding="utf8"): + try: + done.add(json.loads(line)["idx"]) + except Exception: + pass + with ThreadPoolExecutor(workers) as ex: + for idx, rc, err in ex.map(run_one, [i for i in range(total) if i not in done]): + print("idx=%d rc=%d %s" % (idx, rc, err.strip()[:80]), flush=True) + + +if __name__ == "__main__": + main() diff --git a/gh_oauth_check.py b/gh_oauth_check.py new file mode 100644 index 0000000..7625c52 --- /dev/null +++ b/gh_oauth_check.py @@ -0,0 +1,82 @@ +"""Отбраковать GitHub-пул по пригодности для OAuth третьей стороны. + +Зачем: `POST github.com/session` даёт 302 у всех живых аккаунтов, включая +негодные. Единственный честный критерий — дойти до consent-страницы целевого +приложения. Флагнутый аккаунт логинится, открывает /dashboard и отвечает +«This account is flagged, and therefore cannot authorize a third party +application» — такой OAuth не отдаст никогда. + +Использование: + python gh_oauth_check.py [limit] [out.json] + +Формат пула: любой список словарей с полями login/password (totp не нужен — +2FA-аккаунты помечаются `2fa-needed` и остаются в out для отдельного прогона +браузером). + +Категории в выводе: + clean — доходит до формы authorize, годится + FLAGGED — флаг, выбросить + suspended — логин уводит на /suspended + 2fa-needed — нужен TOTP, HTTP-проверка не решает + other/ERR — всё прочее (чужой пароль, капча, сеть) +""" +import json +import re +import sys + +import requests + +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36") + + +def check(sess, login, password, client_id): + sess.cookies.clear() + r = sess.get("https://github.com/login", timeout=25) + m = re.search(r'name="authenticity_token" value="([^"]+)"', r.text) + if not m: + return "no-token", "" + rr = sess.post("https://github.com/session", timeout=30, allow_redirects=True, data={ + "login": login, "password": password, + "authenticity_token": m.group(1), "commit": "Sign in"}) + if "two-factor" in rr.url: + return "2fa-needed", rr.url + if "suspended" in rr.url: + return "suspended", rr.url + au = sess.get( + "https://github.com/login/oauth/authorize?client_id=%s&state=probe&scope=user:email" % client_id, + timeout=30, allow_redirects=True) + body = au.text + if "flagged" in body: + return "FLAGGED", au.url + if "authorize" in au.url or "Authorize" in body: + return "clean", au.url + return "other", au.url + + +def main(): + pool_path, client_id = sys.argv[1], sys.argv[2] + limit = int(sys.argv[3]) if len(sys.argv) > 3 else 25 + out_path = sys.argv[4] if len(sys.argv) > 4 else "gh_oauth_candidates.json" + pool = json.load(open(pool_path, encoding="utf-8")) + sess = requests.Session() + sess.headers.update({"User-Agent": UA}) + out = [] + for acc in pool[:limit]: + login = acc.get("login") + try: + status, url = check(sess, login, acc.get("password", ""), client_id) + except Exception as e: + status, url = "ERR", repr(e)[:70] + print("%-32s %-11s %s" % (login, status, url[:60]), flush=True) + if status in ("clean", "2fa-needed", "other"): + item = dict(acc) + item["status"] = status + out.append(item) + json.dump(out, open(out_path, "w", encoding="utf-8"), ensure_ascii=False, indent=1) + clean = sum(1 for a in out if a.get("status") == "clean") + print("saved %s: clean %d of %d checked" % (out_path, clean, min(limit, len(pool)))) + + +if __name__ == "__main__": + main() diff --git a/mixr_claim.py b/mixr_claim.py new file mode 100644 index 0000000..ce06728 --- /dev/null +++ b/mixr_claim.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Claim mixroute (new-api fork) $5 welcome credit by solving its slide-puzzle captcha. + +Usage: + python mixr_claim.py + +cookie_file: one line `session=...; _ga=...` harvested from a logged-in Chrome profile +(ctx.cookies() joined as name=value). Only the `session` cookie actually matters. + +Idempotent: if the credit is already claimed it prints status and exits 0. +""" +import base64 +import io as _io +import json +import sys +from collections import deque + +import numpy as np +import requests +from PIL import Image + +BASE = "https://console.mixroute.ai" +QUOTA_PER_USD = 500000 # read it from /api/status: data.quota_per_unit + + +def session_from(uid: str, cookie_file: str) -> requests.Session: + s = requests.Session() + s.headers.update( + { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36", + "New-Api-User": str(uid), # without it every /api/user/self* is 401 + "Accept": "application/json", + "Origin": BASE, + "Referer": BASE + "/dashboard", + } + ) + raw = open(cookie_file, encoding="utf-8").read().strip() + for kv in raw.split("; "): + if "=" in kv: + k, v = kv.split("=", 1) + s.cookies.set(k, v, domain="console.mixroute.ai") + return s + + +def solve_slide(bg_bytes: bytes, piece_bytes: bytes): + """Return slide offset in CHALLENGE-image pixels, or None. + + slide units are image px, not CSS px: the frontend sends + Math.round(translateX / (clientWidth / challenge.width)). + """ + gray = np.array(Image.open(_io.BytesIO(bg_bytes)).convert("RGB")).astype(float).mean(axis=2) + pa = np.array(Image.open(_io.BytesIO(piece_bytes)).convert("RGBA")) + opaque = pa[:, :, 3] > 60 + ys, xs = np.nonzero(opaque) + piece_x0, piece_y0 = int(xs.min()), int(ys.min()) + ph, pw = int(ys.max() - ys.min() + 1), int(xs.max() - xs.min() + 1) + h, w = gray.shape + + for thr in (100, 80, 120, 60): + mask = gray > thr + seen = np.zeros_like(mask, bool) + for y in range(h): + for x in range(w): + if not mask[y, x] or seen[y, x]: + continue + q, pts = deque([(y, x)]), [] + seen[y, x] = True + while q: + cy, cx = q.popleft() + pts.append((cy, cx)) + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + ny, nx = cy + dy, cx + dx + if 0 <= ny < h and 0 <= nx < w and mask[ny, nx] and not seen[ny, nx]: + seen[ny, nx] = True + q.append((ny, nx)) + if len(pts) < 60: + continue + yy = [p[0] for p in pts] + xx = [p[1] for p in pts] + x0, x1, y0, y1 = min(xx), max(xx), min(yy), max(yy) + # the hole outline is the component whose bbox equals the piece bbox + if abs((x1 - x0 + 1) - pw) <= 3 and abs((y1 - y0 + 1) - ph) <= 3 and y0 >= ph * 0.5 - 20: + return {"slide": x0 - piece_x0, "hole_x0": x0, "thr": thr, + "piece_off": piece_x0, "size": [pw, ph]} + return None + + +def main() -> int: + uid, cookie_file = sys.argv[1], sys.argv[2] + s = session_from(uid, cookie_file) + + st = s.get(BASE + "/api/user/self/welcome-credit", timeout=30).json().get("data") or {} + print("welcome:", json.dumps({k: st.get(k) for k in ("claimed", "eligible", "quota", "reviewing", "risk")})) + if st.get("claimed"): + print("already claimed") + return 0 + + for attempt in range(1, 5): + d = s.get(BASE + "/api/user/self/welcome-credit/challenge", timeout=30).json().get("data") or {} + cid = d.get("challenge_id") + if not cid: + print("no challenge") + return 1 + solved = solve_slide(base64.b64decode(d["background"].split(",", 1)[1]), + base64.b64decode(d["piece"].split(",", 1)[1])) + print("attempt", attempt, "solved", solved) + if not solved: + return 1 + r = s.post(BASE + "/api/user/self/welcome-credit/claim", + json={"challenge_id": cid, "slide": int(solved["slide"])}, timeout=90) + print("claim", r.status_code, r.text[:300]) + if r.status_code == 200 and r.json().get("success"): + break + + me = s.get(BASE + "/api/user/self", timeout=30).json().get("data") or {} + quota = me.get("quota", 0) + print("quota", quota, "= $%.4f" % (quota / QUOTA_PER_USD)) + return 0 if quota > 0 else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/proxy_multi.py b/proxy_multi.py new file mode 100644 index 0000000..6f11fde --- /dev/null +++ b/proxy_multi.py @@ -0,0 +1,176 @@ +"""Authenticated HTTP CONNECT proxy that pins each connection to a chosen source IP. + +One port exposes N egress IPs: `user-N` in the proxy login always dials the N-th +address from --ips (sticky), a login without the suffix round-robins. All listed +addresses must already be configured on the interface (`ip -4 addr show`). + + python3 proxy_multi.py --port 8888 --user mr --pass secret \ + --ips 203.0.113.10,203.0.113.11,198.51.100.7 + + curl -x http://mr-1:secret@host:8888 https://api.ipify.org # always .11 + +Run detached so an ssh session cannot take it down: + setsid nohup python3 proxy_multi.py ... > /root/proxy_multi.log 2>&1 < /dev/null & +Stop by explicit PID (pkill -f trips interpreter-name guards): + PID=$(ss -lntp | sed -n 's/.*pid=\\([0-9]*\\).*/\\1/p' | head -1); kill $PID + +Playwright needs credentials as fields, not in the URL: + proxy={"server": "http://host:8888", "username": "mr-1", "password": "secret"} +`requests` accepts them inside the proxy URL. +""" +import argparse +import asyncio +import base64 +import itertools +import sys + +IPS = [] +CYCLE = None +USER = "" +PASS = "" +FAILS = {} + + +async def pipe(reader, writer): + try: + while True: + data = await reader.read(65536) + if not data: + break + writer.write(data) + await writer.drain() + except Exception: + pass + finally: + try: + writer.close() + except Exception: + pass + + +async def handle(reader, writer): + try: + head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=20) + except Exception: + writer.close() + return + lines = head.decode("latin-1").split("\r\n") + parts = lines[0].split() + if len(parts) < 3: + writer.write(b"HTTP/1.1 400 Bad Request\r\n\r\n") + writer.close() + return + method, target = parts[0], parts[1] + hdrs = {} + for ln in lines[1:]: + if ":" in ln: + k, v = ln.split(":", 1) + hdrs[k.strip().lower()] = v.strip() + + if method != "CONNECT": + from urllib.parse import urlsplit + try: + u = urlsplit(target) + host, port = u.hostname, u.port or 80 + path = (u.path or "/") + (("?" + u.query) if u.query else "") + except Exception: + writer.write(b"HTTP/1.1 400 Bad Request\r\n\r\n") + writer.close() + return + fwd = {k: v for k, v in hdrs.items() if k != "proxy-connection"} + fwd["host"] = host + req = "GET %s HTTP/1.1\r\n" % path + "".join("%s: %s\r\n" % (k, v) for k, v in fwd.items()) + "\r\n" + try: + r, w = await asyncio.wait_for( + asyncio.open_connection(host, port, local_addr=(next(CYCLE), 0)), timeout=25) + except Exception: + writer.write(b"HTTP/1.1 502 Bad Gateway\r\n\r\n") + writer.close() + return + w.write(req.encode("latin-1")) + await w.drain() + while True: + chunk = await r.read(65536) + if not chunk: + break + writer.write(chunk) + await writer.drain() + w.close() + writer.close() + return + + sticky = None + if USER: + got = hdrs.get("proxy-authorization", "") + user_part = "" + if got.startswith("Basic "): + try: + user_part = base64.b64decode(got[6:]).decode("latin-1").split(":", 1)[0] + except Exception: + user_part = "" + base_user = user_part.split("-", 1)[0] + if "-" in user_part: + try: + sticky = int(user_part.rsplit("-", 1)[1]) + except Exception: + sticky = None + want = "Basic " + base64.b64encode(("%s:%s" % (USER, PASS)).encode()).decode() + if got != want and base_user != USER: + writer.write(b"HTTP/1.1 407 Proxy Authentication Required\r\n" + b"Proxy-Authenticate: Basic realm=\"proxy\"\r\n\r\n") + await writer.drain() + writer.close() + return + + host, _, port = target.rpartition(":") + port = int(port or 443) + order = list(IPS) + if sticky is not None: + first = IPS[sticky % len(IPS)] + order = [first] + [x for x in IPS if x != first] + remote = None + for i in range(len(order)): + src = order[i] if sticky is not None else next(CYCLE) + if FAILS.get(src, 0) >= 3: + continue + try: + remote = await asyncio.wait_for( + asyncio.open_connection(host, port, local_addr=(src, 0)), timeout=20) + break + except Exception: + FAILS[src] = FAILS.get(src, 0) + 1 + remote = None + if remote is None: + writer.write(b"HTTP/1.1 502 Bad Gateway\r\n\r\n") + await writer.drain() + writer.close() + return + r, w = remote + writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n") + await writer.drain() + await asyncio.gather(pipe(reader, w), pipe(r, writer)) + + +async def main(): + global IPS, CYCLE, USER, PASS + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=8888) + ap.add_argument("--bind", default="0.0.0.0") + ap.add_argument("--user", default="") + ap.add_argument("--pass", dest="password", default="") + ap.add_argument("--ips", required=True, help="comma separated source IPs on this host") + a = ap.parse_args() + IPS = [x.strip() for x in a.ips.split(",") if x.strip()] + CYCLE = itertools.cycle(IPS) + USER, PASS = a.user, a.password + srv = await asyncio.start_server(handle, a.bind, a.port, backlog=512) + print("listening %s:%d ips=%s" % (a.bind, a.port, IPS), flush=True) + async with srv: + await srv.serve_forever() + + +if __name__ == "__main__": + try: + asyncio.run(main()) + except KeyboardInterrupt: + sys.exit(0)