commit 25a9efb8be8abc98a929ef2fadf5796626f2cf72 Author: ENI Date: Wed Nov 4 13:48:42 2026 +0300 unrestricted.sh autoreg: HTTP flow, IMAP magic-link, farm pacing, key shim diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9054a93 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +__pycache__/ +*.pyc +bank.jsonl +done.txt +domains_dead.txt +alive.txt +proxies.txt +*.log +env.sh \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..654ffff --- /dev/null +++ b/README.md @@ -0,0 +1,99 @@ +# unrestricted.sh autoreg + +Регистрация аккаунтов на `unrestricted.sh` без браузера: Turnstile через 2captcha, +magic-link по IMAP, ключ `unr_sk_*` через Next-Action эндпоинт `/keys`. +Плюс ферма с управлением egress-адресами и OpenAI-совместимый шим-ротатор +для new-api. + +Сервис: uncensored-модели (`qwen3.8-27b-uncensored`, 262 144 ctx, $1.00 in / $0.10 cached / $2.00 out). +Триальный бонус приветствия — $0.50 на аккаунт. + +## Состав + +| Файл | Что делает | +|------|------------| +| `ur_reg.py` | один аккаунт: капча → magic-link → verify → wallet → ключ. Печать — JSON-строка | +| `mail_reader.py` | IMAP-ридер magic-link ссылки: одно соединение, все папки, декод quoted-printable | +| `farm.py` | пул аккаунтов × пул egress: паузы по 429/пустым аккаунтам, кап кредитов на адрес | +| `keycheck.py` | живая проверка `unr_sk_*` (`GET /v1/models`), с шагом и браузерным UA | +| `ur_shim.py` | OpenAI-совместимый шим: ротация ключей из банка, деад-лист, `/status` | + +## Установка + +```bash +python -m pip install requests +cp proxies.txt.example proxies.txt # вписать свои egress (http/socks5/direct) +``` + +Переменные окружения (см. `.env.example`): + +```bash +export TWOCAPTCHA_KEY=... # обязателен: один решённый Turnstile на попытку +export UR_MAIL_HOST=root@vps # опционально: где крутить mail_reader.py +export UR_NEXT_ACTION=... # хэш Next-Action, меняется при деплое сервиса +``` + +## Запуск + +```bash +# один аккаунт +python ur_reg.py "user@domain:imap_password" "http://user:pass@host:port" + +# ферма: 8 потоков, 100 аккаунтов из пула +python farm.py pool.txt 8 100 + +# проверка банка ключей +python keycheck.py bank.jsonl 1.0 + +# шим для new-api +UR_PORT=48016 UR_BANK=/opt/ur-shim/bank.jsonl python ur_shim.py +``` + +Канал в new-api: тип OpenAI, base URL `http://127.0.0.1:48016`, ключ канала — любой +(шим сам подставляет ключ из банка), модели — имена из каталога сервиса. + +## Как всё устроено + +1. **Капча.** `POST 2captcha in.php` с `method=turnstile` и sitekey `0x4AAAAAAE0Ejmo0NV9mf20B`. + Токен подставляется в заголовок `x-captcha-response` — именно он, а не `cf-turnstile-response`. + Без токена сервис отвечает `400 {"code":"MISSING_RESPONSE"}`. +2. **Регистрация.** `POST /api/auth/sign-in/magic-link` с телом + `{email, callbackURL, newUserCallbackURL, errorCallbackURL}` и заголовками `x-signup-device`, + `x-signup-context`, `x-signup-automation`. Ответ `200 {"status":true}` = письмо поставлено в очередь. +3. **Письмо.** Читается по IMAP: одно соединение на всё ожидание, скан всех папок + (INBOX/Junk/Spam/Bulk + список сервера), `get_payload(decode=True)` — иначе + quoted-printable рвёт токен и ссылка приходит вида `verify?token=`. +4. **Verify.** `GET` ссылки в той же `requests.Session` — токен одноразовый и живёт минуты. +5. **Баланс.** `GET /api/wallet` → `balanceMicrocents / 1e8` = доллары, `welcomeWithheld` = бонус удержан. +6. **Ключ.** `POST /keys` с заголовком `next-action: <хэш>` и телом `["First key","home"]`, + из ответа вытаскивается `unr_sk_[a-z0-9]+`. + +## Лимиты и экономика (замеры) + +- **Rate limit по IP.** Не «2 за окно», а bucket: ~3 успешных magic-link за пару минут, + дальше `429` на 5–18 минут, `Retry-After` не отдаётся. 429 приходит **после** списания капчи. +- **Пауза адреса.** После любой попытки адрес отдыхает 150 с; после 429 — 900 с с ростом до 3600 с. + Без этого потоки конкурируют за один IP и получают лавину 429. +- **Кап кредитов.** На адрес не больше 2 кредитных аккаунтов за окно ~6 ч: адрес «остывает» + и снова начинает выдавать бонус. +- **Воронка (127 попыток).** 40 доставленных писем (31%) → 10 с кредитом (25%) → **8% на попытку**. + Основные потери — `rate_limited` и `no_mail`. +- **Стоимость.** Один Turnstile ≈ $0.003. То есть кредитный аккаунт стоит ~$0.04, и это $0.50 кредита. +- **Ключи не истекают.** 401 у отдельного ключа = флаг конкретного аккаунта, а не TTL. + +## Где ломается + +- **Письма не доставляются.** Сервис режет отправку по домену: `t-online.de`, `rambler.ru` + перестают получать письма вообще, при этом `200 {"status":true}` продолжает приходить. + Лечится только сменой почвы, а не ретраями. +- **Бонус выключают целиком.** В такие периоды баланс `0.0` у всех новых аккаунтов + (`welcomeWithheld: true`) независимо от домена и egress — регистрация жжёт капчу впустую. + Признак: три пустых аккаунта подряд на разных адресах. +- **Проверка ключей с датацентр-IP бесполезна.** Cloudflare отдаёт `403 error code: 1010`, + бурст — `429`. Считается только с резидентного IP, браузерным UA, с шагом ~1 с. +- **`/status` шима ≠ живость.** Он показывает число ключей с остатком в банке, а не результат пробы. + +## Дисклеймер + +Код для тестирования собственной инфраструктуры и исследования стойкости регистрационных +флоу. Ответственность за использование — на запускающем. \ No newline at end of file diff --git a/env.example b/env.example new file mode 100644 index 0000000..0a7bd36 --- /dev/null +++ b/env.example @@ -0,0 +1,24 @@ +# пример конфигурации: скопировать в env.sh / экспортировать вручную + +# 2captcha — обязателен для регистрации (Turnstile) +TWOCAPTCHA_KEY= + +# Где крутить mail_reader.py (опционально; без этого читаем локально) +# UR_MAIL_HOST=root@your.vps +# UR_MAIL_PATH=/root/mail_reader.py +# UR_SSH_KEY=~/.ssh/id_ed25519 + +# Next-Action хэш эндпоинта /keys (меняется при деплое сервиса) +# UR_NEXT_ACTION= + +# Сколько секунд ждать письмо +UR_MAIL_WAIT=120 + +# Кап кредитных аккаунтов на один egress за окно +UR_CAP_CREDIT=2 + +# Шим +# UR_PORT=48016 +# UR_BANK=/opt/ur-shim/bank.jsonl +# UR_DEAD=/opt/ur-shim/dead.json +# UR_UPSTREAM=https://api.unrestricted.sh \ No newline at end of file diff --git a/farm.py b/farm.py new file mode 100644 index 0000000..a07b5eb --- /dev/null +++ b/farm.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""farm.py [workers] [limit] + +Пул строк "email:imap_password". Для каждого аккаунта запускается ur_reg.py +на отдельном egress. Логика пауз — главное, что экономит капчу: + + credit -> адрес получает +1, после 2 кредитов пауза 6 ч + rate_limited -> штраф адресу 900..3600 с (растёт экспоненциально), аккаунт в очередь + no_credit -> 3 пустых аккаунта на адрес без единого кредита = пауза 1 ч + no_mail -> аккаунт возвращается в очередь через 40 мин + любая попытка -> адрес отдыхает 150 с (иначе следующий запрос сразу ловит 429) + +Адреса берутся из proxies.txt (по одному в строке, допускается 'direct'). +Результаты дописываются в bank.jsonl, обработанные — в done.txt. +""" +import json +import os +import subprocess +import sys +import threading +import time +from collections import deque + +HERE = os.path.dirname(os.path.abspath(__file__)) +PY = sys.executable + +POOL = sys.argv[1] +WORKERS = int(sys.argv[2]) if len(sys.argv) > 2 else 2 +LIMIT = int(sys.argv[3]) if len(sys.argv) > 3 else 100 + +PROXY_FILE = os.environ.get("UR_PROXIES", os.path.join(HERE, "proxies.txt")) +PROXIES = [l.strip() for l in open(PROXY_FILE, encoding="utf-8") if l.strip()] \ + if os.path.exists(PROXY_FILE) else ["direct"] + +CAP_CREDIT = int(os.environ.get("UR_CAP_CREDIT", "2")) +CONF = {"credit_cap": 21600, "rate_limited": 600, "err:ConnectionError": 1800, + "captcha_fail": 120, "no_mail": 2400} + +rows = [l.strip() for l in open(POOL, encoding="utf-8", errors="replace") + if "@" in l and ":" in l] +DONE_P = os.path.join(HERE, "done.txt") +BANK_P = os.path.join(HERE, "bank.jsonl") +DEAD_P = os.path.join(HERE, "domains_dead.txt") + + +def read_set(p): + if not os.path.exists(p): + return set() + return set(l.strip() for l in open(p, encoding="utf-8", errors="replace")) + + +done = read_set(DONE_P) +dead = read_set(DEAD_P) +queue = deque(r for r in rows + if r not in done and r.split("@")[-1].split(":")[0].lower() not in dead) +print("queue", len(queue), flush=True) +if LIMIT: + queue = deque(list(queue)[:LIMIT]) + print("limited to", len(queue), flush=True) + +lock = threading.Lock() +cool = {p: 0.0 for p in PROXIES} +cr, pen, zc = {}, {}, {} +busy = set() + +# предзагрузка счётчика кредитов по адресам, чтобы не превышать кап после рестарта +if os.path.exists(BANK_P): + for line in open(BANK_P, encoding="utf-8", errors="replace"): + if line.startswith("{"): + try: + d = json.loads(line) + except Exception: + continue + if d.get("result") == "credit": + k = (d.get("proxy") or "?").split("@")[-1] + cr[k] = cr.get(k, 0) + 1 + + +def pick_proxy(): + """Эксклюзивно бронирует адрес; при всех в паузе — ждёт, а не рекурсирует.""" + while True: + now = time.time() + best = None + with lock: + for p in PROXIES: + if cool[p] <= now and p not in busy: + busy.add(p) + return p + if best is None or cool[p] < cool[best]: + best = p + wait = max(0.0, cool[best] - now) if best else 5.0 + time.sleep(min(max(wait, 1.0), 30.0)) + + +def worker(wid): + while True: + with lock: + if not queue: + return + cred = queue.popleft() + px = pick_proxy() + try: + r = subprocess.run([PY, os.path.join(HERE, "ur_reg.py"), cred, px], cwd=HERE, + env=dict(os.environ, PYTHONIOENCODING="utf-8"), + capture_output=True, text=True, timeout=1500) + out = "" + for l in (r.stdout or "").splitlines(): + if l.startswith("{"): + out = l + d = json.loads(out) if out else {"result": "crash"} + except Exception as e: + d = {"result": "err:" + type(e).__name__} + d["email"] = d.get("email") or cred.split(":")[0] + d["proxy"] = px + res = d.get("result", "") + with lock: + busy.discard(px) + with open(BANK_P, "a", encoding="utf-8") as f: + f.write(json.dumps(d, ensure_ascii=False) + "\n") + if res in ("credit", "no_credit", "domain_blocked", "verify_error", "magiclink_fail"): + with open(DONE_P, "a", encoding="utf-8") as f: + f.write(cred + "\n") + if res == "domain_blocked": + with open(DEAD_P, "a", encoding="utf-8") as f: + f.write(d.get("domain", "") + "\n") + if res == "credit": + k = px.split("@")[-1] + cr[k] = cr.get(k, 0) + 1 + if cr[k] >= CAP_CREDIT: + cool[px] = time.time() + CONF["credit_cap"] + print(" [cap] %s -> %d кредитов, пауза 6ч" % (k, cr[k]), flush=True) + if res in ("credit", "no_credit", "no_mail", "verify_error"): + cool[px] = time.time() + 150 + if res in ("no_credit", "no_mail"): + k = px.split("@")[-1] + zc[k] = zc.get(k, 0) + 1 + if zc[k] >= 3 and cr.get(k, 0) == 0: + cool[px] = time.time() + 3600 + print(" [zero] %s -> 3 пустых, пауза 1ч" % k, flush=True) + if res == "rate_limited": + k = px.split("@")[-1] + pen[k] = min(max(pen.get(k, 600) * 2, 900), 3600) + cool[px] = time.time() + pen[k] + print(" [429] %s -> пауза %d с" % (k, pen[k]), flush=True) + queue.append(cred) + elif res in CONF: + cool[px] = time.time() + CONF[res] + queue.append(cred) + print("%d %s %s %s" % (wid, d["email"], res, d.get("balance")), flush=True) + + +threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(WORKERS)] +for t in threads: + t.start() +for t in threads: + t.join() +print("farm done", flush=True) \ No newline at end of file diff --git a/keycheck.py b/keycheck.py new file mode 100644 index 0000000..7e77dc7 --- /dev/null +++ b/keycheck.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""keycheck.py [delay] + +Проверка живости unr_sk_ ключей. Важно: probe с датацентр-IP бесполезен — +Cloudflare отдаёт 403 "error code: 1010" на любой запрос, а бурст ловит +429 "Too many requests from this IP address". Поэтому: + * User-Agent браузерный, + * шаг между запросами 1 с (настраивается), + * 429 = ключ, скорее всего, живой — нужно добить после паузы, а не считать мёртвым. + +Выход: сводка + alive.txt со живыми ключами. +""" +import json +import sys +import time + +import requests + +BANK = sys.argv[1] if len(sys.argv) > 1 else "bank.jsonl" +DELAY = float(sys.argv[2]) if len(sys.argv) > 2 else 1.0 +UA = {"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/141.0 Safari/537.36"), + "Accept": "application/json"} +URL = "https://api.unrestricted.sh/v1/models" + +rows = [json.loads(l) for l in open(BANK, encoding="utf-8", errors="replace") if l.strip()] +ok, codes = [], {} +for r in rows: + k = r.get("key") or "" + if not k.startswith("unr_sk_"): + continue + try: + s = requests.get(URL, headers={**UA, "Authorization": "Bearer " + k}, timeout=15) + st = s.status_code + except Exception as e: + st = type(e).__name__ + codes[st] = codes.get(st, 0) + 1 + if st == 200: + ok.append((k, float(r.get("balance") or 0))) + print(k[:14], st, flush=True) + time.sleep(DELAY) + +print("проверено %d | живых %d | сумма $%.2f | коды %s" + % (len(rows), len(ok), sum(b for _, b in ok), codes)) +with open("alive.txt", "w", encoding="utf-8") as f: + f.write("\n".join(k for k, _ in ok)) \ No newline at end of file diff --git a/mail_reader.py b/mail_reader.py new file mode 100644 index 0000000..801afbd --- /dev/null +++ b/mail_reader.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""mail_reader.py [from_filter] + +Держит ОДНО IMAP-соединение и опрашивает его, вместо логина на каждом круге: +Gmail/aliyun/rambler отбивают частые повторные логины, и скрипт возвращает +NOLINK на письмо, которое реально пришло. + +Сканирует все папки один раз, дальше только те, где что-то было, + INBOX/Junk. + +Выход: одна строка с URL verify?token=... либо NOLINK (exit 1). +""" +import email +import html +import imaplib +import re +import sys +import time +from email.utils import parsedate_to_datetime + +EMAIL_ = sys.argv[1] +PW = sys.argv[2] +MIN_TS = int(sys.argv[3]) if len(sys.argv) > 3 else 0 +TIMEOUT = int(sys.argv[4]) if len(sys.argv) > 4 else 120 +FROMF = (sys.argv[5] if len(sys.argv) > 5 else "unrestricted").lower() + +DOM = EMAIL_.split("@")[-1].lower() + +# известные IMAP-хосты; для остальных пробуем imap.<домен> и mail.<домен> +KNOWN = { + "gmail.com": ["imap.gmail.com"], + "t-online.de": ["secureimap.t-online.de"], + "singnet.com.sg": ["imap.singnet.com.sg"], + "gazeta.pl": ["imap.gazeta.pl"], + "rambler.ru": ["imap.rambler.ru"], + "aliyun.com": ["imap.aliyun.com"], + "ldsubmissions.com": ["mail.ldsubmissions.com", "imap.ldsubmissions.com"], +} +hosts = KNOWN.get(DOM, ["imap." + DOM, "mail." + DOM]) + +VERIFY = re.compile(r"https?://[^\s\"'<>]*magic-link/verify\?token=([A-Za-z0-9_\-]{16,})([^\s\"'<>]*)") + + +def body_text(msg): + """Текст письма с декодом quoted-printable: без этого токен ссылки обрезается.""" + parts = [] + for p in (msg.walk() if msg.is_multipart() else [msg]): + try: + if p.get_content_type() not in ("text/plain", "text/html"): + continue + payload = p.get_payload(decode=True) + if payload: + parts.append(payload.decode(p.get_content_charset() or "utf-8", "replace")) + except Exception: + pass + t = "\n".join(parts).replace("=\r\n", "").replace("=\n", "") + return html.unescape(t) + + +def msg_ts(msg): + try: + return int(parsedate_to_datetime(msg.get("Date")).timestamp()) + except Exception: + return 0 + + +def folders(m): + out = [] + try: + typ, boxes = m.list() + for b in boxes or []: + s = b.decode("utf-8", "replace") if isinstance(b, bytes) else str(b) + mm = re.search(r'"([^"]*)"\s*$', s) + out.append(mm.group(1) if mm else s.split()[-1].strip('"')) + except Exception: + pass + for extra in ("INBOX", "Junk", "Spam", "Bulk"): + if extra not in out: + out.append(extra) + return out + + +def scan(m, boxes): + for box in boxes: + try: + m.select(box, readonly=True) + except Exception: + continue + try: + typ, d = m.search(None, "ALL") + ids = d[0].split()[-30:] if d and d[0] else [] + except Exception: + continue + for i in reversed(ids): + try: + t, msg = m.fetch(i, "(BODY.PEEK[])") + raw = msg[0][1] + except Exception: + continue + em = email.message_from_bytes(raw) + frm = (em.get("From") or "").lower() + if FROMF not in frm and FROMF not in raw.decode("utf-8", "replace").lower()[:4000]: + continue + ts = msg_ts(em) + if MIN_TS and ts and ts < MIN_TS - 3600: + continue + mm = VERIFY.search(body_text(em)) + if mm: + return "https://unrestricted.sh/api/auth/magic-link/verify?token=%s%s" % ( + mm.group(1), html.unescape(mm.group(2))) + return None + + +def main(): + t0 = time.time() + m = None + boxes = None + while time.time() - t0 < TIMEOUT: + if m is None: + for host in hosts: + try: + m = imaplib.IMAP4_SSL(host, 993) + m.login(EMAIL_, PW) + boxes = folders(m) + break + except Exception: + m = None + if m is None: + time.sleep(15) + continue + try: + link = scan(m, boxes) + if link: + print(link) + sys.exit(0) + except Exception: + try: + m.logout() + except Exception: + pass + m = None + time.sleep(10) + try: + m.logout() + except Exception: + pass + print("NOLINK") + sys.exit(1) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/proxies.txt.example b/proxies.txt.example new file mode 100644 index 0000000..dba522c --- /dev/null +++ b/proxies.txt.example @@ -0,0 +1,2 @@ +# один egress на строку: http://user:pass@host:port | socks5://host:port | direct +direct diff --git a/ur_reg.py b/ur_reg.py new file mode 100644 index 0000000..6806675 --- /dev/null +++ b/ur_reg.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""ur_reg.py — регистрация аккаунта на unrestricted.sh по HTTP (без браузера). + +Флоу: + Turnstile (2captcha) -> POST /api/auth/sign-in/magic-link (x-captcha-response) + -> письмо magic-link (IMAP) -> GET ссылки (cookie сессии) + -> GET /api/wallet (balanceMicrocents, welcomeWithheld) + -> POST /keys (Next-Action) -> unr_sk_... + +usage: + python ur_reg.py "email@domain:imap_password" [proxy|direct] + +Прокси: http://user:pass@host:port либо socks5://host:port. +Печать: одна JSON-строка с результатом. + +ENV: + TWOCAPTCHA_KEY ключ 2captcha (обязателен) + UR_MAIL_HOST ssh-хост с mail_reader.py (по умолчанию пусто = читать локально) + UR_MAIL_PATH путь к mail_reader.py на хосте (по умолчанию /root/mail_reader.py) + UR_SSH_KEY приватный ключ для ssh (по умолчанию ~/.ssh/id_ed25519) + UR_NEXT_ACTION Next-Action хэш эндпоинта /keys (меняется при деплое сервиса) + UR_MAIL_WAIT сколько секунд ждать письмо (по умолчанию 120) +""" +import json +import os +import re +import secrets +import subprocess +import sys +import time + +import requests + +BASE = "https://unrestricted.sh" +SITEKEY = "0x4AAAAAAE0Ejmo0NV9mf20B" +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36") +NEXT_ACTION = os.environ.get("UR_NEXT_ACTION", "60761de63c00065c1e86debf70258e1671b2173da1") +CAPKEY = os.environ.get("TWOCAPTCHA_KEY", "").strip() +MAIL_HOST = os.environ.get("UR_MAIL_HOST", "").strip() +MAIL_PATH = os.environ.get("UR_MAIL_PATH", "/root/mail_reader.py") +SSH_KEY = os.environ.get("UR_SSH_KEY", os.path.expanduser("~/.ssh/id_ed25519")) +MAIL_WAIT = int(os.environ.get("UR_MAIL_WAIT", "120")) + + +def solve(pageurl): + """Turnstile через 2captcha. Пустая строка = не решено.""" + if not CAPKEY: + return "" + try: + j = requests.post("https://2captcha.com/in.php", + data={"key": CAPKEY, "method": "turnstile", "sitekey": SITEKEY, + "pageurl": pageurl, "useragent": UA, "json": 1}, + timeout=40).json() + except Exception: + return "" + if j.get("status") != 1: + return "" + rid = j["request"] + for _ in range(40): + time.sleep(5) + try: + r = requests.get("https://2captcha.com/res.php", + params={"key": CAPKEY, "action": "get", "id": rid, "json": 1}, + timeout=30).json() + except Exception: + continue + if r.get("status") == 1: + return r["request"] + if r.get("request") != "CAPCHA_NOT_READY": + return "" + return "" + + +def _q(s): + return "'" + s.replace("'", "'\\''") + "'" + + +def wait_link(addr, pw, min_ts, timeout=None): + """Ищет ссылку в почте: локально либо через mail_reader.py по ssh.""" + timeout = timeout or MAIL_WAIT + args = "%s %s %d %d unrestricted.sh" % (_q(addr), _q(pw), min_ts, timeout) + if MAIL_HOST: + cmd = ["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=20", + "-i", SSH_KEY, MAIL_HOST, "python3 %s %s" % (MAIL_PATH, args)] + else: + cmd = [sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), + "mail_reader.py")] + \ + [addr, pw, str(min_ts), str(timeout), "unrestricted.sh"] + try: + r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout + 120) + for line in (r.stdout or "").splitlines(): + if line.startswith("https://"): + return line.strip() + except Exception: + return None + return None + + +def main(): + if len(sys.argv) < 2: + print(__doc__) + sys.exit(2) + cred = sys.argv[1] + proxy = sys.argv[2] if len(sys.argv) > 2 else "direct" + addr, pw = cred.split(":", 1) + rec = {"email": addr, "domain": addr.split("@")[-1].lower(), "proxy": proxy} + t0 = int(time.time()) - 60 + + s = requests.Session() + s.headers["user-agent"] = UA + if proxy != "direct": + s.proxies = {"http": proxy, "https": proxy} + + tok = solve(BASE + "/signup") + rec["captcha_len"] = len(tok) + if not tok: + rec["result"] = "captcha_fail" + print(json.dumps(rec, ensure_ascii=False)) + return + + headers = {"content-type": "application/json", "origin": BASE, + "referer": BASE + "/signup", "x-captcha-response": tok, + "x-signup-device": secrets.token_hex(16), + "x-signup-context": "%7B%22landingPath%22%3A%22%2Fsignup%22%7D", + "x-signup-automation": "none"} + body = {"email": addr, "callbackURL": "/dashboard", + "newUserCallbackURL": "/dashboard", "errorCallbackURL": "/auth/error"} + try: + r = s.post(BASE + "/api/auth/sign-in/magic-link", json=body, headers=headers, timeout=45) + except Exception as e: + rec["result"] = "err:" + type(e).__name__ + print(json.dumps(rec, ensure_ascii=False)) + return + rec["magiclink"] = [r.status_code, r.text[:120]] + if r.status_code == 429: + rec["result"] = "rate_limited" + print(json.dumps(rec, ensure_ascii=False)) + return + if r.status_code != 200: + low = r.text.lower() + rec["result"] = "domain_blocked" if ("domain" in low or "disposable" in low) else "magiclink_fail" + print(json.dumps(rec, ensure_ascii=False)) + return + + link = wait_link(addr, pw, t0) + rec["link"] = bool(link) + if not link: + rec["result"] = "no_mail" + print(json.dumps(rec, ensure_ascii=False)) + return + + v = None + last = "" + for _ in range(3): + try: + v = s.get(link, timeout=45, allow_redirects=True) + break + except Exception as e: + last = type(e).__name__ + time.sleep(3) + if v is None: + rec["result"] = "verify_err:" + last + print(json.dumps(rec, ensure_ascii=False)) + return + rec["final"] = v.url[:90] + if "/auth/error" in v.url: + rec["result"] = "verify_error" + print(json.dumps(rec, ensure_ascii=False)) + return + + try: + w = s.get(BASE + "/api/wallet", headers={"referer": BASE + "/dashboard"}, timeout=30).json() + except Exception: + w = {} + rec["balance"] = (w.get("balanceMicrocents") or 0) / 1e8 + rec["withheld"] = w.get("welcomeWithheld") + + h3 = {"content-type": "text/plain;charset=UTF-8", "accept": "text/x-component", + "next-action": NEXT_ACTION, "origin": BASE, "referer": BASE + "/dashboard"} + try: + k = s.post(BASE + "/keys", data=json.dumps(["First key", "home"]), headers=h3, timeout=45) + m = re.search(r"unr_sk_[a-z0-9]+", k.text) + rec["key"] = m.group(0) if m else "" + rec["keys_status"] = k.status_code + except Exception as e: + rec["key"] = "" + rec["keys_err"] = type(e).__name__ + rec["result"] = "credit" if rec["balance"] > 0 else "no_credit" + print(json.dumps(rec, ensure_ascii=False)) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/ur_shim.py b/ur_shim.py new file mode 100644 index 0000000..4969ecc --- /dev/null +++ b/ur_shim.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""ur-shim — OpenAI-совместимый ротатор ключей api.unrestricted.sh для new-api. +ENV: UR_PORT(48016) UR_BANK(/opt/ur-shim/bank.jsonl) UR_UPSTREAM(https://api.unrestricted.sh) +""" +import json +import os +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import urlparse + +import requests + +PORT = int(os.environ.get("UR_PORT", "48016")) +BANK = os.environ.get("UR_BANK", "/opt/ur-shim/bank.jsonl") +UPSTREAM = os.environ.get("UR_UPSTREAM", "https://api.unrestricted.sh").rstrip("/") +DEAD = os.environ.get("UR_DEAD", "/opt/ur-shim/dead.json") +DEAD_TTL = 6 * 3600 +LOCK = threading.Lock() +STATE = {"keys": [], "idx": 0, "dead": {}, "mtime": 0} + + +def load(): + with LOCK: + try: + mt = os.path.getmtime(BANK) + except OSError: + return + if mt <= STATE["mtime"]: + return + keys, seen = [], set() + try: + with open(BANK, encoding="utf-8", errors="ignore") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + rec = json.loads(line) + except Exception: + continue + k = rec.get("key") or "" + if not k.startswith("unr_sk_") or k in seen: + continue + bal = rec.get("balance") + if bal is not None and float(bal) <= 0: + continue + seen.add(k) + keys.append(k) + except OSError: + return + try: + STATE["dead"] = json.load(open(DEAD)) + except Exception: + STATE["dead"] = {} + STATE["keys"] = keys + STATE["mtime"] = mt + print("bank reloaded: %d keys" % len(keys), flush=True) + + +def alive_keys(): + now = time.time() + out = [] + for k in STATE["keys"]: + until = STATE["dead"].get(k, 0) + if until and until > now: + continue + out.append(k) + return out + + +def mark_dead(k, why=""): + with LOCK: + STATE["dead"][k] = time.time() + DEAD_TTL + try: + json.dump(STATE["dead"], open(DEAD, "w")) + except Exception: + pass + print("dead key %s… %s" % (k[:14], why), flush=True) + + +def pick(n=3): + ks = alive_keys() + if not ks: + return [] + start = STATE["idx"] + out = [ks[(start + i) % len(ks)] for i in range(min(n, len(ks)))] + with LOCK: + STATE["idx"] = (start + 1) % max(1, len(ks)) + return out + + +class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + return + + def _send(self, code, body, ctype="application/json"): + if isinstance(body, str): + body = body.encode() + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + p = urlparse(self.path).path + if p in ("/health", "/status"): + load() + self._send(200, json.dumps({"ok": True, "keys": len(STATE["keys"]), + "alive": len(alive_keys()), + "dead": len(STATE["dead"]), "upstream": UPSTREAM})) + return + if p.startswith("/v1/models"): + load() + ks = pick(2) + for k in ks: + try: + r = requests.get(UPSTREAM + "/v1/models", headers={"authorization": "Bearer " + k}, + timeout=25) + if r.status_code == 200: + self._send(200, r.content) + return + if r.status_code == 401: + mark_dead(k, '401') + elif r.status_code in (402, 403) and 'insufficient_quota' not in r.text: + mark_dead(k, str(r.status_code)) + except Exception as e: + print("models err", e, flush=True) + self._send(502, json.dumps({"error": {"message": "ur-shim: no live keys"}})) + return + self._send(404, json.dumps({"error": {"message": "not found"}})) + + def do_POST(self): + n = int(self.headers.get("content-length") or 0) + body = self.rfile.read(n) + p = urlparse(self.path).path + if not (p.endswith("/chat/completions") or p.endswith("/messages") or p.endswith("/completions")): + self._send(404, json.dumps({"error": {"message": "unsupported path " + p}})) + return + load() + target = UPSTREAM + p + ks = pick(3) + if not ks: + self._send(503, json.dumps({"error": {"message": "ur-shim: no live keys"}})) + return + try: + payload = json.loads(body.decode("utf-8", "ignore") or "{}") + except Exception: + payload = {} + stream = bool(payload.get("stream")) + last = None + for k in ks: + headers = {"authorization": "Bearer " + k, "content-type": "application/json", + "accept": "text/event-stream" if stream else "application/json"} + if self.headers.get("anthropic-version"): + headers["anthropic-version"] = self.headers["anthropic-version"] + try: + r = requests.post(target, data=body, headers=headers, timeout=300, stream=stream) + except Exception as e: + last = (502, json.dumps({"error": {"message": "upstream " + str(e)}})) + continue + if r.status_code == 401: + mark_dead(k, "401") + last = (r.status_code, r.text[:400]) + continue + if r.status_code in (402, 403) and 'insufficient_quota' not in r.text: + mark_dead(k, "%s %s" % (r.status_code, r.text[:80])) + last = (r.status_code, r.text[:400]) + continue + if r.status_code == 429: + last = (429, r.text[:200]) + continue + if stream and r.status_code == 200: + self.send_response(200) + self.send_header("content-type", r.headers.get("content-type", "text/event-stream")) + self.send_header("cache-control", "no-cache") + self.send_header("connection", "close") + self.end_headers() + try: + for chunk in r.iter_content(chunk_size=None): + if chunk: + self.wfile.write(chunk) + self.wfile.flush() + except Exception: + pass + return + self._send(r.status_code, r.content, + r.headers.get("content-type", "application/json")) + return + code, txt = last if last else (502, '{"error":{"message":"no keys"}}') + self._send(code if code not in (401, 402, 403) else 429, txt) + + +if __name__ == "__main__": + load() + srv = ThreadingHTTPServer(("127.0.0.1", PORT), H) + print("ur-shim on 127.0.0.1:%d upstream=%s keys=%d" % (PORT, UPSTREAM, len(STATE["keys"])), flush=True) + srv.serve_forever() \ No newline at end of file