From 8285b2f4cfd8ce7890c708c135204dcaddd34445 Mon Sep 17 00:00:00 2001 From: vlad Date: Fri, 30 Oct 2026 20:21:48 +0000 Subject: [PATCH] context.dev autoreg: agent claim flow, chrome CDP signup, bank shim --- .gitignore | 12 ++ README.md | 99 +++++++++++++ chrome_up.py | 34 +++++ ctx_farm2.py | 351 +++++++++++++++++++++++++++++++++++++++++++++++ ctx_shim.py | 186 +++++++++++++++++++++++++ ctx_wave.py | 36 +++++ requirements.txt | 3 + verify_keys.py | 35 +++++ 8 files changed, 756 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100755 chrome_up.py create mode 100755 ctx_farm2.py create mode 100755 ctx_shim.py create mode 100755 ctx_wave.py create mode 100644 requirements.txt create mode 100755 verify_keys.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..439880a --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +gmail_env.json +2cap_key.txt +bank.jsonl +bank2.jsonl +acct_ctx*.json +apikeys.json +chrome_prof*/ +js/ +js2/ +*.session +__pycache__/ +*.pyc \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..5ef1557 --- /dev/null +++ b/README.md @@ -0,0 +1,99 @@ +# contextdev-autoreg + +Автоматическая регистрация аккаунтов [context.dev](https://www.context.dev/) через +агентский claim-флоу и сбор API-ключей `ctxt_secret_*` в банк для локального шлюза. + +Промо-код `SPOOKY10K` (10 000 кредитов на новый аккаунт) в этой сборке **мёртв** — +платформа закрыла его и массово отключила ключи фермы. Репозиторий оставлен как +рабочая механика флоу: полезен, когда появляется новый промокод/оффер. + +## Что делает + +1. `POST https://www.context.dev/agent/identity` (`type=service_auth`) — создаёт + registration и отдаёт `claim_token` + `user_code` (6 цифр) + `verification_uri`. +2. Реальный Chrome по CDP открывает `verification_uri`, закрывает cookie-баннер, + заполняет форму (full name / work email / password) и проходит Firebase App Check + + reCAPTCHA Enterprise. +3. Ветка Firebase: `accounts:signUp` → `/api/auth/ensure-user` → `/api/login`. +4. `user_code` подтверждает claim (`/api/agent/claim/confirm`), затем письмо из Gmail + по IMAP даёт ссылку подтверждения email. +5. Редим промокода через tRPC: `organization.redeemCreditPackage`, `organization_id` + берётся из URL `/o/`. +6. API-ключ и метаданные аккаунта пишутся в `bank.jsonl`. + +## Почему нужен именно настоящий Chrome + +Firebase App Check проверяет attestation. Camoufox и токены 2captcha дают +`403 App attestation failed` на `exchangeRecaptchaEnterpriseToken`. Проходит только +реальный Chrome (`--remote-debugging-port`), подключённый Playwright'ом через +`connect_over_cdp`. С датацентр-IP reCAPTCHA обычно отбивает (`recaptcha rejected`), +нужен residential/мобильный egress. + +## Файлы + +| Файл | Назначение | +|------|------------| +| `chrome_up.py` | поднимает Chrome с CDP-портом и прокси (`CTX_CDP_PORT`, `CTX_CHROME_PROF`, `CTX_CHROME_PROXY`) | +| `ctx_farm2.py` | воркер одного аккаунта: identity → браузер → код → email → claim → редим → ключ | +| `ctx_wave.py` | волна: батчи по `CTX_BATCH`, пауза `CTX_PAUSE`, опциональная ротация egress | +| `ctx_shim.py` | локальный OpenAI-независимый шлюз `:8913` (`/search /scrape /map /answers /status`) с ротацией ключей | +| `verify_keys.py` | проверка банка через `GET /v1/org/logs` → `credits_remaining` | + +## Установка + +```bash +pip install -r requirements.txt +``` + +`gmail_env.json` в рабочем каталоге: + +```json +{"gm": "you@gmail.com", "gp": "app-password"} +``` + +Плюс-алиасы (`you+ctx450@gmail.com`) читаются тем же ящиком. + +## Запуск + +```bash +# 1. Chrome с CDP и прокси +CTX_CDP_PORT=9225 CTX_CHROME_PROF=chrome_prof \ +CTX_CHROME_PROXY=http://127.0.0.1:8899 python chrome_up.py + +# 2. Волна на 30 аккаунтов +CTX_CDP=http://127.0.0.1:9225 CTX_CDP_PORT=9225 \ +CTX_CHROME_PROXY=http://127.0.0.1:8899 CTX_PROXY=http://127.0.0.1:8899 \ +CTX_ID_PROXIES="http://127.0.0.1:8899" CTX_BANK=bank.jsonl \ +CTX_PAUSE=75 CTX_BATCH=2 CTX_ROTATE=0 python ctx_wave.py 460 30 + +# 3. Шлюз +python ctx_shim.py --port 8913 --bank bank.jsonl + +# 4. Проверка банка +python verify_keys.py +``` + +## Переменные окружения + +`CTX_CDP`, `CTX_CDP_PORT`, `CTX_CHROME_PROF`, `CTX_CHROME_PROXY`, `CTX_PROXY`, +`CTX_ID_PROXIES` (пул для шага identity, через запятую), `CTX_BANK`, `CTX_PAUSE`, +`CTX_BATCH`, `CTX_ROTATE`. + +## Гейты, на которые упирается флоу + +- **Cloudflare по egress.** После серии регистраций IP получает `403` на весь домен, + включая главную. Лечится сменой IP (мобильный PPP), не заголовками: `curl`, + `requests`, `curl_cffi` получают одинаковый `403`. +- **reCAPTCHA Enterprise на датацентр-IP.** `recaptcha rejected` при заполненной форме. +- **Промокод одноразовый на организацию.** Повторный редим → `400 That credit code is + invalid, expired, or unavailable` или `403 You cannot redeem credits for this + organization`. +- **Флаг антифрода.** `Your account has been flagged for manual review` — аккаунт + живёт, но редим закрыт. +- **Отзыв кредитов и отключение ключей.** Итог этой сборки: 16 аккаунтов, ~15 000 + кредитов, затем все ключи → `401 Your API key is disabled`, баланс `0`. + +## Статус + +Механика отработана, промо закрыто. Цифры последнего прогона: 16 аккаунтов с ключами, +пик 15 000 кредитов, через несколько часов — `0` живых ключей. \ No newline at end of file diff --git a/chrome_up.py b/chrome_up.py new file mode 100755 index 0000000..657510a --- /dev/null +++ b/chrome_up.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +"""Launch real Chrome with CDP on 9223 (detached) for context.dev flow.""" +import os, subprocess, time, json, urllib.request + +CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe" +PROF = os.environ.get("CTX_CHROME_PROF", r"C:\Users\User\tmp\ctxdev\chrome_prof") +PORT = int(os.environ.get("CTX_CDP_PORT", "9223")) +PROXY = os.environ.get("CTX_CHROME_PROXY", "") +os.makedirs(PROF, exist_ok=True) + +def 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: + return None + +if not up(): + args = [CHROME, "--remote-debugging-port=%d" % PORT, "--user-data-dir=" + PROF, + "--no-first-run", "--no-default-browser-check", + "--disable-blink-features=AutomationControlled", + "--window-size=1280,900"] + if PROXY: + args.append("--proxy-server=" + PROXY) + args.append("--proxy-bypass-list=<-loopback>") + args.append("about:blank") + subprocess.Popen(args, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True) + for _ in range(25): + time.sleep(1) + if up(): + break +v = up() +print("CDP:", "up" if v else "DOWN", (v or {}).get("Browser", "")) \ No newline at end of file diff --git a/ctx_farm2.py b/ctx_farm2.py new file mode 100755 index 0000000..8f06752 --- /dev/null +++ b/ctx_farm2.py @@ -0,0 +1,351 @@ +#!/usr/bin/env python +"""Context.dev farm v2: robust chrome lifecycle + tRPC redeem + email verify retries. + +Usage: ctx_farm2.py +""" +import json, os, sys, time, re, random, string, subprocess, imaplib, email +import requests +from playwright.sync_api import sync_playwright + +BASE = os.path.dirname(os.path.abspath(__file__)) +START, COUNT = int(sys.argv[1]), int(sys.argv[2]) +PROMO = "SPOOKY10K" +CDP = os.environ.get("CTX_CDP", "http://127.0.0.1:9223") +PROXY_URL = os.environ.get("CTX_PROXY", "") +PXY = {"http": PROXY_URL, "https": PROXY_URL} if PROXY_URL else None +ID_PROXIES = [p for p in os.environ.get("CTX_ID_PROXIES", "").split(",") if p.strip()] + + +def id_pxy(): + """identity runs on a rotating pool (datacenter IPv6 is fine - no captcha there).""" + if ID_PROXIES: + p = random.choice(ID_PROXIES).strip() + return {"http": p, "https": p} + return PXY +NAMES = ["Nikita Refor", "Alex Grobman", "Dan Vorobets", "Max Koval", "Yuri Larin", "Oleg Sydor", "Kirill Bolt"] +G = json.load(open(r"gmail_env.json")) + + +def log(*a): + print(*a, flush=True) + + +def cdp_ok(): + try: + return requests.get(CDP + "/json/version", timeout=3).status_code == 200 + except Exception: + return False + + +def ensure_chrome(): + if cdp_ok(): + return True + subprocess.run([sys.executable, os.path.join(BASE, "chrome_up.py")], check=False) + for _ in range(20): + if cdp_ok(): + return True + time.sleep(1) + return False + + +def identity(mail, tag): + r = requests.post("https://www.context.dev/agent/identity", json={ + "type": "service_auth", "login_hint": mail, + "api_key_name": "hermes-%s" % tag, "client_name": "Hermes"}, timeout=60, proxies=id_pxy()) + try: + return r.status_code, r.json() + except Exception: + return r.status_code, {} + + +def txt(pg, n=260): + try: + return re.sub(r"\s+", " ", pg.inner_text("body"))[:n] + except Exception: + return "" + + +def click_btn(pg, rx, exact_first=True): + js = """(() => {const bs=[...document.querySelectorAll('button')]; + let x=bs.find(e=>new RegExp(%s,'i').test(e.innerText||'')); + if(!x) return null; const r=x.getBoundingClientRect(); + return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2,t:(x.innerText||'').trim()})})()""" % json.dumps(rx) + b = pg.evaluate(js) + if not b: + return False + c = json.loads(b) + try: + pg.mouse.move(c["x"], c["y"], steps=8); time.sleep(0.2) + pg.mouse.click(c["x"], c["y"]) + except Exception: + pg.evaluate("""(() => {const bs=[...document.querySelectorAll('button')]; + const x=bs.find(e=>new RegExp(%s,'i').test(e.innerText||'')); if(x)x.click();})()""" % json.dumps(rx)) + return True + + +def go(pg, url, **kw): + """goto with retries - the mobile egress drops TLS now and then.""" + kw.setdefault("timeout", 90000) + kw.setdefault("wait_until", "domcontentloaded") + last = None + for i in range(4): + try: + return pg.goto(url, **kw) + except Exception as e: + last = e + log(" goto retry %d: %s" % (i + 1, str(e)[:70])) + time.sleep(5) + if pg.is_closed(): + raise + raise last + + +def find_code_input(pg): + return pg.evaluate("""(() => {const els=[...document.querySelectorAll('input')].filter(e=>e.offsetWidth||e.offsetHeight); + let c=els.find(e=>/code|otp|verif/i.test((e.id||'')+(e.name||'')+(e.placeholder||'')+(e.getAttribute('aria-label')||''))); + if(!c && els.length===1 && els[0].maxLength>3 && els[0].maxLength<=8) c=els[0]; + if(!c) return null; c.focus(); return c.id||'x'})()""") + + +def clear_session(pg): + # keep Google/reCAPTCHA cookies (they carry trust score), drop only app session + try: + for c in pg.context.cookies(): + if str(c.get("name", "")).startswith("BrandDev"): + pg.context.clear_cookies(name=c["name"]) + except Exception: + pass + try: + pg.evaluate("""async ()=>{try{localStorage.clear();sessionStorage.clear()}catch(e){} + try{const dbs=await indexedDB.databases();for(const d of dbs){if(/firebase/i.test(d.name||'')){try{indexedDB.deleteDatabase(d.name)}catch(e){}}}}catch(e){}}""") + except Exception: + pass + + +def get_verify_link(alias, timeout=200, not_before=0): + t0 = time.time() + while time.time() - t0 < timeout: + try: + m = imaplib.IMAP4_SSL("imap.gmail.com") + m.login(G["gm"], G["gp"].strip()) + m.select("INBOX") + typ, data = m.search(None, "ALL") + for i in reversed(data[0].split()[-15:]): + typ, d = m.fetch(i, "(RFC822)") + msg = email.message_from_bytes(d[0][1]) + if alias.lower() not in msg.get("To", "").lower(): + continue + subj = str(email.header.make_header(email.header.decode_header(msg.get("Subject", "")))) + if "Verify your email" not in subj: + continue + body = "" + for part in msg.walk(): + if part.get_content_type() in ("text/plain", "text/html"): + try: + body += part.get_payload(decode=True).decode(part.get_content_charset() or "utf-8", "replace") + except Exception: + pass + ls = re.findall(r"https://www\.context\.dev/verify-email\?[^\s\"'<>]+", body) + if ls: + m.logout() + return ls[0].replace("&", "&") + m.logout() + except Exception as e: + log(" imap:", str(e)[:70]) + time.sleep(10) + return "" + + +def api_credits(key): + try: + r = requests.get("https://api.context.dev/v1/org/logs", + headers={"Authorization": "Bearer " + key}, timeout=60) + return r.json().get("key_metadata", {}).get("credits_remaining") + except Exception: + return None + + +def redeem_trpc(pg, promo, org_hint=None): + """Redeem via tRPC (needs organization_id + code).""" + js = """async ([code, org]) => { + if (!org) { + try { + const r0 = await fetch('/api/trpc/organization.get?batch=1&input=' + encodeURIComponent(JSON.stringify({"0":{"json":null}}))); + const t0 = await r0.text(); + const m = t0.match(/"id"\\s*:\\s*"([0-9a-f-]{36})"/); + if (m) org = m[1]; + } catch(e) {} + } + const body = {"0":{"json":{"code":code,"organization_id":org}}}; + const r = await fetch('/api/trpc/organization.redeemCreditPackage?batch=1', { + method:'POST', headers:{'content-type':'application/json'}, body: JSON.stringify(body)}); + const t = await r.text(); + return JSON.stringify({org:org, status:r.status, body:t.slice(0,400)}); + }""" + try: + out = pg.evaluate(js, [promo, org_hint]) + log(" redeem api:", str(out)[:280]) + if '"credits_added"' in str(out): + return True + except Exception as e: + log(" redeem err:", str(e)[:100]) + return False + + +def run_one(pg, mail, tag): + code, ident = identity(mail, tag) + log("[%s] identity %s" % (tag, code)) + if code != 200 or "claim" not in ident: + log(" fail:", json.dumps(ident)[:200]) + return None + vuri, ucode, ct = ident["claim"]["verification_uri"], ident["claim"]["user_code"], ident["claim_token"] + pw = "Kq7" + "".join(random.choice(string.ascii_letters + string.digits) for _ in range(9)) + "!2" + json.dump({"email": mail, "tag": tag, "pw": pw, "claim_token": ct, "vuri": vuri, "user_code": ucode, + "offer": ident.get("offer"), "created": time.time()}, + open(os.path.join(BASE, "acct_%s.json" % tag), "w"), indent=1) + log(" VURI", vuri) + log(" CODE", ucode) + + go(pg, "https://www.context.dev/claim", wait_until="domcontentloaded", timeout=90000) + time.sleep(3) + clear_session(pg) + go(pg, vuri, wait_until="domcontentloaded", timeout=90000) + time.sleep(7) + t = txt(pg, 200) + log(" page:", t[:100]) + if "We use cookies" in t or "cookie" in t[:90].lower(): + for rx in (r"^accept", r"^reject", r"^continue", r"^got it", r"^allow", r"^ok"): + if click_btn(pg, rx): + log(" consent:", rx) + break + time.sleep(3) + t = txt(pg, 220) + log(" page2:", t[:90]) + + if "Full name" in t or "Create account" in t: + need = pg.evaluate("""(() => {const e=document.querySelector('input[name=username]')||document.querySelector('input[type=email]'); + if(!e) return 'none'; if(e.value && e.value.trim()) return 'ok'; e.readOnly=false; e.focus(); return 'need'})()""") + if need == "need": + pg.keyboard.type(mail, delay=45); time.sleep(0.7) + pg.evaluate("""(() => {const e=document.querySelector('input[name=username]')||document.querySelector('input[type=email]'); + if(e && e.value !== %s){const s=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; s.call(e,%s); e.dispatchEvent(new Event('input',{bubbles:true}))}})()""" % (json.dumps(mail), json.dumps(mail))) + log(" email field:", need) + pg.focus("#name"); pg.keyboard.type(random.choice(NAMES), delay=55) + pg.focus("#password"); pg.keyboard.type(pw, delay=55) + pg.evaluate("(()=>{const c=document.querySelector('input[type=checkbox]'); if(!c.checked)c.click()})()") + time.sleep(4) + if not click_btn(pg, r"^create account"): + log(" no signup button") + return None + for _ in range(35): + time.sleep(4) + t = txt(pg, 220) + if "Confirm agent setup" in t or "Setup code" in t: + break + if "couldn't verify" in t or "Security check failed" in t: + log(" recaptcha rejected") + return None + if "Confirm agent setup" not in t and "Setup code" not in t: + log(" no code screen:", t[:130]) + return None + elif "Confirm agent setup" not in t: + log(" unexpected page") + return None + + if find_code_input(pg): + pg.keyboard.type(ucode, delay=90); time.sleep(1) + click_btn(pg, r"confirm setup|^confirm$|continue") + time.sleep(7) + log(" after code:", txt(pg, 130)[:110]) + + # verify email + if "Check your inbox" in txt(pg, 260) or "verification link" in txt(pg, 260): + link = get_verify_link(mail) + if not link: + log(" NO link") + return None + go(pg, link, wait_until="domcontentloaded", timeout=90000); time.sleep(5) + click_btn(pg, r"verify email address|verify email") + time.sleep(9) + go(pg, vuri, wait_until="domcontentloaded", timeout=90000); time.sleep(5) + t = txt(pg, 220) + if "I've verified my email" in t: + click_btn(pg, r"verified my email"); time.sleep(8) + elif find_code_input(pg): + pg.keyboard.type(ucode, delay=90); time.sleep(1) + click_btn(pg, r"confirm setup|^confirm$|continue"); time.sleep(7) + log(" post-verify:", txt(pg, 140)[:110]) + + # redeem + org = None + m = re.search(r"/o/([0-9a-f-]{36})", pg.url) + if m: + org = m.group(1) + go(pg, "https://www.context.dev/dashboard/redeem-credits", wait_until="domcontentloaded", timeout=60000) + time.sleep(6) + if "Check your inbox" in txt(pg, 300): + log(" redeem blocked: email not verified") + else: + redeem_trpc(pg, PROMO, org) + time.sleep(3) + + r = requests.post("https://www.context.dev/oauth2/token", + data={"grant_type": "urn:workos:agent-auth:grant-type:claim", "claim_token": ct}, timeout=60, proxies=PXY) + d = r.json() if r.headers.get("content-type", "").startswith("application/json") else {} + if "access_token" not in d: + log(" TOKEN FAIL", r.status_code, json.dumps(d)[:150]) + return None + key = d["access_token"] + cr = api_credits(key) + entry = {"email": mail, "tag": tag, "key": key, "ts": time.time(), + "gift": d.get("signup_gift_credits"), "credits": cr} + with open(os.path.join(BASE, os.environ.get("CTX_BANK", "bank.jsonl")), "a") as f: + f.write(json.dumps(entry) + "\n") + log(" KEY OK len %d gift=%s credits=%s" % (len(key), d.get("signup_gift_credits"), cr)) + return entry + + +def main(): + ok = 0 + for idx in range(START, START + COUNT): + mail, tag = "baradok609+ctx%d@gmail.com" % idx, "ctx%d" % idx + log("\n=== %s ===" % mail) + if not ensure_chrome(): + log(" chrome down"); continue + try: + with sync_playwright() as p: + br = p.chromium.connect_over_cdp(CDP) + ctx = br.contexts[0] + pg = ctx.new_page() + e = None + for attempt in range(3): + try: + if pg.is_closed(): + pg = ctx.new_page() + e = run_one(pg, mail, tag) + except Exception as ex: + log(" exc:", str(ex)[:120]) + e = None + try: + pg = ctx.new_page() + except Exception: + pass + if e: + break + log(" retry %d/3 in 25s" % (attempt + 1)) + time.sleep(25) + log("RESULT", "OK" if e else "FAIL") + if e: + ok += 1 + try: + pg.close() + except Exception: + pass + br.close() + except Exception as ex: + print("EXC", str(ex)[:200], flush=True) + time.sleep(int(os.environ.get("CTX_PAUSE", "6"))) + log("\nTOTAL OK %d / %d" % (ok, COUNT)) + + +main() \ No newline at end of file diff --git a/ctx_shim.py b/ctx_shim.py new file mode 100755 index 0000000..2cff0e3 --- /dev/null +++ b/ctx_shim.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python +"""ctx_shim.py — local Context.dev gateway with API-key rotation. + +Endpoints: + GET /search?q=&num= -> context.dev /v1/web/search + POST /scrape {"url": "...", "formats": {...}} -> /v1/web/scrape + GET /answers?task=<...> -> /v1/web/answers (fast) + GET /map?domain=stripe.com -> /v1/web/urls + GET /status -> key pool state + credits +Keys are reloaded from bank.jsonl on every 30 s; dead keys are parked. +""" +import json, os, threading, time, urllib.parse, urllib.request, urllib.error +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +BASE = os.path.dirname(os.path.abspath(__file__)) +BANK = os.path.join(BASE, "bank.jsonl") +API = "https://api.context.dev/v1" +PORT = int(os.environ.get("CTX_SHIM_PORT", "8891")) + +lock = threading.Lock() +keys = [] # list of dicts {email, key, credits, dead} +last_load = 0.0 + + +def load_keys(): + global keys, last_load + if time.time() - last_load < 30 and keys: + return + with lock: + if time.time() - last_load < 30 and keys: + return + seen, out = set(), [] + try: + for line in open(BANK): + line = line.strip() + if not line: + continue + d = json.loads(line) + k = d.get("key") + if not k or k in seen: + continue + seen.add(k) + out.append({"email": d.get("email"), "key": k, + "credits": d.get("credits"), "dead": False}) + except FileNotFoundError: + pass + old = {x["key"]: x for x in keys} + for x in out: + if x["key"] in old: + x["credits"] = old[x["key"]]["credits"] + x["dead"] = old[x["key"]]["dead"] + keys = out + last_load = time.time() + + +def pick(): + load_keys() + with lock: + live = [k for k in keys if not k["dead"]] + if not live: + return None + live.sort(key=lambda x: (x["credits"] if isinstance(x["credits"], int) else 0), reverse=True) + return live[0] + + +def call(method, path, payload=None, key=None, timeout=60): + data = json.dumps(payload).encode() if payload is not None else None + req = urllib.request.Request(API + path, data=data, method=method, + headers={"Authorization": "Bearer " + key, + "Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + body = r.read().decode("utf-8", "replace") + return r.status, body, dict(r.headers) + except urllib.error.HTTPError as e: + return e.code, e.read().decode("utf-8", "replace"), dict(e.headers) + except Exception as e: + return 0, json.dumps({"error": str(e)}), {} + + +def do_call(method, path, payload=None): + """Try keys until one works; park dead ones.""" + load_keys() + with lock: + cands = [k for k in keys if not k["dead"]] + if not cands: + return 503, {"error": "no live keys"} + cands.sort(key=lambda x: (x["credits"] if isinstance(x["credits"], int) else 0), reverse=True) + last = (0, "{}") + for k in cands[:12]: + st, body, hd = call(method, path, payload, k["key"]) + if st == 429: + # free plan allows 2 concurrent per key: rotate to the next key, do not park + last = (429, body) + continue + if st in (401, 402, 403): + with lock: + k["dead"] = True + last = (st, body) + continue + # refresh credits from metadata if present + try: + j = json.loads(body) + cr = j.get("key_metadata", {}).get("credits_remaining") + if isinstance(cr, int): + with lock: + k["credits"] = cr + except Exception: + pass + return st, body + return last[0] or 502, last[1] + + +class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def _send(self, code, obj): + raw = obj if isinstance(obj, str) else json.dumps(obj, ensure_ascii=False) + b = raw.encode() + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def log_message(self, *a): + pass + + def do_GET(self): + u = urllib.parse.urlparse(self.path) + q = urllib.parse.parse_qs(u.query) + if u.path == "/status": + load_keys() + with lock: + return self._send(200, {"keys": len(keys), "live": sum(1 for k in keys if not k["dead"]), + "credits_total": sum(k["credits"] for k in keys if isinstance(k["credits"], int)), + "details": [{"email": k["email"], "credits": k["credits"], "dead": k["dead"]} for k in keys]}) + if u.path == "/search": + qs = q.get("q", [""])[0] + num = int(q.get("num", ["10"])[0]) + if not qs: + return self._send(400, {"error": "q required"}) + payload = {"query": qs, "numResults": num} + if q.get("markdown", ["0"])[0] == "1": + payload["markdown"] = True + if q.get("fresh", ["0"])[0] == "1": + payload["maxAgeMs"] = 0 + st, body = do_call("POST", "/web/search", payload) + return self._send(st if st else 502, body) + if u.path == "/map": + dom = q.get("domain", [""])[0] + if not dom: + return self._send(400, {"error": "domain required"}) + st, body = do_call("GET", "/web/urls?domain=" + urllib.parse.quote(dom)) + return self._send(st if st else 502, body) + if u.path == "/answers": + task = q.get("task", [""])[0] + if not task: + return self._send(400, {"error": "task required"}) + st, body = do_call("POST", "/web/answers", {"task": task, "mode": "fast"}) + return self._send(st if st else 502, body) + return self._send(404, {"error": "unknown path", "paths": ["/search", "/scrape", "/map", "/answers", "/status"]}) + + def do_POST(self): + u = urllib.parse.urlparse(self.path) + n = int(self.headers.get("Content-Length") or 0) + try: + payload = json.loads(self.rfile.read(n) or b"{}") + except Exception: + return self._send(400, {"error": "bad json"}) + if u.path == "/scrape": + url = payload.get("url") + if not url: + return self._send(400, {"error": "url required"}) + body = {"url": url, "formats": payload.get("formats") or {"markdown": True}} + if payload.get("mainContentOnly") is not None: + body["sharedParams"] = {"mainContentOnly": payload["mainContentOnly"]} + st, resp = do_call("POST", "/web/scrape", body) + return self._send(st if st else 502, resp) + return self._send(404, {"error": "unknown path"}) + + +if __name__ == "__main__": + load_keys() + print("ctx shim on :%d, keys=%d" % (PORT, len(keys)), flush=True) + ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever() \ No newline at end of file diff --git a/ctx_wave.py b/ctx_wave.py new file mode 100755 index 0000000..5d1b7e5 --- /dev/null +++ b/ctx_wave.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +"""ctx_wave.py — run the farm in batches, rotating the ZTE mobile IP between batches. + +Requires env for ctx_farm2: CTX_CDP, CTX_CDP_PORT, CTX_CHROME_PROF, CTX_CHROME_PROXY, CTX_PROXY, CTX_ID_PROXIES, CTX_BANK. +""" +import os, subprocess, sys, time +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +os.environ["PYTHONIOENCODING"] = "utf-8" + +BASE = os.path.dirname(os.path.abspath(__file__)) +PY = sys.executable +START, TOTAL = int(sys.argv[1]), int(sys.argv[2]) +BATCH = int(os.environ.get("CTX_BATCH", "4")) +ROTATE = os.environ.get("CTX_ROTATE", "1") == "1" +idx = START +done = 0 +while idx < START + TOTAL: + n = min(BATCH, START + TOTAL - idx) + print("\n######## WAVE %d..%d ########" % (idx, idx + n - 1), flush=True) + env = dict(os.environ) + try: + subprocess.run([PY, os.path.join(BASE, "ctx_farm2.py"), str(idx), str(n)], + cwd=BASE, env=env, timeout=3600) + except Exception as e: + print("wave err", str(e)[:150], flush=True) + idx += n + done += n + if ROTATE and idx < START + TOTAL: + try: + sys.path.insert(0, r"regfarm") + import newapi_lib as L + print("zte_rotate:", L.zte_rotate(max_wait=150), flush=True) + except Exception as e: + print("rotate err:", type(e).__name__, str(e)[:120], flush=True) + time.sleep(20) +print("\nWAVE DONE %d accounts requested" % done, flush=True) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..8108073 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +playwright>=1.40 +requests>=2.31 +httpx>=0.27 \ No newline at end of file diff --git a/verify_keys.py b/verify_keys.py new file mode 100755 index 0000000..9ec6a4d --- /dev/null +++ b/verify_keys.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python +"""Verify every ctx key: live + credits. Rewrites bank.jsonl with fresh credits/dead flags.""" +import json, os, time, requests + +BASE = os.path.dirname(os.path.abspath(__file__)) +BANK = os.path.join(BASE, "bank.jsonl") +rows = [json.loads(l) for l in open(BANK) if l.strip()] +seen, out = set(), [] +total = 0 +for r in rows: + k = r.get("key") + if not k or k in seen: + continue + seen.add(k) + try: + x = requests.get("https://api.context.dev/v1/org/logs", + headers={"Authorization": "Bearer " + k}, timeout=45) + if x.status_code == 200: + cr = x.json().get("key_metadata", {}).get("credits_remaining") + r["credits"], r["dead"] = cr, False + total += cr or 0 + print("OK %-28s credits=%s" % (r.get("email"), cr)) + else: + r["dead"] = True + print("DEAD %-28s %s %s" % (r.get("email"), x.status_code, x.text[:80])) + except Exception as e: + r["dead"] = None + print("ERR %-28s %s" % (r.get("email"), str(e)[:60])) + out.append(r) + +with open(BANK, "w") as f: + for r in out: + f.write(json.dumps(r, ensure_ascii=False) + "\n") +live = [r for r in out if r.get("dead") is False] +print("\nkeys=%d live=%d credits_total=%d" % (len(out), len(live), total)) \ No newline at end of file