minara.ai autoreg + pool shim: HTTP/browser cycles, domain scoring, 3 walls bypassed
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
# minara-autoreg
|
||||
|
||||
Авторегистрация аккаунтов [minara.ai](https://minara.ai) (OpenAI-совместимый агрегатор, 118 моделей: `anthropic/*`, `gpt-6.1-sol`, `grok-4.20`, `glm-5.3-prime`, …) и пул-шим для подключения к любому OpenAI-совместимому шлюзу.
|
||||
|
||||
Новый аккаунт = **300 кредитов**, рефка даёт приглашающему 200. Кредиты живут месяцами, ключи не нужны — API работает по аккаунт-токену.
|
||||
|
||||
## Что внутри
|
||||
|
||||
| Файл | Назначение |
|
||||
|---|---|
|
||||
| `core.py` | цикл регистрации: IMAP-baseline → 2captcha → `POST /auth/email/code` → чтение кода → `POST /auth/email/verify` с инвайтом |
|
||||
| `farm_parallel.py` | N воркеров, очередь `pool.jsonl`, банк `bank.jsonl`, журнал `farm_done.txt` |
|
||||
| `browser_farm.py` | тот же цикл, но `fetch` выполняется **из контекста реального Chrome** (обход анти-бот 403) |
|
||||
| `domain_score.py` | скоринг доменов по фактическим прогонам → whitelist + explore пулы |
|
||||
| `sync_tokens.py` | долив токенов на прод и рестарт шима |
|
||||
| `shim.py` | OpenAI-совместимый пул-шим: ротация токенов, дед-логика, SSE-passthrough |
|
||||
| `patch_gates2.py` | патчер гейтов шлюза (model_limits, rank_models, toolgate) с бэкапами |
|
||||
|
||||
## API minara
|
||||
|
||||
```
|
||||
POST https://api.minara.ai/auth/email/code {email, captchaToken} -> 201
|
||||
POST https://api.minara.ai/auth/email/verify {email, code, inviteCode, deviceId, deviceType} -> 201 {access_token}
|
||||
GET /auth/me -> creditBalance.total, invitedByUID, invitationCode
|
||||
GET /v1/models (118) POST /v1/chat/completions (stream + native tool_calls)
|
||||
```
|
||||
|
||||
Заголовки обязательны: `Origin: https://minara.ai`, `Referer: https://minara.ai/`, UA Chrome.
|
||||
Капча — reCAPTCHA v2, sitekey `6LfLGJQrAAAAANxZ6T3x1xZfasyW--3cOqldBQEv`, поле ровно `captchaToken`.
|
||||
Код письма — 6 алфанумерических символов в блоке `font-size:48px` (regex `\d{6}` ловит мусор).
|
||||
`+` в адресе запрещён: «Email addresses containing + cannot register new accounts».
|
||||
|
||||
## Стены и обходы (актуально на ноябрь 2026)
|
||||
|
||||
1. **10 кодов в час на IP** → ротация source-адресов: свой CONNECT-прокси внутри выданного /64
|
||||
(`ip -6 addr add <prefix>::<hex>/64 dev eth0 nodad` + чтение `/proc/net/if_inet6`).
|
||||
2. **`IPv6 subnet registration limit reached` (403 на verify)** — лимит на подсеть, не на адрес.
|
||||
Все адреса одного /48 = один бакет. Обход: разные провайдеры / мобильный egress.
|
||||
3. **Анти-бот на verify**: `requests` и даже `curl_cffi impersonate=chrome` получают 403,
|
||||
а тот же запрос `fetch`'ем из живой страницы `minara.ai` — 201. Поэтому и появился `browser_farm.py`.
|
||||
4. **Чёрный список доменов**: `{"message":"Domain X is not a valid domain"}` — дохлые бесплатные зоны
|
||||
отбрасываются на этапе send, капчу на них уже не жгём (отсев по `domain_stats.json`).
|
||||
5. **Троттлинг MTA получателя**: после ~1000-1700 регистраций на домен письма перестают доходить
|
||||
(`stage=mail`, ящик пуст). Домен уходит в карантин на 1-4 часа, потом оживает.
|
||||
Проверять одиночной пробой, а не волной.
|
||||
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
export TWOCAPTCHA_KEY=... # 2captcha
|
||||
export MINARA_INVITE=UM9Y8P # рефка
|
||||
export MINARA_PROXY_POOL=http://user:pass@host:18888,...
|
||||
export MINARA_LIVE_DIR=/path/to/live # каталог с live_<domain>.txt (email:pass)
|
||||
export MINARA_IMAPMAP=discovered_imap.json
|
||||
|
||||
# HTTP-путь (пока сервер не режет по TLS-фингерпринту)
|
||||
python farm_parallel.py 900 20
|
||||
|
||||
# браузерный путь (когда verify отдаёт 403)
|
||||
MINARA_BPROXY=http://user:pass@host:18888 python browser_farm.py 60 4
|
||||
|
||||
# пересобрать пулы по фактическим результатам
|
||||
python domain_score.py 0.4 1
|
||||
```
|
||||
|
||||
`MINARA_MAIL_TIMEOUT` — сколько ждать письмо (сек), `MINARA_FORCE_V4=1` — принудительно IPv4,
|
||||
`MINARA_IMPERSONATE=chrome` — curl_cffi вместо requests.
|
||||
|
||||
## Шим
|
||||
|
||||
`shim.py` — stdlib-сервер на `:48140`: держит `tokens.jsonl`, отдаёт `/health` и `/pool`,
|
||||
ротирует токены round-robin, помечает мёртвые по 401/402/403, пробрасывает SSE без изменений,
|
||||
маппит короткие имена (`claude-haiku-5.5` → `anthropic/claude-haiku-5.5`), кэширует список моделей 10 минут.
|
||||
|
||||
## Результаты прогона
|
||||
|
||||
```
|
||||
13 300+ аккаунтов, 3.99M кредитов, 99.7% живых токенов в пуле
|
||||
конверсия на обжитых доменах: 96-99.7% (волны 150/220/400/600 → 148/219/397/577)
|
||||
на смешанном пуле: 50-80% в зависимости от доли мёртвых доменов
|
||||
```
|
||||
|
||||
## Этика
|
||||
|
||||
Код писался для собственного пула аккаунтов и тестов нативности моделей.
|
||||
Массовая регистрация нарушает ToS сервиса — используйте на свой риск.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+278
@@ -0,0 +1,278 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minara farm через реальный Chrome (CDP): обходит 403 IPv6-лимит, который отбивает requests/curl_cffi.
|
||||
|
||||
Схема: Chrome с CDP-портом, страница https://minara.ai, дальше send/verify делаются fetch'ем
|
||||
ИЗ КОНТЕКСТА СТРАНИЦЫ (браузерный TLS/заголовки/HTTP2) — сервер такой запрос принимает,
|
||||
а прямой HTTP из python получает 403 "IPv6 subnet registration limit reached".
|
||||
|
||||
usage: python browser_farm.py <count> [workers]
|
||||
env: MINARA_POOL (default pool_whitelist.jsonl), MINARA_CDP_PORT (9250), MINARA_CDP_PROF
|
||||
"""
|
||||
import json
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
HERE = os.environ.get("MINARA_HOME") or os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
|
||||
PORT = int(os.environ.get("MINARA_CDP_PORT", "9250"))
|
||||
PROF = os.environ.get("MINARA_CDP_PROF", HERE + "/chprof")
|
||||
POOL = os.environ.get("MINARA_POOL", HERE + "/pool_whitelist.jsonl")
|
||||
DONE = HERE + "/farm_done.txt"
|
||||
BANK = HERE + "/bank.jsonl"
|
||||
INVITE = "UM9Y8P"
|
||||
SITEKEY = "6LfLGJQrAAAAANxZ6T3x1xZfasyW--3cOqldBQEv"
|
||||
CAPKEY = os.environ.get("TWOCAPTCHA_KEY", "").strip()
|
||||
|
||||
SEND_JS = """async (args) => {
|
||||
try {
|
||||
const r = await fetch('https://api.minara.ai/auth/email/code', {method:'POST',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify({email: args.email, captchaToken: args.tok})});
|
||||
return [r.status, (await r.text()).slice(0,200)];
|
||||
} catch(e) { return [0, String(e)]; }
|
||||
}"""
|
||||
|
||||
VERIFY_JS = """async (args) => {
|
||||
try {
|
||||
const r = await fetch('https://api.minara.ai/auth/email/verify', {method:'POST',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body: JSON.stringify(args.body)});
|
||||
return [r.status, (await r.text()).slice(0,400)];
|
||||
} catch(e) { return [0, String(e)]; }
|
||||
}"""
|
||||
|
||||
|
||||
def solve_captcha(timeout=180):
|
||||
import requests
|
||||
body = {"clientKey": CAPKEY,
|
||||
"task": {"type": "RecaptchaV2TaskProxyless", "websiteURL": "https://minara.ai/", "websiteKey": SITEKEY}}
|
||||
try:
|
||||
r = requests.post("https://api.2captcha.com/createTask", json=body, timeout=25).json()
|
||||
tid = r.get("taskId")
|
||||
if not tid:
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
time.sleep(4)
|
||||
try:
|
||||
s = requests.post("https://api.2captcha.com/getTaskResult",
|
||||
json={"clientKey": CAPKEY, "taskId": tid}, timeout=20).json()
|
||||
except Exception:
|
||||
continue
|
||||
if s.get("status") == "ready":
|
||||
return (s.get("solution") or {}).get("gRecaptchaResponse")
|
||||
return None
|
||||
|
||||
|
||||
def take(n):
|
||||
got = []
|
||||
if not os.path.exists(POOL):
|
||||
return got
|
||||
lines = open(POOL, encoding="utf8", errors="ignore").readlines()
|
||||
rest = []
|
||||
for l in lines:
|
||||
if len(got) < n and l.strip():
|
||||
try:
|
||||
got.append(json.loads(l))
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
rest.append(l)
|
||||
open(POOL, "w", encoding="utf8").writelines(rest)
|
||||
return got
|
||||
|
||||
|
||||
def mark(email, status):
|
||||
with open(DONE, "a", encoding="utf8") as fh:
|
||||
fh.write("%s\t%s\t%d\n" % (email, status, int(time.time())))
|
||||
|
||||
|
||||
def save(rec):
|
||||
with open(BANK, "a", encoding="utf8") as fh:
|
||||
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
def chrome_up():
|
||||
try:
|
||||
with urllib.request.urlopen("http://127.0.0.1:%d/json/version" % PORT, timeout=2) as r:
|
||||
return json.loads(r.read().decode())
|
||||
except Exception:
|
||||
pass
|
||||
os.makedirs(PROF, exist_ok=True)
|
||||
subprocess.Popen([CHROME, "--remote-debugging-port=%d" % PORT, "--user-data-dir=" + PROF,
|
||||
"--no-first-run", "--no-default-browser-check", "--disable-blink-features=AutomationControlled",
|
||||
"--window-size=900,700", "https://minara.ai/r/" + INVITE],
|
||||
creationflags=0x00000008 | 0x00000200)
|
||||
for _ in range(40):
|
||||
time.sleep(1)
|
||||
try:
|
||||
with urllib.request.urlopen("http://127.0.0.1:%d/json/version" % PORT, timeout=2) as r:
|
||||
return json.loads(r.read().decode())
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def worker(idx, rows, q):
|
||||
from playwright.sync_api import sync_playwright
|
||||
from core import imap_conn, find_code
|
||||
import uuid
|
||||
|
||||
proxies = [x for x in os.environ.get("MINARA_BPROXY", "").split(",") if x]
|
||||
px = proxies[idx % len(proxies)] if proxies else ""
|
||||
|
||||
def make_ctx(br, i):
|
||||
if px:
|
||||
scheme, rest = px.split("://", 1)
|
||||
auth, _, host = rest.rpartition("@")
|
||||
user, _, pwd = auth.partition(":")
|
||||
return br.new_context(proxy={"server": scheme + "://" + host, "username": user, "password": pwd})
|
||||
return br.new_context()
|
||||
|
||||
with sync_playwright() as pw:
|
||||
br = pw.chromium.connect_over_cdp("http://127.0.0.1:%d" % PORT)
|
||||
ctx = make_ctx(br, 0)
|
||||
page = ctx.new_page()
|
||||
page.goto("https://minara.ai/r/" + INVITE, wait_until="domcontentloaded", timeout=60000)
|
||||
time.sleep(2)
|
||||
n_used = 0
|
||||
for row in rows:
|
||||
if n_used and n_used % 12 == 0:
|
||||
try:
|
||||
page.close(); ctx.close()
|
||||
except Exception:
|
||||
pass
|
||||
ctx = make_ctx(br, n_used)
|
||||
page = ctx.new_page()
|
||||
page.goto("https://minara.ai/r/" + INVITE, wait_until="domcontentloaded", timeout=60000)
|
||||
time.sleep(1)
|
||||
n_used += 1
|
||||
em, pw_, dom = row["email"], row["pw"], row["dom"]
|
||||
out = {"email": em, "pw": pw_, "dom": dom}
|
||||
try:
|
||||
imap = imap_conn(dom, em, pw_)
|
||||
base = 0
|
||||
try:
|
||||
t, d = imap.uid("SEARCH", None, "ALL")
|
||||
uids = d[0].split() if d and d[0] else []
|
||||
base = int(uids[-1]) if uids else 0
|
||||
except Exception:
|
||||
base = 0
|
||||
except Exception as e:
|
||||
q.put(("FAIL", em, "imap", str(e)[:60]))
|
||||
mark(em, "imap")
|
||||
continue
|
||||
|
||||
tok = solve_captcha()
|
||||
if not tok:
|
||||
q.put(("FAIL", em, "captcha", ""))
|
||||
mark(em, "captcha")
|
||||
try:
|
||||
imap.logout()
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
|
||||
st, body = page.evaluate(SEND_JS, {"email": em, "tok": tok})
|
||||
if st != 201:
|
||||
reason = "invalid_domain" if "not a valid domain" in body else body[:60]
|
||||
q.put(("FAIL", em, "send", reason))
|
||||
mark(em, "send")
|
||||
try:
|
||||
imap.logout()
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
|
||||
code, end = None, time.time() + 150
|
||||
while time.time() < end:
|
||||
try:
|
||||
try:
|
||||
imap.noop()
|
||||
except Exception:
|
||||
imap = imap_conn(dom, em, pw_)
|
||||
code = find_code(imap, base)
|
||||
except Exception:
|
||||
try:
|
||||
imap = imap_conn(dom, em, pw_)
|
||||
except Exception:
|
||||
pass
|
||||
if code:
|
||||
break
|
||||
time.sleep(6)
|
||||
try:
|
||||
imap.logout()
|
||||
except Exception:
|
||||
pass
|
||||
if not code:
|
||||
q.put(("FAIL", em, "mail", ""))
|
||||
mark(em, "mail")
|
||||
continue
|
||||
|
||||
vbody = {"email": em, "code": code, "inviteCode": INVITE,
|
||||
"deviceId": uuid.uuid4().hex, "deviceType": "web"}
|
||||
st2, body2 = page.evaluate(VERIFY_JS, {"body": vbody})
|
||||
if st2 != 201 or "access_token" not in body2:
|
||||
q.put(("FAIL", em, "verify", str(st2) + " " + body2[:70]))
|
||||
mark(em, "verify")
|
||||
continue
|
||||
try:
|
||||
j = json.loads(body2)
|
||||
except Exception:
|
||||
j = {}
|
||||
out.update({"ok": True, "token": j.get("access_token", ""), "uid": j.get("id", "")})
|
||||
save(out)
|
||||
mark(em, "ok")
|
||||
q.put(("OK", em, "", ""))
|
||||
try:
|
||||
page.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
count = int(sys.argv[1]) if len(sys.argv) > 1 else 20
|
||||
workers = int(sys.argv[2]) if len(sys.argv) > 2 else 2
|
||||
v = chrome_up()
|
||||
print("cdp:", bool(v), flush=True)
|
||||
if not v:
|
||||
print("chrome not up", flush=True)
|
||||
return
|
||||
rows = take(count)
|
||||
print("batch:", len(rows), "workers:", workers, flush=True)
|
||||
# делим на пачки
|
||||
chunks = [rows[i::workers] for i in range(workers)]
|
||||
q = mp.Queue()
|
||||
procs = [mp.Process(target=worker, args=(i, chunks[i], q)) for i in range(workers) if chunks[i]]
|
||||
for p in procs:
|
||||
p.start()
|
||||
ok = fail = 0
|
||||
got = 0
|
||||
while got < len(rows):
|
||||
try:
|
||||
tag, em, stage, msg = q.get(timeout=600)
|
||||
except Exception:
|
||||
break
|
||||
got += 1
|
||||
if tag == "OK":
|
||||
ok += 1
|
||||
print("OK ", em, flush=True)
|
||||
else:
|
||||
fail += 1
|
||||
print("FAIL", em, stage, msg[:80], flush=True)
|
||||
for p in procs:
|
||||
p.join(timeout=30)
|
||||
print("DONE ok=%d/%d" % (ok, len(rows)), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minara reg core: baseline UID -> send code -> wait NEW mail -> verify.
|
||||
|
||||
usage: python core.py <email> <pass> [invite|none]
|
||||
"""
|
||||
import imaplib, json, os, poplib, random, re, sys, time
|
||||
|
||||
if os.environ.get("MINARA_FORCE_V4"):
|
||||
import socket as _sock
|
||||
|
||||
_orig_gai = _sock.getaddrinfo
|
||||
|
||||
def _v4_only(host, port, family=0, type=0, proto=0, flags=0):
|
||||
return _orig_gai(host, port, _sock.AF_INET, type, proto, flags)
|
||||
|
||||
_sock.getaddrinfo = _v4_only
|
||||
import email as emaillib
|
||||
import requests
|
||||
|
||||
HERE = os.environ.get("MINARA_HOME") or os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
from flow import solve_captcha
|
||||
|
||||
API = "https://api.minara.ai"
|
||||
INVITE = os.environ.get("MINARA_INVITE", "UM9Y8P")
|
||||
PROXIES = [p.strip() for p in os.environ.get("MINARA_PROXY_POOL", "").split(",") if p.strip()]
|
||||
IMAPMAP_PATH = os.environ.get("MINARA_IMAPMAP", "discovered_imap.json")
|
||||
IMAPMAP = json.load(open(IMAPMAP_PATH)) if os.path.exists(IMAPMAP_PATH) else {}
|
||||
POP_HOSTS = {"rediffmail.com": ("pop.rediffmail.com", 995)}
|
||||
BANK = os.environ.get("MINARA_BANK", HERE + "/bank.jsonl")
|
||||
HDRS = {
|
||||
"Content-Type": "application/json",
|
||||
"Origin": "https://minara.ai",
|
||||
"Referer": "https://minara.ai/",
|
||||
"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",
|
||||
}
|
||||
|
||||
def new_session():
|
||||
p = random.choice(PROXIES)
|
||||
if os.environ.get("MINARA_IMPERSONATE"):
|
||||
from curl_cffi import requests as cffi
|
||||
s = cffi.Session(impersonate=os.environ.get("MINARA_IMPERSONATE") or "chrome")
|
||||
if p:
|
||||
s.proxies = {"http": p, "https": p}
|
||||
s.headers.update(HDRS)
|
||||
return s
|
||||
s = requests.Session()
|
||||
s.proxies = {"http": p, "https": p}
|
||||
s.headers.update(HDRS)
|
||||
return s
|
||||
|
||||
def imap_conn(dom, user, pw):
|
||||
host, port = IMAPMAP.get(dom, ("imap." + dom, 993))
|
||||
port = int(port)
|
||||
c = imaplib.IMAP4_SSL(host, port, timeout=25) if port == 993 else imaplib.IMAP4(host, port, timeout=25)
|
||||
c.login(user, pw)
|
||||
c.select("INBOX")
|
||||
return c
|
||||
|
||||
def max_uid(c):
|
||||
t, d = c.uid("SEARCH", None, "ALL")
|
||||
ids = d[0].split() if d and d[0] else []
|
||||
return int(ids[-1]) if ids else 0
|
||||
|
||||
def find_code(c, since_uid):
|
||||
"""Быстрый поиск: только письма от minara.ai новее since_uid (без полного скана ящика)."""
|
||||
d_since = time.strftime("%d-%b-%Y", time.localtime(time.time() - 86400))
|
||||
try:
|
||||
t, d = c.uid("SEARCH", None, "ALL")
|
||||
raw = d[0].split() if d and d[0] else []
|
||||
except Exception:
|
||||
raise
|
||||
uids = sorted(int(u) for u in raw if int(u) > since_uid)[-3:]
|
||||
if not uids:
|
||||
return None
|
||||
for u in reversed(uids):
|
||||
t, m = c.uid("FETCH", str(u).encode(), "(BODY.PEEK[])")
|
||||
if not m or not m[0]:
|
||||
continue
|
||||
msg = emaillib.message_from_bytes(m[0][1])
|
||||
if "minara.ai" not in (msg.get("From") or "").lower():
|
||||
continue
|
||||
body = ""
|
||||
for p in msg.walk():
|
||||
if p.get_content_type() in ("text/plain", "text/html"):
|
||||
body += (p.get_payload(decode=True) or b"").decode("utf8", "ignore")
|
||||
m1 = re.search(r"font-size:\s*48px[\s\S]{0,500}?>\s*([A-Za-z0-9]{6})\s*<", body)
|
||||
if m1:
|
||||
return m1.group(1)
|
||||
dc = re.findall(r"(?<!\d)(\d{6})(?!\d)", re.sub(r"<[^>]+>", " ", body))
|
||||
if dc:
|
||||
return dc[0]
|
||||
return None
|
||||
|
||||
def pop_conn(dom, user, pw):
|
||||
host = POP_HOSTS.get(dom) or ("pop." + dom, 995)
|
||||
c = poplib.POP3_SSL(host[0], host[1], timeout=25)
|
||||
c.user(user)
|
||||
c.pass_(pw)
|
||||
return c
|
||||
|
||||
|
||||
def pop_find_code(dom, user, pw, since_ts, timeout=240):
|
||||
"""POP3 fallback (rediffmail и подобные): свежее письмо от minara.ai."""
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
c = pop_conn(dom, user, pw)
|
||||
n = len(c.list()[1])
|
||||
for i in range(n, max(1, n - 12), -1):
|
||||
try:
|
||||
resp, lines, _ = c.retr(i)
|
||||
except Exception:
|
||||
continue
|
||||
raw = b"\n".join(lines)
|
||||
m = emaillib.message_from_bytes(raw)
|
||||
if "minara.ai" not in (m.get("From") or "").lower():
|
||||
continue
|
||||
body = ""
|
||||
for p in m.walk():
|
||||
if p.get_content_type() in ("text/plain", "text/html"):
|
||||
body += (p.get_payload(decode=True) or b"").decode("utf8", "ignore")
|
||||
m1 = re.search(r"font-size:\s*48px[\s\S]{0,500}?>\s*([A-Za-z0-9]{6})\s*<", body)
|
||||
code = m1.group(1) if m1 else None
|
||||
if not code:
|
||||
dc = re.findall(r"(?<!\d)(\d{6})(?!\d)", re.sub(r"<[^>]+>", " ", body))
|
||||
code = dc[0] if dc else None
|
||||
if code:
|
||||
try:
|
||||
c.quit()
|
||||
except Exception:
|
||||
pass
|
||||
return code
|
||||
try:
|
||||
c.quit()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(8)
|
||||
return None
|
||||
|
||||
|
||||
def register(em, pw, dom, invite=INVITE, timeout=None):
|
||||
if timeout is None:
|
||||
timeout = int(os.environ.get("MINARA_MAIL_TIMEOUT", "240"))
|
||||
s = new_session()
|
||||
use_pop = False
|
||||
try:
|
||||
c = imap_conn(dom, em, pw)
|
||||
base = max_uid(c)
|
||||
except Exception as e:
|
||||
c = None
|
||||
use_pop = True
|
||||
base = 0
|
||||
print(" imap-fallback->pop", em, str(e)[:60], flush=True)
|
||||
tok = solve_captcha()
|
||||
if not tok:
|
||||
return {"email": em, "ok": False, "stage": "captcha"}
|
||||
r = s.post(API + "/auth/email/code", json={"email": em, "captchaToken": tok}, timeout=40)
|
||||
if '"success":true' not in r.text:
|
||||
return {"email": em, "ok": False, "stage": "send", "http": r.status_code, "resp": r.text[:200]}
|
||||
code = None
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
if use_pop:
|
||||
code = pop_find_code(dom, em, pw, time.time(), timeout=30)
|
||||
else:
|
||||
try:
|
||||
c.noop()
|
||||
except Exception:
|
||||
c = imap_conn(dom, em, pw)
|
||||
c.select("INBOX")
|
||||
code = find_code(c, base)
|
||||
except Exception:
|
||||
try:
|
||||
c = imap_conn(dom, em, pw)
|
||||
c.select("INBOX")
|
||||
except Exception:
|
||||
pass
|
||||
if code:
|
||||
break
|
||||
time.sleep(6)
|
||||
try:
|
||||
if c:
|
||||
c.logout()
|
||||
except Exception:
|
||||
pass
|
||||
if not code:
|
||||
return {"email": em, "ok": False, "stage": "mail"}
|
||||
body = {"email": em, "code": code, "channel": None,
|
||||
"deviceId": "".join(random.choices("0123456789abcdef", k=32)), "deviceType": "web"}
|
||||
if invite and invite.lower() != "none":
|
||||
body["inviteCode"] = invite
|
||||
r = s.post(API + "/auth/email/verify", json=body, timeout=40)
|
||||
try:
|
||||
j = json.loads(r.text)
|
||||
except Exception:
|
||||
return {"email": em, "ok": False, "stage": "verify", "http": r.status_code, "resp": r.text[:200]}
|
||||
at = j.get("access_token")
|
||||
if not at:
|
||||
return {"email": em, "ok": False, "stage": "verify", "code_used": code, "http": r.status_code, "resp": j}
|
||||
me = s.get(API + "/auth/me", headers={"Authorization": "Bearer " + at}, timeout=40)
|
||||
rec = {"email": em, "pw": pw, "dom": dom, "ok": True, "token": at, "me_http": me.status_code,
|
||||
"me": me.text[:2000], "ts": int(time.time())}
|
||||
with open(BANK, "a", encoding="utf8") as fh:
|
||||
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
return rec
|
||||
|
||||
if __name__ == "__main__":
|
||||
em, pw = sys.argv[1], sys.argv[2]
|
||||
inv = sys.argv[3] if len(sys.argv) > 3 else INVITE
|
||||
print(json.dumps(register(em, pw, em.split("@")[-1].lower(), inv), ensure_ascii=False)[:1500])
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собирает статистику доменов из всех farm*.log и строит отфильтрованный пул.
|
||||
|
||||
usage: python domain_score.py [min_rate] [min_ok]
|
||||
Writes: domain_stats.json, pool_whitelist.jsonl
|
||||
"""
|
||||
import glob, io, json, os, re, sys
|
||||
|
||||
HERE = os.environ.get("MINARA_HOME") or os.path.dirname(os.path.abspath(__file__))
|
||||
ok = {}
|
||||
bad = {}
|
||||
|
||||
|
||||
def bump(d, k):
|
||||
d[k] = d.get(k, 0) + 1
|
||||
|
||||
|
||||
for path in glob.glob(HERE + "/farm*.log"):
|
||||
for line in io.open(path, encoding="utf8", errors="ignore"):
|
||||
line = line.rstrip()
|
||||
if not line or "@" not in line:
|
||||
continue
|
||||
m = re.search(r"@([A-Za-z0-9._-]+)", line)
|
||||
if not m:
|
||||
continue
|
||||
dom = m.group(1).lower()
|
||||
if line.startswith("OK "):
|
||||
bump(ok, dom)
|
||||
elif "FAIL" in line:
|
||||
bump(bad, dom)
|
||||
|
||||
stats = {}
|
||||
for dom in set(list(ok) + list(bad)):
|
||||
o, b = ok.get(dom, 0), bad.get(dom, 0)
|
||||
stats[dom] = {"ok": o, "bad": b, "rate": round(o / (o + b), 3) if o + b else 0}
|
||||
json.dump(stats, io.open(HERE + "/domain_stats.json", "w", encoding="utf8"), ensure_ascii=False, indent=1)
|
||||
|
||||
min_rate = float(sys.argv[1]) if len(sys.argv) > 1 else 0.4
|
||||
min_ok = int(sys.argv[2]) if len(sys.argv) > 2 else 1
|
||||
|
||||
good = {d for d, s in stats.items() if s["ok"] >= min_ok and s["rate"] >= min_rate}
|
||||
dead = {d for d, s in stats.items() if s["ok"] == 0 and s["bad"] >= 2}
|
||||
|
||||
rows, seen = [], set()
|
||||
|
||||
# не выдавать повторно уже обработанные ящики (farm_done) и зарегистрированные (bank)
|
||||
for name in ("farm_done.txt", "bank.jsonl"):
|
||||
p = os.path.join(HERE, name)
|
||||
if not os.path.exists(p):
|
||||
continue
|
||||
for line in io.open(p, encoding="utf8", errors="ignore"):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
em = line.split("\t")[0].strip().lower()
|
||||
if name == "bank.jsonl":
|
||||
try:
|
||||
em = (json.loads(line).get("email") or "").strip().lower()
|
||||
except Exception:
|
||||
pass
|
||||
if em:
|
||||
seen.add(em)
|
||||
|
||||
for f in ("pool_mix.jsonl", "pool.jsonl"):
|
||||
p = os.path.join(HERE, f)
|
||||
if not os.path.exists(p):
|
||||
continue
|
||||
for line in io.open(p, encoding="utf8", errors="ignore"):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
dom = (r.get("dom") or "").lower()
|
||||
em = (r.get("email") or "").lower()
|
||||
if em in seen or dom in dead or dom not in good:
|
||||
continue
|
||||
seen.add(em)
|
||||
rows.append(r)
|
||||
|
||||
with io.open(HERE + "/pool_whitelist.jsonl", "w", encoding="utf8") as fh:
|
||||
for r in rows:
|
||||
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
|
||||
# exploration lane: домены без статистики (новые), чтобы расширять whitelist
|
||||
explore = []
|
||||
seen2 = set()
|
||||
for f in ("pool_mix.jsonl", "pool.jsonl"):
|
||||
p = os.path.join(HERE, f)
|
||||
if not os.path.exists(p):
|
||||
continue
|
||||
for line in io.open(p, encoding="utf8", errors="ignore"):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
dom = (r.get("dom") or "").lower()
|
||||
em = (r.get("email") or "").lower()
|
||||
if dom in stats or em in seen or em in seen2:
|
||||
continue
|
||||
seen2.add(em)
|
||||
explore.append(r)
|
||||
with io.open(HERE + "/pool_explore.jsonl", "w", encoding="utf8") as fh:
|
||||
for r in explore:
|
||||
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
|
||||
print("explore pool (unseen domains):", len(explore), "| domains:", len({r["dom"] for r in explore}))
|
||||
|
||||
print("domains scored:", len(stats), "| good:", len(good), "| dead:", len(dead))
|
||||
print("whitelist pool:", len(rows), "| domains:", len({r["dom"] for r in rows}))
|
||||
top = sorted(stats.items(), key=lambda kv: (-kv[1]["rate"], -kv[1]["ok"]))[:10]
|
||||
print("top:", [(d, s["ok"], s["bad"]) for d, s in top])
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minara parallel farm: N workers register accounts via rotating IPv6 proxies.
|
||||
|
||||
usage: python farm_parallel.py <count> [workers]
|
||||
Writes: bank.jsonl (tokens), pool.jsonl (queue), farm_done.txt (processed emails)
|
||||
"""
|
||||
import json, os, random, sys, threading, time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
HERE = os.environ.get("MINARA_HOME") or os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
from core import register, BANK
|
||||
|
||||
POOL = os.environ.get("MINARA_POOL") or (HERE + "/pool.jsonl")
|
||||
DONE = HERE + "/farm_done.txt"
|
||||
LOCK = threading.Lock()
|
||||
|
||||
DOMAINS = [d for d in os.environ.get(
|
||||
"MINARA_DOMAINS",
|
||||
"rambler.ru,bfirstmail.com,singnet.com.sg,topnet.tn,mail.tmwlsw.com,ldsubmissions.com"
|
||||
).split(",") if d]
|
||||
|
||||
|
||||
def build_pool():
|
||||
if os.path.exists(POOL) and os.path.getsize(POOL) > 0:
|
||||
return
|
||||
done = set()
|
||||
if os.path.exists(BANK):
|
||||
for l in open(BANK, encoding="utf8"):
|
||||
try:
|
||||
done.add(json.loads(l)["email"].lower())
|
||||
except Exception:
|
||||
pass
|
||||
rows, seen = [], set(done)
|
||||
for dom in DOMAINS:
|
||||
p = os.path.join(os.environ.get("MINARA_LIVE_DIR", "live"), "live_%s.txt" % dom)
|
||||
if not os.path.exists(p):
|
||||
print("no pool file for", dom, flush=True)
|
||||
continue
|
||||
for line in open(p, encoding="utf8", errors="ignore"):
|
||||
line = line.strip()
|
||||
if "@" + dom not in line:
|
||||
continue
|
||||
em, _, pw = line.partition(":")
|
||||
em = em.strip().lower()
|
||||
pw = pw.strip()
|
||||
if not pw or em in seen:
|
||||
continue
|
||||
seen.add(em)
|
||||
rows.append({"email": em, "pw": pw, "dom": dom})
|
||||
random.shuffle(rows)
|
||||
with open(POOL, "w", encoding="utf8") as fh:
|
||||
for r in rows:
|
||||
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
print("pool built:", len(rows), flush=True)
|
||||
|
||||
|
||||
def take(n):
|
||||
got = []
|
||||
with LOCK:
|
||||
with open(POOL, encoding="utf8") as fh:
|
||||
lines = fh.readlines()
|
||||
rest = []
|
||||
for l in lines:
|
||||
if not l.strip():
|
||||
continue
|
||||
try:
|
||||
r = json.loads(l)
|
||||
except Exception:
|
||||
continue
|
||||
if len(got) < n and (not DOMAINS or r.get("dom") in DOMAINS):
|
||||
got.append(r)
|
||||
else:
|
||||
rest.append(l)
|
||||
with open(POOL, "w", encoding="utf8") as fh:
|
||||
fh.writelines(rest)
|
||||
return got
|
||||
|
||||
|
||||
def worker(row):
|
||||
try:
|
||||
rec = register(row["email"], row["pw"], row["dom"])
|
||||
except Exception as e:
|
||||
rec = {"email": row["email"], "ok": False, "stage": "exception", "err": str(e)[:150]}
|
||||
with LOCK:
|
||||
with open(DONE, "a", encoding="utf8") as fh:
|
||||
fh.write("%s\t%s\t%s\n" % (row["email"], "ok" if rec.get("ok") else rec.get("stage"), int(time.time())))
|
||||
tag = "OK " if rec.get("ok") else "FAIL"
|
||||
try:
|
||||
msg = rec.get("resp") or rec.get("err") or ""
|
||||
if not isinstance(msg, str):
|
||||
msg = json.dumps(msg, ensure_ascii=False, default=str)
|
||||
print(tag, row["email"], rec.get("stage") or "", "" if rec.get("ok") else msg[:90], flush=True)
|
||||
except Exception:
|
||||
print(tag, row.get("email", "?"), "print-error", flush=True)
|
||||
return rec
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
count = int(sys.argv[1]) if len(sys.argv) > 1 else 20
|
||||
workers = int(sys.argv[2]) if len(sys.argv) > 2 else 5
|
||||
build_pool()
|
||||
rows = take(count)
|
||||
print("batch:", len(rows), "workers:", workers, flush=True)
|
||||
ok = 0
|
||||
with ThreadPoolExecutor(max_workers=workers) as ex:
|
||||
futs = [ex.submit(worker, r) for r in rows]
|
||||
for f in as_completed(futs):
|
||||
if f.result().get("ok"):
|
||||
ok += 1
|
||||
print("DONE ok=%d/%d" % (ok, len(rows)), flush=True)
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minara auto-reg: reCAPTCHA v2 -> email code -> verify with invite code."""
|
||||
import base64, email as emaillib, imaplib, json, os, random, re, string, sys, time
|
||||
import requests
|
||||
|
||||
API = "https://api.minara.ai"
|
||||
SITEKEY = "6LfLGJQrAAAAANxZ6T3x1xZfasyW--3cOqldBQEv"
|
||||
PAGEURL = "https://minara.ai/home?code=UM9Y8P&from=user"
|
||||
INVITE = "UM9Y8P"
|
||||
CAPKEY = os.environ.get("TWOCAPTCHA_KEY", "").strip()
|
||||
HDRS = {
|
||||
"Content-Type": "application/json",
|
||||
"Origin": "https://minara.ai",
|
||||
"Referer": "https://minara.ai/",
|
||||
"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",
|
||||
}
|
||||
PX = os.environ.get("MINARA_PROXY", "").strip()
|
||||
PROXIES = {"http": PX, "https": PX} if PX else None
|
||||
|
||||
def solve_captcha(pageurl=PAGEURL, tries=3):
|
||||
for t in range(tries):
|
||||
try:
|
||||
r = requests.post("https://api.2captcha.com/createTask", json={
|
||||
"clientKey": CAPKEY,
|
||||
"task": {"type": "RecaptchaV2TaskProxyless", "websiteURL": pageurl,
|
||||
"websiteKey": SITEKEY}
|
||||
}, timeout=30).json()
|
||||
except Exception:
|
||||
time.sleep(5)
|
||||
continue
|
||||
if r.get("errorId"):
|
||||
print("cap create err", r, flush=True)
|
||||
time.sleep(5); continue
|
||||
tid = r["taskId"]
|
||||
print("captcha task", tid, flush=True)
|
||||
for _ in range(40):
|
||||
time.sleep(5)
|
||||
try:
|
||||
g = requests.post("https://api.2captcha.com/getTaskResult", json={
|
||||
"clientKey": CAPKEY, "taskId": tid}, timeout=30).json()
|
||||
except Exception:
|
||||
time.sleep(3)
|
||||
continue
|
||||
if g.get("status") == "ready":
|
||||
return g["solution"]["gRecaptchaResponse"]
|
||||
if g.get("errorId"):
|
||||
print("cap poll err", g, flush=True); break
|
||||
return None
|
||||
|
||||
def send_code(email):
|
||||
r = requests.post(f"{API}/auth/email/code", headers=HDRS,
|
||||
json={"email": email, "captchaToken": solve_captcha()}, timeout=40, proxies=PROXIES)
|
||||
return r.status_code, r.text
|
||||
|
||||
def gmail_code(gm, gp, alias, since_ts, timeout=180):
|
||||
box = imaplib.IMAP4_SSL("imap.gmail.com")
|
||||
box.login(gm, gp)
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
box.select("INBOX")
|
||||
typ, data = box.search(None, 'X-GM-RAW', '"to:%s newer_than:1d"' % alias)
|
||||
ids = (data[0].split() if data and data[0] else [])[-6:]
|
||||
for i in reversed(ids):
|
||||
typ, msg = box.fetch(i, "(RFC822)")
|
||||
if not msg or not msg[0]:
|
||||
continue
|
||||
m = emaillib.message_from_bytes(msg[0][1])
|
||||
body = ""
|
||||
if m.is_multipart():
|
||||
for p in m.walk():
|
||||
if p.get_content_type() in ("text/plain", "text/html"):
|
||||
body += p.get_payload(decode=True).decode("utf8", "ignore")
|
||||
else:
|
||||
body = m.get_payload(decode=True).decode("utf8", "ignore")
|
||||
if "minara" not in (m.get("From", "") + body).lower():
|
||||
continue
|
||||
codes = re.findall(r"\b(\d{6})\b", body)
|
||||
if codes:
|
||||
box.logout()
|
||||
return codes[0]
|
||||
time.sleep(6)
|
||||
box.logout()
|
||||
return None
|
||||
|
||||
def verify(email, code):
|
||||
r = requests.post(f"{API}/auth/email/verify", headers=HDRS, json={
|
||||
"email": email, "code": code, "inviteCode": INVITE,
|
||||
"deviceId": "".join(random.choices(string.hexdigits.lower(), k=32)),
|
||||
"deviceType": "web",
|
||||
}, timeout=40, proxies=PROXIES)
|
||||
return r.status_code, r.text
|
||||
|
||||
def me(tok):
|
||||
r = requests.get(f"{API}/auth/me", headers={**HDRS, "Authorization": "Bearer " + tok}, timeout=30, proxies=PROXIES)
|
||||
return r.status_code, r.text[:1200]
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Patch iishko gates for minara-pool models (line-based, no escape games)."""
|
||||
import json, py_compile, shutil, time
|
||||
|
||||
MODELS = json.load(open("/root/minara_models.json", encoding="utf-8"))
|
||||
ts = time.strftime("%Y%m%d-%H%M%S")
|
||||
TAG = " # [MINARA 1106]"
|
||||
|
||||
line_sso = "MODELS += [m for m in " + repr(MODELS) + " if m not in MODELS]" + TAG
|
||||
line_rank = " models += [m for m in " + repr(MODELS) + " if m not in models]" + TAG
|
||||
line_tool = "ALLOW += [m for m in " + repr(MODELS) + " if m not in ALLOW]" + TAG
|
||||
|
||||
|
||||
def insert_after(path, anchor, newline):
|
||||
lines = open(path, encoding="utf-8").read().split("\n")
|
||||
if any("MINARA 1106" in l for l in lines):
|
||||
return "already"
|
||||
idx = [i for i, l in enumerate(lines) if anchor in l]
|
||||
if not idx:
|
||||
return "anchor-missing"
|
||||
shutil.copy2(path, path + ".bak-minara-" + ts)
|
||||
out = lines[:idx[0] + 1] + [newline] + lines[idx[0] + 1:]
|
||||
open(path, "w", encoding="utf-8").write("\n".join(out))
|
||||
py_compile.compile(path, doraise=True)
|
||||
return "patched"
|
||||
|
||||
|
||||
def insert_before(path, anchor, newline):
|
||||
lines = open(path, encoding="utf-8").read().split("\n")
|
||||
if any("MINARA 1106" in l for l in lines):
|
||||
return "already"
|
||||
idx = [i for i, l in enumerate(lines) if anchor in l]
|
||||
if not idx:
|
||||
return "anchor-missing"
|
||||
shutil.copy2(path, path + ".bak-minara-" + ts)
|
||||
out = lines[:idx[0]] + [newline] + lines[idx[0]:]
|
||||
open(path, "w", encoding="utf-8").write("\n".join(out))
|
||||
py_compile.compile(path, doraise=True)
|
||||
return "patched"
|
||||
|
||||
|
||||
def append_line(path, newline):
|
||||
lines = open(path, encoding="utf-8").read().split("\n")
|
||||
if any("MINARA 1106" in l for l in lines):
|
||||
return "already"
|
||||
shutil.copy2(path, path + ".bak-minara-" + ts)
|
||||
out = lines + [newline, ""]
|
||||
open(path, "w", encoding="utf-8").write("\n".join(out))
|
||||
py_compile.compile(path, doraise=True)
|
||||
return "patched"
|
||||
|
||||
|
||||
print("sso_limits:", insert_before("/root/sso_limits.py", "parts = [x.strip()", line_sso))
|
||||
print("legacy:", insert_after("/opt/grok-bot/iishko/legacy.py",
|
||||
"models += IMG_MODELS + IMG_ALWAYS + DISC_MODELS + WUS_MODELS", line_rank))
|
||||
print("toolgate:", append_line("/root/toolgate.py", line_tool))
|
||||
for p in ("/root/sso_limits.py", "/opt/grok-bot/iishko/legacy.py", "/root/toolgate.py"):
|
||||
n = sum(1 for l in open(p, encoding="utf-8") if "MINARA 1106" in l)
|
||||
print(p, "markers:", n)
|
||||
@@ -0,0 +1,268 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minara AI -> OpenAI-compatible pool shim.
|
||||
|
||||
Upstream is already OpenAI-shaped: https://api.minara.ai/v1 (118 models).
|
||||
Shim only pools account access_tokens (300 credits each), rotates them,
|
||||
marks burned ones dead and relays SSE streams as-is.
|
||||
|
||||
Endpoints:
|
||||
GET /v1/models
|
||||
POST /v1/chat/completions (stream supported)
|
||||
GET /health
|
||||
GET /pool (per-token credit snapshot)
|
||||
|
||||
Env:
|
||||
MINARA_PORT (default 48140)
|
||||
MINARA_TOKENS (default /opt/minara-shim/tokens.jsonl)
|
||||
MINARA_STATE (default /opt/minara-shim/state.json)
|
||||
"""
|
||||
import json, os, re, sys, threading, time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import requests
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
UP = "https://api.minara.ai"
|
||||
TOKENS_PATH = os.environ.get("MINARA_TOKENS") or os.path.join(HERE, "tokens.jsonl")
|
||||
STATE_PATH = os.environ.get("MINARA_STATE") or os.path.join(HERE, "state.json")
|
||||
PORT = int(os.environ.get("MINARA_PORT", sys.argv[1] if len(sys.argv) > 1 else "48140"))
|
||||
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"
|
||||
DEAD_TTL = int(os.environ.get("MINARA_DEAD_TTL", "1800"))
|
||||
|
||||
LOCK = threading.Lock()
|
||||
RR = [0]
|
||||
TOKENS = [] # [{email, token, dead_until, credits, fail}]
|
||||
MODELS_CACHE = {"ts": 0, "data": None}
|
||||
|
||||
|
||||
def log(*a):
|
||||
print(time.strftime("%H:%M:%S"), *a, flush=True)
|
||||
|
||||
|
||||
def load_tokens():
|
||||
global TOKENS
|
||||
rows = []
|
||||
if os.path.exists(TOKENS_PATH):
|
||||
for line in open(TOKENS_PATH, encoding="utf-8"):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
if r.get("token"):
|
||||
rows.append(r)
|
||||
st = {}
|
||||
if os.path.exists(STATE_PATH):
|
||||
try:
|
||||
st = json.load(open(STATE_PATH, encoding="utf-8"))
|
||||
except Exception:
|
||||
st = {}
|
||||
out = []
|
||||
for r in rows:
|
||||
s = st.get(r["token"][-12:], {})
|
||||
out.append({"email": r.get("email", ""), "token": r["token"],
|
||||
"dead_until": s.get("dead_until", 0), "credits": s.get("credits"),
|
||||
"fail": s.get("fail", 0)})
|
||||
TOKENS = out
|
||||
log("tokens loaded: %d alive / %d" % (sum(1 for t in TOKENS if t["dead_until"] < time.time()), len(TOKENS)))
|
||||
|
||||
|
||||
def save_state():
|
||||
st = {}
|
||||
for t in TOKENS:
|
||||
st[t["token"][-12:]] = {"dead_until": t["dead_until"], "credits": t["credits"], "fail": t["fail"]}
|
||||
try:
|
||||
tmp = STATE_PATH + ".tmp"
|
||||
json.dump(st, open(tmp, "w", encoding="utf-8"))
|
||||
os.replace(tmp, STATE_PATH)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def hdrs(token):
|
||||
return {"Authorization": "Bearer " + token, "Content-Type": "application/json",
|
||||
"Origin": "https://minara.ai", "Referer": "https://minara.ai/", "User-Agent": UA}
|
||||
|
||||
|
||||
def pick(n=8):
|
||||
"""Round-robin over live tokens; returns list of candidates."""
|
||||
now = time.time()
|
||||
with LOCK:
|
||||
live = [t for t in TOKENS if t["dead_until"] < now]
|
||||
if not live:
|
||||
return []
|
||||
start = RR[0] % len(live)
|
||||
RR[0] += 1
|
||||
live = live[start:] + live[:start]
|
||||
return live[:n]
|
||||
|
||||
|
||||
def mark_dead(t, code, body=""):
|
||||
with LOCK:
|
||||
t["fail"] = t.get("fail", 0) + 1
|
||||
if code in (401, 402, 403) or "insufficient" in (body or "").lower() or "quota" in (body or "").lower():
|
||||
t["dead_until"] = time.time() + DEAD_TTL
|
||||
t["credits"] = 0
|
||||
log("dead %s code=%s" % (t["email"], code))
|
||||
save_state()
|
||||
|
||||
|
||||
def _ids():
|
||||
d = MODELS_CACHE["data"] or {}
|
||||
if isinstance(d, dict):
|
||||
d = d.get("data") or []
|
||||
return [m.get("id") for m in d if isinstance(m, dict)]
|
||||
|
||||
|
||||
def ensure_models():
|
||||
if MODELS_CACHE["data"] and time.time() - MODELS_CACHE["ts"] < 600:
|
||||
return True
|
||||
for t in pick(3):
|
||||
try:
|
||||
r = requests.get(UP + "/v1/models", headers=hdrs(t["token"]), timeout=30)
|
||||
if r.status_code == 200:
|
||||
MODELS_CACHE["data"] = r.json()
|
||||
MODELS_CACHE["ts"] = time.time()
|
||||
return True
|
||||
mark_dead(t, r.status_code, r.text[:200])
|
||||
except Exception as e:
|
||||
mark_dead(t, 0, str(e))
|
||||
return False
|
||||
|
||||
|
||||
def map_model(name):
|
||||
"""Accept both 'anthropic/claude-opus-5.5' and 'claude-opus-5.5'."""
|
||||
ids = _ids()
|
||||
if name in ids:
|
||||
return name
|
||||
low = name.lower()
|
||||
for i in ids:
|
||||
if i.lower() == low:
|
||||
return i
|
||||
for i in ids:
|
||||
if i.lower().split("/")[-1] == low:
|
||||
return i
|
||||
short = low.replace("-", ".")
|
||||
for i in ids:
|
||||
tail = i.lower().split("/")[-1].replace("-", ".")
|
||||
if tail == short:
|
||||
return i
|
||||
return name
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def sendj(self, code, obj):
|
||||
b = json.dumps(obj, ensure_ascii=False).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(b)))
|
||||
self.end_headers()
|
||||
self.wfile.write(b)
|
||||
|
||||
def err(self, code, msg):
|
||||
self.sendj(code, {"error": {"message": msg, "type": "upstream_error", "code": code}})
|
||||
|
||||
def do_GET(self):
|
||||
p = self.path.split("?")[0]
|
||||
if p in ("/health", "/"):
|
||||
now = time.time()
|
||||
alive = [t for t in TOKENS if t["dead_until"] < now]
|
||||
return self.sendj(200, {"ok": True, "tokens": len(TOKENS), "alive": len(alive),
|
||||
"credits": round(sum(t["credits"] or 0 for t in alive), 2)})
|
||||
if p == "/pool":
|
||||
return self.sendj(200, {"tokens": TOKENS})
|
||||
if p.endswith("/models"):
|
||||
if MODELS_CACHE["data"] and time.time() - MODELS_CACHE["ts"] < 600:
|
||||
return self.sendj(200, MODELS_CACHE["data"])
|
||||
for t in pick(5):
|
||||
try:
|
||||
r = requests.get(UP + "/v1/models", headers=hdrs(t["token"]), timeout=30)
|
||||
if r.status_code == 200:
|
||||
MODELS_CACHE["data"] = r.json()
|
||||
MODELS_CACHE["ts"] = time.time()
|
||||
return self.sendj(200, MODELS_CACHE["data"])
|
||||
mark_dead(t, r.status_code, r.text[:200])
|
||||
except Exception as e:
|
||||
mark_dead(t, 0, str(e))
|
||||
if MODELS_CACHE["data"]:
|
||||
return self.sendj(200, MODELS_CACHE["data"])
|
||||
return self.err(503, "no live tokens")
|
||||
return self.err(404, "not found")
|
||||
|
||||
def do_POST(self):
|
||||
p = self.path.split("?")[0]
|
||||
if not p.endswith("/chat/completions"):
|
||||
return self.err(404, "not found")
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(n) if n else b"{}"
|
||||
try:
|
||||
body = json.loads(raw or b"{}")
|
||||
except Exception:
|
||||
return self.err(400, "bad json")
|
||||
ensure_models()
|
||||
body["model"] = map_model(body.get("model") or "")
|
||||
stream = bool(body.get("stream"))
|
||||
last = None
|
||||
for t in pick(8):
|
||||
try:
|
||||
r = requests.post(UP + "/v1/chat/completions", headers=hdrs(t["token"]),
|
||||
json=body, timeout=600, stream=stream)
|
||||
except Exception as e:
|
||||
mark_dead(t, 0, str(e))
|
||||
last = str(e)
|
||||
continue
|
||||
if r.status_code != 200:
|
||||
txt = r.text[:300]
|
||||
mark_dead(t, r.status_code, txt)
|
||||
last = txt
|
||||
continue
|
||||
if stream:
|
||||
self.send_response(200)
|
||||
self.send_header("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
|
||||
data = r.content
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
self.err(503, "all tokens failed: %s" % (last or "")[:200])
|
||||
|
||||
|
||||
def reloader():
|
||||
while True:
|
||||
time.sleep(60)
|
||||
try:
|
||||
if os.path.exists(TOKENS_PATH):
|
||||
m = os.path.getmtime(TOKENS_PATH)
|
||||
if m > reloader.last:
|
||||
reloader.last = m
|
||||
load_tokens()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
reloader.last = 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
load_tokens()
|
||||
threading.Thread(target=reloader, daemon=True).start()
|
||||
log("minara shim on :%d" % PORT)
|
||||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Push new minara tokens from local bank.jsonl to prod shim and reload it.
|
||||
|
||||
Dedupe by token suffix; appends only new lines; restarts shim if anything changed.
|
||||
"""
|
||||
import json, os, subprocess, sys
|
||||
|
||||
HERE = os.environ.get("MINARA_HOME") or os.path.dirname(os.path.abspath(__file__))
|
||||
BANK = HERE + "/bank.jsonl"
|
||||
PROD = os.environ.get("MINARA_PROD", "root@127.0.0.1")
|
||||
REMOTE = "/opt/minara-shim/tokens.jsonl"
|
||||
|
||||
|
||||
def sh(args, inp=None):
|
||||
p = subprocess.run(args, input=inp, capture_output=True, text=True, timeout=120)
|
||||
return p.returncode, p.stdout.strip(), p.stderr.strip()[:200]
|
||||
|
||||
|
||||
def main():
|
||||
rows = []
|
||||
if os.path.exists(BANK):
|
||||
for l in open(BANK, encoding="utf8"):
|
||||
l = l.strip()
|
||||
if not l:
|
||||
continue
|
||||
try:
|
||||
r = json.loads(l)
|
||||
except Exception:
|
||||
continue
|
||||
if r.get("ok") and r.get("token"):
|
||||
rows.append({"email": r["email"], "token": r["token"]})
|
||||
if not rows:
|
||||
print("bank empty")
|
||||
return
|
||||
rc, out, err = sh(["ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no", PROD,
|
||||
"cut -c1-0 %s >/dev/null; python3 - <<'PY'\nimport json\nseen=set()\nfor l in open('%s'):\n try: seen.add(json.loads(l)['token'])\n except Exception: pass\nprint(len(seen))\nPY" % (REMOTE, REMOTE)])
|
||||
try:
|
||||
remote_n = int(out.split("\n")[-1])
|
||||
except Exception:
|
||||
remote_n = -1
|
||||
# append whole deduped set (shim dedupes nothing, so rebuild list and replace)
|
||||
uniq, seen = [], set()
|
||||
for r in rows:
|
||||
if r["token"] in seen:
|
||||
continue
|
||||
seen.add(r["token"])
|
||||
uniq.append(r)
|
||||
payload = "\n".join(json.dumps(r, ensure_ascii=False) for r in uniq) + "\n"
|
||||
rc, out, err = sh(["ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no", PROD,
|
||||
"cat > %s && systemctl restart minara-shim && sleep 2 && curl -s -m 10 http://127.0.0.1:48140/health" % REMOTE],
|
||||
inp=payload)
|
||||
print("local=%d remote_before=%s rc=%d %s %s" % (len(uniq), remote_n, rc, out[:200], err))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user