Files

278 lines
9.6 KiB
Python

#!/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()