From 7f304b97294da50f7665aeb1fe2dee72717c379f Mon Sep 17 00:00:00 2001 From: reform Date: Wed, 4 Nov 2026 13:40:21 +0300 Subject: [PATCH] cometapi autoreg: Castle via CDP, org fix, sequential wave (43 accounts verified) --- .gitignore | 9 +++ POST.md | 37 +++++++++ README.md | 74 ++++++++++++++++++ cap.py | 27 +++++++ comet2.py | 205 ++++++++++++++++++++++++++++++++++++++++++++++++++ comet_cdp.py | 150 ++++++++++++++++++++++++++++++++++++ kill_comet.py | 29 +++++++ orgfix.py | 54 +++++++++++++ tfa.py | 66 ++++++++++++++++ wave_seq.py | 85 +++++++++++++++++++++ 10 files changed, 736 insertions(+) create mode 100644 .gitignore create mode 100644 POST.md create mode 100644 README.md create mode 100644 cap.py create mode 100644 comet2.py create mode 100644 comet_cdp.py create mode 100644 kill_comet.py create mode 100644 orgfix.py create mode 100644 tfa.py create mode 100644 wave_seq.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c03cfed --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +*.jsonl +*.log +*.out +keys.jsonl +chrome_result_*.json +cdp_*.json +prof*/ +__pycache__/ +*.session diff --git a/POST.md b/POST.md new file mode 100644 index 0000000..68df818 --- /dev/null +++ b/POST.md @@ -0,0 +1,37 @@ +# COMETAPI — 493 модели за одним ключом, но есть нюанс + +CometAPI — агрегатор: один OpenAI-совместимый эндпоинт `https://api.cometapi.com/v1`, под ним 493 модели. Каталог реально богатый: `claude-opus-5-5` и `claude-fable-5-1`, `gpt-6.1-sol` / `-terra` / `gpt-6-luna` / `-astra`, `gemini-4-argon`, `gemini-3.8-flash`, `grok-4.7`, `deepseek-v4-pro`, `kimi-k3.1-pro`, `glm-5.3`, `qwen3.8-max`. Картинки — `flux-3`, `gemini-nano-banana-2.1`, `qwen-image-3.0`, `doubao-seedream-4-5`. Видео — `veo3.1`, 25 моделей `kling`, `runway`, `luma`, `seedance-2-5`. + +Одна модель из их же рекламы отсутствует: `sora-2-pro` в каталоге нет ни в одном виде. + +## Нюанс, из-за которого всё стоит + +Бонус $1.5 новому аккаунту **не начисляется**. Проверено на 43 аккаунтах, созданных авторегом: + +``` +quota: 0, first_create_token: false, first_api_call: false +POST /v1/chat/completions → 403 pre-consume quota failed +``` + +Не помогает ничего: другой домен почты, созданная организация, включённая 2FA, первый токен, первый вызов, ожидание час. Флаги `newbie_tasks` в `/api/status` есть, сервер их не выдаёт. Минимальное пополнение — $10, и только после него срабатывает `first_charge` ($3). + +То есть каталог открыт (`/v1/models` отдаёт все 493 без квоты), а генерация закрыта. + +## Что собрано и работает + +Репа: [cometapi-autoreg](https://git.reformboss.com/reform/cometapi-autoreg) + +Два барьера, которые она обходит: + +**Castle** — без `castle_request_token` сервер отвечает `registration blocked by security check`. Токен на 6300 символов рождается только в настоящем Chrome через `import('castle.umd')` + `createRequestToken()`, поэтому регистрация идёт по CDP на persistent-профиле, а не через `playwright.launch`. + +**Организация** — `org_list` остаётся `null` даже после успешного `POST /api/organization`, и токен отдаёт `organization context required`. Правильно брать id из `GET /api/organization` и слать его в `X-Organization-Id`. + +## Цифры волны + +* 40 аккаунтов за сессию, **100% с ключами**, 36-120с на аккаунт +* капчи ~$0.003 за аккаунт (Turnstile через 2captcha, токен 837 симв) +* три egress по кругу: ZTE, два SSH-socks +* письма приходят только на gmail `+alias`; aliyun, rambler, tvnetwork, gazeta — `verify 200` и тишина + +В парке 43 ключа, все годны на каталог и ждут, если промо включат. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..efb46ea --- /dev/null +++ b/README.md @@ -0,0 +1,74 @@ +# cometapi-autoreg + +Авторег аккаунтов [cometapi.com](https://www.cometapi.com) — агрегатор на 493 модели (Claude Opus 5.5, GPT-6.1 sol/terra/luna/astra, Gemini 4 argon, Grok 4.7, DeepSeek v4 pro, Kimi k3.1 pro, GLM 5.3, плюс 120 картинко- и видеомоделей). + +## Статус квоты (проверено 04.11.26) + +**Кредит $1.5 на новых аккаунтах не начисляется.** 43 аккаунта, созданных авторегом, у всех: + +``` +/api/user/self -> quota 0, first_create_token false, first_api_call false +POST /v1/chat/completions -> 403 pre-consume quota failed, + organization and owner combined quota is zero +``` + +Не помогает ничего из перечисленного: другой домен почты, создание организации, 2FA, первый токен, первый вызов, задержка в час. В `/api/status` флаги `newbie_tasks` присутствуют (`first_create_token` $0.5, `first_api_call` $1, `first_charge` $3), но сервер их не начисляет. Пополнение — от $10, только после этого включается `first_charge`. + +Итог: аккаунты годны на `/v1/models` (каталог без ключа квоты) и как парк под будущую активацию промо. Механика авторега полностью рабочая. + +## Как работает рега + +Входа по паролю нет — только passwordless по 6-значному коду: + +1. `GET /api/verification?email=&turnstile=` → `{"success":true}`. +2. Turnstile sitekey `0x4AAAAAABDUjQJBI2lFYkkW`, решается через 2captcha `TurnstileTaskProxyless` (токен ~837 симв). +3. `POST /api/user/login?turnstile=` с телом `{email, verification_code, castle_request_token}`. +4. Код приходит письмом от `CometAPI `, тема в base64: «CometAPI is your temporary login code: 823030». +5. Первый логин создаёт аккаунт (`data.id`). + +## Два барьера и их обход + +**Castle.** Без `castle_request_token` сервер отвечает `{"message":"registration blocked by security check"}`. Токен (~6300 симв) создаётся только в реальном Chrome: + +```js +const c = await import('/console/assets/castle.umd-Cdx-vt7N.js'); +c.configure({ pk: 'pk_5VctrDACzauDfAsjj8FUyjqNA4aJ71rS' }); +await c.createRequestToken(); +``` + +Поэтому регистрация идёт через persistent-профиль Chrome и `connect_over_cdp` (порт 9333+), а не через `playwright.launch`. + +**Организация.** `org_list` в `/api/user/self` остаётся `null` даже после успешного `POST /api/organization`, и `POST /api/token` отдаёт `organization context required`. Правильный путь — `GET /api/organization` → `data[0].id` → заголовки `X-Organization-Id` / `X-Workspace-Id` → токен создаётся. + +## Что ломает массовую волну + +* **Параллельность.** Три воркера одновременно → `registration blocked by security check` почти на всех. Последовательно — 0 блокировок. +* **Зависшие Chrome.** Процесс на профиле даёт `Page.goto: Timeout 90000ms exceeded` или `TargetClosedError`. Перед каждым аккаунтом профиль зачищается по `psutil`. +* **Почта.** Письма приходят только на gmail `+alias`. aliyun, rambler, tvnetwork, gazeta — `verify 200`, но письма нет вообще (их SMTP-фильтр, прокси не лечат). +* **IP.** Домашний и серверный адреса выжигаются за 1-2 регистрации (`429` с пустым телом). Работают три канала по кругу: ZTE `http://127.0.0.1:8899`, `socks5h://127.0.0.1:1089`, `socks5h://127.0.0.1:1090`. + +## Файлы + +* `comet_cdp.py` — основной регистратор: Chrome по CDP → Castle → Turnstile → код с почты → org → токен → ключ. +* `comet2.py` — общий слой (Turnstile-солвер, чтение кода по `X-GM-RAW to:`, запуск Chrome). +* `wave_seq.py` — волна: последовательные аккаунты, ротация трёх egress, чистка профиля перед стартом. +* `cap.py` — отдельный 2captcha Turnstile-солвер. +* `orgfix.py` — добивает организацию и токен по сохранённым cookies. +* `tfa.py` — включение 2FA по серверному времени (локальные часы уезжают на 60с+, TOTP по `Date` из `/api/status`). +* `kill_comet.py` — зачистка зависших процессов и Chrome по профилям. + +## Запуск + +``` +set COMET_GMAIL_USER=you@gmail.com +set COMET_GMAIL_PASS= +set TWOCAPTCHA_KEY= + +python wave_seq.py 30 1 # 30 аккаунтов начиная с +1@ +``` + +Альтернатива на внешних доменах с IMAP — `comet_cdp.py `. + +## Метрики волны + +40 аккаунтов за сессию: 100% успешных ключей, 36-120с на аккаунт, капчи ~$0.003 за аккаунт. Всего в парке 43 ключа. \ No newline at end of file diff --git a/cap.py b/cap.py new file mode 100644 index 0000000..ca43a69 --- /dev/null +++ b/cap.py @@ -0,0 +1,27 @@ +import json, time, sys, urllib.request, urllib.parse, os +KEY=os.environ.get('TWOCAPTCHA_KEY','') +SITEKEY="0x4AAAAAABDUjQJBI2lFYkkW" +PAGE="https://www.cometapi.com/console/login" +def post(url, data): + d=urllib.parse.urlencode(data).encode() + with urllib.request.urlopen(urllib.request.Request(url, data=d, headers={'User-Agent':'Mozilla/5.0'}), timeout=40) as r: + return json.loads(r.read().decode()) +def solve_turnstile(sitekey=SITEKEY, page=PAGE, tries=3): + for t in range(tries): + r=post("https://2captcha.com/in.php", {"key":KEY,"method":"turnstile","sitekey":sitekey,"pageurl":page,"json":1}) + if r.get("status")!=1: + print("in err", r); time.sleep(5); continue + tid=r["request"]; print("task", tid, flush=True) + for i in range(60): + time.sleep(5) + q=urllib.request.urlopen(f"https://2captcha.com/res.php?key={KEY}&action=get&id={tid}&json=1", timeout=30).read().decode() + j=json.loads(q) + if j.get("status")==1: + return j["request"] + if j.get("request") not in ("CAPCHA_NOT_READY",): + print("res err", j); break + return None +if __name__=="__main__": + tok=solve_turnstile() + print("TOKEN_LEN", len(tok or '')) + open("ts_token.txt","w").write(tok or "") diff --git a/comet2.py b/comet2.py new file mode 100644 index 0000000..e04a58d --- /dev/null +++ b/comet2.py @@ -0,0 +1,205 @@ +import json, re, time, sys, os, imaplib, email, requests +from email.header import decode_header + +KEY2CAP = os.environ.get("TWOCAPTCHA_KEY", "") +SITE = "0x4AAAAAABDUjQJBI2lFYkkW" +CASTLE_MOD = "/console/assets/castle.umd-Cdx-vt7N.js" +GM_USER = os.environ.get("COMET_GMAIL_USER", "") +GM_PASS = os.environ.get("COMET_GMAIL_PASS", "") +BASE = "https://www.cometapi.com" +LOG = open(r"C:\Users\User\tmp\cometapi\chrome.log", "a", encoding="utf-8") + + +def log(*a): + s = " ".join(str(x) for x in a) + print(s, flush=True) + LOG.write(time.strftime("[%H:%M:%S] ") + s + "\n"); LOG.flush() + + +def dh(v): + try: + return "".join(x.decode(e or "utf-8", "ignore") if isinstance(x, bytes) else x for x, e in decode_header(v)) + except Exception: + return str(v) + + +def solve(): + s = requests.Session() + r = s.post("https://api.2captcha.com/createTask", json={"clientKey": KEY2CAP, "task": { + "type": "TurnstileTaskProxyless", "websiteURL": BASE + "/console/login", + "websiteKey": SITE, + "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36", + "action": "login"}}, timeout=30).json() + tid = r.get("taskId") + log("captcha", tid or str(r)[:100]) + if not tid: + return None + for _ in range(60): + time.sleep(5) + res = s.post("https://api.2captcha.com/getTaskResult", json={"clientKey": KEY2CAP, "taskId": tid}, timeout=30).json() + if res.get("status") == "ready": + return res["solution"]["token"] + if res.get("errorId"): + return None + return None + + +def gmail_last_uid(addr): + try: + M = imaplib.IMAP4_SSL("imap.gmail.com", 993, timeout=30) + M.login(GM_USER, GM_PASS); M.select("INBOX", readonly=True) + t, d = M.search(None, "X-GM-RAW", '"to:%s newer_than:1d"' % addr) + ids = [int(x) for x in d[0].split()] or [0] + M.logout(); return max(ids) + except Exception as e: + log("imap base", repr(e)[:80]); return 0 + + +def gmail_code(addr, since, timeout=240): + end = time.time() + timeout + while time.time() < end: + try: + M = imaplib.IMAP4_SSL("imap.gmail.com", 993, timeout=30) + M.login(GM_USER, GM_PASS) + M.select("INBOX", readonly=True) + t, d = M.search(None, "X-GM-RAW", '"to:%s newer_than:1d"' % addr) + ids = [int(x) for x in d[0].split()] + ids = [i for i in ids if i > since][-25:] + for i in reversed(ids): + raw = M.fetch(str(i).encode(), "(BODY.PEEK[])")[1][0][1] + msg = email.message_from_bytes(raw) + subj = dh(str(msg.get("Subject", ""))) + m = re.search(r"(\d{6})", subj) + if m: + log("mail:", subj[:70]); M.logout(); return m.group(1) + M.logout() + except Exception as e: + log("imap", repr(e)[:80]) + time.sleep(6) + return None + + +def chrome_exe(): + for c in [r"C:\Program Files\Google\Chrome\Application\chrome.exe", + os.path.join(os.environ.get("LOCALAPPDATA", ""), r"Google\Chrome\Application\chrome.exe"), + r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"]: + if os.path.exists(c): + return c + return None + + +def main(addr): + from playwright.sync_api import sync_playwright + res = {"email": addr} + with sync_playwright() as pw: + px = os.environ.get("COMET_PROXY", "").strip() + launch_kw = dict(executable_path=chrome_exe(), headless=False, + args=["--disable-blink-features=AutomationControlled"]) + if px: + launch_kw["proxy"] = {"server": px} + br = pw.chromium.launch(**launch_kw) + ctx = br.new_context(locale="en-US", viewport={"width": 1366, "height": 900}) + pg = ctx.new_page() + pg.goto(BASE + "/console/login", wait_until="domcontentloaded", timeout=90000) + pg.wait_for_timeout(6000) + pk = pg.evaluate("async()=>{const r=await fetch('/api/status');const j=await r.json();return j.data.castle_publishable_key||''}") + log("castle_pk:", pk) + pg.evaluate("(v)=>{window.__pk=v}", pk) + + base_uid = gmail_last_uid(addr) + log("baseline uid", base_uid) + cap = solve() + v = pg.evaluate("""async ([email, tok]) => { + const r = await fetch('/api/verification?email=' + encodeURIComponent(email) + '&turnstile=' + encodeURIComponent(tok)); + return [r.status, await r.text()]; + }""", [addr, cap]) + log("verify:", v) + res["verify"] = v + if '"success":true' not in v[1]: + br.close(); return res + code = gmail_code(addr, base_uid) + log("code:", code) + if not code: + br.close(); return res + cap2 = solve() + out = pg.evaluate("""async ([email, code, tok, mod]) => { + const log = []; + let ct = ''; + try { + const m = await import(mod); + const c = m.c || m.default; + const client = c.configure({ pk: window.__pk }); + ct = await client.createRequestToken(); + log.push('ctlen:' + (ct || '').length); + } catch (e) { log.push('CERR:' + String((e && e.message) || e)); } + const r = await fetch('/api/user/login?turnstile=' + encodeURIComponent(tok), { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email: email, verification_code: code, castle_request_token: ct, + aff_code: '', ref: null, landing_page: null, referrer: null }) + }); + const txt = await r.text(); + log.push('login:' + r.status + ':' + txt.slice(0, 1500)); + return log; + }""", [addr, code, cap2, CASTLE_MOD]) + log("LOGIN OUT:", " || ".join(out)) + res["login"] = out + res["cookies"] = {c["name"]: c["value"] for c in ctx.cookies() if "cometapi" in c["domain"]} + ok = any('"success":true' in x for x in out) + me = pg.evaluate("async()=>{const r=await fetch('/api/user/self');return [r.status, await r.text()]}") + log("self:", me[1][:600]) + res["self"] = me[1] + if ok: + tk = pg.evaluate("""async()=>{ + const me = await (await fetch('/api/user/self')).json(); + const ol = (me.data && me.data.org_list) || []; + let oid=null, wid=null; + if (ol.length) { const o = ol.find(x=>x.state==='active')||ol[0]; oid = o.id; + const wl = o.workspace_list||[]; wid = wl.length ? (wl.find(x=>x.state==='active')||wl[0]).id : o.id; } + if (!oid) { try { const o = await (await fetch('/api/organization')).json(); + const arr = o.data||[]; if (arr.length) { oid = arr[0].id; const wl=arr[0].workspace_list||[]; wid = wl.length?wl[0].id:oid; } } catch(e){} } + const H = {'Content-Type':'application/json'}; + if (oid) { H['X-Organization-Id']=String(oid); H['X-Workspace-Id']=String(wid||oid); } + const r = await fetch('/api/token', {method:'POST', headers:H, + body: JSON.stringify({name:'main', remain_quota:0, expired_time:-1, unlimited_quota:true, + model_limits_enabled:false, model_limits:'', allow_ips:'', group:''})}); + const a = await r.text(); + const b = await (await fetch('/api/token?p=0&size=10', {headers:H})).text(); + const c = await (await fetch('/api/user/self')).text(); + return [a.slice(0,500), b.slice(0,1800), c.slice(0,1500), String(oid), String(wid)]; + }""") + log("TOKEN CREATE:", tk[0]) + log("TOKEN LIST:", tk[1][:1200]) + log("SELF AFTER:", tk[2][:900]) + log("ORG/WS:", tk[3], tk[4]) + res["token_create"] = tk[0]; res["token_list"] = tk[1]; res["self_after"] = tk[2] + res["org"] = tk[3]; res["ws"] = tk[4] + m = re.search(r'"key":"([^"]+)"', tk[0]) + if m: + k = m.group(1) + res["key"] = k if k.startswith("sk-") else "sk-" + k + log("KEY", res["key"]) + probe = {} + for path in ["/console/register", "/console/token", "/console/personal"]: + try: + pg.goto(BASE + path, wait_until="domcontentloaded", timeout=60000) + pg.wait_for_timeout(5000) + txt = pg.inner_text("body")[:1200] + btns = pg.evaluate("JSON.stringify([...document.querySelectorAll('button,a')].map(e=>e.innerText.trim()).filter(Boolean).slice(0,40))") + probe[path] = {"url": pg.url, "text": txt, "buttons": btns} + log("UI", path, "->", pg.url, "|", txt[:160].replace("\n", " | ")) + except Exception as e: + probe[path] = {"err": str(e)[:120]} + res["ui_probe"] = probe + br.close() + return res + + +if __name__ == "__main__": + a = sys.argv[1] + r = main(a) + open(r"C:\Users\User\tmp\cometapi\chrome_result_%s.json" % re.sub(r"\W+", "_", a), "w", encoding="utf-8").write( + json.dumps(r, ensure_ascii=False, indent=1)) + if r.get("key"): + open(r"C:\Users\User\tmp\cometapi\keys.jsonl", "a", encoding="utf-8").write( + json.dumps({"email": a, "key": r["key"], "ts": int(time.time())}) + "\n") + log("DONE", r.get("key")) \ No newline at end of file diff --git a/comet_cdp.py b/comet_cdp.py new file mode 100644 index 0000000..8d47d58 --- /dev/null +++ b/comet_cdp.py @@ -0,0 +1,150 @@ +import json, os, re, sys, time, subprocess, urllib.request +sys.path.insert(0, r"C:\Users\User\tmp\cometapi") +import comet2 as C + +BASE = C.BASE +CHROME = C.chrome_exe() +PORT = int(os.environ.get("CC_PORT", "9333")) +PROF = os.environ.get("CC_PROF", r"C:\Users\User\tmp\cometapi\prof_home") +PROXY = os.environ.get("CC_PROXY", "").strip() + + +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 + + +def start(): + if up(): return True + os.makedirs(PROF, exist_ok=True) + args = [CHROME, "--remote-debugging-port=%d" % PORT, "--user-data-dir=" + PROF, + "--no-first-run", "--no-default-browser-check", "--disable-blink-features=AutomationControlled", + "--window-size=1366,900"] + if PROXY: + args += ["--proxy-server=" + PROXY, "--proxy-bypass-list=<-loopback>"] + args.append("about:blank") + subprocess.Popen(args, creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP, + stdout=open(r"C:\Users\User\tmp\cometapi\cc.out", "ab"), stderr=subprocess.STDOUT, close_fds=True) + for _ in range(30): + time.sleep(1) + if up(): return True + return False + + +def run(addr, ihost, iuser, ipass, iport=993): + from playwright.sync_api import sync_playwright + out = {"email": addr, "cdp": PORT} + if not start(): + out["err"] = "chrome_down"; return out + with sync_playwright() as pw: + br = pw.chromium.connect_over_cdp("http://127.0.0.1:%d" % PORT) + ctx = br.contexts[0] if br.contexts else br.new_context() + pg = [x for x in ctx.pages if "cometapi" in (x.url or "")] + pg = pg[0] if pg else (ctx.pages[0] if ctx.pages else ctx.new_page()) + base = C.gmail_last_uid(addr) if addr.endswith("gmail.com") else 0 + if not addr.endswith("gmail.com"): + import imaplib + try: + M = imaplib.IMAP4_SSL(ihost, iport, timeout=25); M.login(iuser, ipass); M.select("INBOX", readonly=True) + typ, d = M.search(None, "ALL"); ids = [int(x) for x in d[0].split()] or [0]; base = max(ids); M.logout() + except Exception as e: + C.log("imap base", repr(e)[:80]); out["err"] = "imap_dead"; return out + pg.goto(BASE + "/console/login", wait_until="domcontentloaded", timeout=90000) + pg.wait_for_timeout(6000) + pk = pg.evaluate("async()=>{const r=await fetch('/api/status');const j=await r.json();return j.data.castle_publishable_key||''}") + pg.evaluate("(v)=>{window.__pk=v}", pk) + C.log("page", pg.url, "pk", pk[:12]) + cap = C.solve() + v = pg.evaluate("""async ([email, tok]) => { + const r = await fetch('/api/verification?email=' + encodeURIComponent(email) + '&turnstile=' + encodeURIComponent(tok)); + return [r.status, await r.text()]; + }""", [addr, cap]) + C.log("verify", v[0], v[1][:120]) + out["verify"] = v[1] + if '"success":true' not in v[1]: + return out + # read code + code = None + if addr.endswith("gmail.com"): + code = C.gmail_code(addr, base) + else: + import imaplib, email as em + end = time.time() + 180 + while time.time() < end and not code: + try: + M = imaplib.IMAP4_SSL(ihost, iport, timeout=25); M.login(iuser, ipass); M.select("INBOX", readonly=True) + typ, d = M.search(None, "ALL") + ids = [int(x) for x in d[0].split() if int(x) > base][-10:] + for i in reversed(ids): + raw = M.fetch(str(i).encode(), "(BODY.PEEK[])")[1][0][1] + msg = em.message_from_bytes(raw) + m = re.search(r"(\d{6})", C.dh(str(msg.get("Subject", "")))) + if m: + code = m.group(1); break + M.logout() + except Exception as e: + C.log("imap", repr(e)[:80]) + if not code: time.sleep(6) + C.log("code", code) + out["code"] = code + if not code: return out + cap2 = C.solve() + res = pg.evaluate("""async ([email, code, tok, mod]) => { + let ct=''; + try { const m = await import(mod); const c = m.c||m.default; ct = await (c.configure({pk:window.__pk})).createRequestToken(); } + catch(e){ return {err:'castle:'+String(e && e.message||e)}; } + const r = await fetch('/api/user/login?turnstile='+encodeURIComponent(tok), {method:'POST', + headers:{'Content-Type':'application/json'}, + body: JSON.stringify({email, verification_code:code, castle_request_token:ct, aff_code:'', ref:null, landing_page:null, referrer:null})}); + const t = await r.text(); + let s2=null; try { s2 = await (await fetch('/api/user/self')).json(); } catch(e){} + return {status:r.status, body:t.slice(0,400), me: s2 && s2.data ? {id:s2.data.id, quota:s2.data.quota, org:(s2.data.org_list||[])[0]} : null}; + }""", [addr, code, cap2, C.CASTLE_MOD]) + C.log("login", str(res)[:280]) + out["login"] = res + if not res.get("me"): return out + oid = str((res["me"].get("org") or {}).get("id") or "") + tk = pg.evaluate("""async (o)=>{ + const H={'Content-Type':'application/json'}; + let oid = o; + if(!oid){ + try{ + const g = await (await fetch('/api/organization')).json(); + if(g && g.data && g.data.length) oid = String(g.data[0].id); + }catch(e){} + } + if(!oid){ + try{ + await fetch('/api/organization',{method:'POST',headers:H,body:JSON.stringify({name:'org '+Math.random().toString(36).slice(2,8)})}); + const g = await (await fetch('/api/organization')).json(); + if(g && g.data && g.data.length) oid = String(g.data[0].id); + }catch(e){} + } + if(oid){H['X-Organization-Id']=oid;H['X-Workspace-Id']=oid;} + const r=await fetch('/api/token',{method:'POST',headers:H,body:JSON.stringify({name:'main',remain_quota:0,expired_time:-1,unlimited_quota:true,model_limits_enabled:false,model_limits:'',allow_ips:'',group:''})}); + const a=await r.text(); + const s2=await (await fetch('/api/user/self')).json(); + return [a, JSON.stringify({q:s2.data.quota,fct:s2.data.first_create_token,fac:s2.data.first_api_call}), oid]; + }""", oid) + C.log("token", tk[0][:250]); C.log("self2", tk[1][:160]) + out["token"] = tk[0]; out["self_after"] = tk[1]; out["org"] = tk[2] if len(tk) > 2 else oid + m = re.search(r'"key":"([^"]+)"', tk[0]) + if m: + k = m.group(1); out["key"] = k if k.startswith("sk-") else "sk-" + k + C.log("KEY", out["key"]) + out["cookies"] = {c["name"]: c["value"] for c in ctx.cookies() if "cometapi" in c["domain"]} + return out + + +if __name__ == "__main__": + addr = sys.argv[1]; ihost = sys.argv[2]; iuser = sys.argv[3]; ipass = sys.argv[4] + iport = int(sys.argv[5]) if len(sys.argv) > 5 and sys.argv[5] != "-" else 993 + r = run(addr, ihost, iuser, ipass, iport) + fn = r"C:\Users\User\tmp\cometapi\cdp_%s.json" % re.sub(r"\W+", "_", addr) + open(fn, "w", encoding="utf-8").write(json.dumps(r, ensure_ascii=False, indent=1)) + if r.get("key"): + open(r"C:\Users\User\tmp\cometapi\keys.jsonl", "a", encoding="utf-8").write( + json.dumps({"email": addr, "key": r["key"], "ts": int(time.time())}) + "\n") \ No newline at end of file diff --git a/kill_comet.py b/kill_comet.py new file mode 100644 index 0000000..b5c5177 --- /dev/null +++ b/kill_comet.py @@ -0,0 +1,29 @@ +import psutil +import time + +marks = ('wave_seq.py', 'comet_cdp.py', 'wave_gmail.py', 'comet_wave_px.py') +killed = [] +for p in psutil.process_iter(['pid', 'name', 'cmdline']): + try: + if (p.info['name'] or '').lower() != 'python.exe': + continue + c = ' '.join(p.info['cmdline'] or []) + if any(m in c for m in marks) and 'kill_comet.py' not in c: + p.kill() + killed.append(p.info['pid']) + except Exception: + pass +time.sleep(1) +c2 = 0 +for p in psutil.process_iter(['pid', 'name', 'cmdline']): + try: + if (p.info['name'] or '').lower() != 'chrome.exe': + continue + c = ' '.join(p.info['cmdline'] or []) + if 'cometapi' in c and 'prof' in c: + p.kill() + c2 += 1 + except Exception: + pass +print('killed python:', killed) +print('killed chrome:', c2) \ No newline at end of file diff --git a/orgfix.py b/orgfix.py new file mode 100644 index 0000000..6b085a9 --- /dev/null +++ b/orgfix.py @@ -0,0 +1,54 @@ +import json, sys, requests, time + +B = 'https://www.cometapi.com' + + +def go(result_file): + d = json.load(open(result_file)) + s = requests.Session() + for k, v in (d.get('cookies') or {}).items(): + try: + s.cookies.set(k, v, domain='www.cometapi.com') + except Exception: + pass + H = {'User-Agent': 'Mozilla/5.0 Chrome/141', 'Accept': 'application/json', 'Origin': B, + 'Referer': B + '/console/token', 'Content-Type': 'application/json'} + r = s.get(B + '/api/user/self', headers=H, timeout=25) + me = r.json().get('data', {}) + print('self', r.status_code, 'quota', me.get('quota'), 'orgs', json.dumps(me.get('org_list'), ensure_ascii=False)[:300]) + if not me.get('org_list'): + nm = (d.get('email') or 'acct').split('@')[0] + r2 = s.post(B + '/api/organization', headers=H, json={"name": nm + " org"}, timeout=30) + print('org create', r2.status_code, r2.text[:300]) + r = s.get(B + '/api/user/self', headers=H, timeout=25) + me = r.json().get('data', {}) + print('self2 quota', me.get('quota'), 'orgs', json.dumps(me.get('org_list'), ensure_ascii=False)[:300]) + ol = me.get('org_list') or [] + oid = str(ol[0]['id']) if ol else None + if oid: + HH = dict(H); HH['X-Organization-Id'] = oid; HH['X-Workspace-Id'] = oid + tk = s.post(B + '/api/token', headers=HH, json={"name": "main", "remain_quota": 0, "expired_time": -1, + "unlimited_quota": True, "model_limits_enabled": False, + "model_limits": "", "allow_ips": "", "group": ""}, timeout=30) + print('token', tk.status_code, tk.text[:300]) + key = None + try: + key = tk.json()['data']['key'] + except Exception: + pass + me2 = s.get(B + '/api/user/self', headers=HH, timeout=25).json().get('data', {}) + print('after: quota', me2.get('quota'), 'fct', me2.get('first_create_token'), 'fac', me2.get('first_api_call')) + if key: + k = key if key.startswith('sk-') else 'sk-' + key + print('KEY', k) + json.dump({'email': d.get('email'), 'key': k, 'org': oid}, open(result_file.replace('.json', '_tok.json'), 'w')) + # test chat + r3 = requests.post('https://api.cometapi.com/v1/chat/completions', + headers={'Authorization': 'Bearer ' + k, 'Content-Type': 'application/json'}, + json={'model': 'gpt-6-luna', 'messages': [{'role': 'user', 'content': 'say ok'}], 'max_tokens': 10}, + timeout=90) + print('chat', r3.status_code, r3.text[:250]) + + +if __name__ == '__main__': + go(sys.argv[1]) \ No newline at end of file diff --git a/tfa.py b/tfa.py new file mode 100644 index 0000000..9873413 --- /dev/null +++ b/tfa.py @@ -0,0 +1,66 @@ +import json, requests, time, hmac, hashlib, base64, struct, email.utils, sys + +B = 'https://www.cometapi.com' + + +def server_ts(s): + r = s.get(B + '/api/status', timeout=20) + d = r.headers.get('Date') + try: + return email.utils.parsedate_to_datetime(d).timestamp() + except Exception: + return time.time() + + +def totp(secret, ts, step=30): + key = base64.b32decode(secret + '=' * ((8 - len(secret) % 8) % 8)) + h = hmac.new(key, struct.pack('>Q', int(ts // step)), hashlib.sha1).digest() + o = h[-1] % 16 + return str((struct.unpack('>I', h[o:o + 4])[0] % 0x80000000) % 1000000).zfill(6) + + +def run(result_file): + d = json.load(open(result_file)) + s = requests.Session() + for k, v in d['cookies'].items(): + try: + s.cookies.set(k, v, domain='www.cometapi.com') + except Exception: + pass + H = {'User-Agent': 'Mozilla/5.0 Chrome/141', 'Accept': 'application/json', 'Origin': B, + 'Referer': B + '/console/personal', 'X-Organization-Id': str(d.get('org')), + 'X-Workspace-Id': str(d.get('ws')), 'Content-Type': 'application/json'} + st = s.get(B + '/api/user/2fa/status', headers=H, timeout=20).json() + print('2fa status before', st) + if st.get('data', {}).get('enabled'): + print('already enabled'); return + for attempt in range(5): + r = s.post(B + '/api/user/2fa/setup', headers=H, json={}, timeout=25) + if r.status_code != 200: + print('setup', r.status_code, r.text[:120]); time.sleep(60); continue + j = r.json() + if 'data' not in j: + print('setup body', j); time.sleep(60); continue + sec = j['data']['secret'] + codes = j['data']['backup_codes'] + ts = server_ts(s) + print('secret', sec, 'srv_ts', ts, 'local', time.time()) + for off in (0, -30, 30): + code = totp(sec, ts + off) + r2 = s.post(B + '/api/user/2fa/enable', headers=H, json={"code": code}, timeout=25) + print(' try', off, code, r2.status_code, r2.text[:140]) + if r2.status_code == 429: + time.sleep(70); break + if '"success":true' in r2.text: + json.dump({"secret": sec, "backup": codes}, + open(result_file.replace('.json', '_2fa.json'), 'w')) + print('ENABLED') + me = s.get(B + '/api/user/self', headers=H, timeout=20).json()['data'] + print('quota', me.get('quota'), 'fct', me.get('first_create_token'), 'fac', me.get('first_api_call')) + return + time.sleep(45) + print('FAILED to enable') + + +if __name__ == '__main__': + run(sys.argv[1]) \ No newline at end of file diff --git a/wave_seq.py b/wave_seq.py new file mode 100644 index 0000000..5f4c54c --- /dev/null +++ b/wave_seq.py @@ -0,0 +1,85 @@ +"""Последовательная волна CometAPI на gmail-алиасах с ротацией egress. +Запуск: python wave_seq.py [start_index] +""" +import json +import os +import re +import subprocess +import sys +import time + +HERE = r'C:\Users\User\tmp\cometapi' +PY = r'C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe' +GM_USER = os.environ.get('COMET_GMAIL_USER', '') +GM_PASS = os.environ.get('COMET_GMAIL_PASS', '') +OUT = os.path.join(HERE, 'gmail_wave.jsonl') +USED = os.path.join(HERE, 'gmail_used_seq.txt') + +CHANNELS = [ + ('zte', 'http://127.0.0.1:8899', 0), + ('ssh1089', 'socks5://127.0.0.1:1089', 0), + ('ssh1090', 'socks5://127.0.0.1:1090', 0), +] + +N = int(sys.argv[1]) if len(sys.argv) > 1 else 15 +START = int(sys.argv[2]) if len(sys.argv) > 2 else 41 + +used = set() +if os.path.exists(USED): + used = {l.strip().lower() for l in open(USED, encoding='utf-8', errors='ignore') if l.strip()} + +addrs = [] +i = START +while len(addrs) < N and i < START + 500: + a = 'baradok609+cm%d@gmail.com' % i + if a.lower() not in used: + addrs.append(a) + i += 1 +print('queue', len(addrs), flush=True) + +ok = 0 +for n, addr in enumerate(addrs): + ch_name, ch_url, idx = CHANNELS[n % 3] + port_cdp = 9360 + idx + prof = os.path.join(HERE, 'prof_s%d' % idx) + env = dict(os.environ) + env.pop('PYTHONPATH', None) + env.update({'CC_PROXY': ch_url, 'CC_PORT': str(port_cdp), 'CC_PROF': prof}) + # чистим зависшие Chrome на этом профиле (иначе goto висит 90с) + try: + import psutil + for pp in psutil.process_iter(['pid', 'name', 'cmdline']): + if (pp.info['name'] or '').lower() != 'chrome.exe': + continue + pc = ' '.join(pp.info['cmdline'] or []) + if prof in pc: + try: + pp.kill() + except Exception: + pass + time.sleep(2) + except Exception: + pass + cmd = [PY, os.path.join(HERE, 'comet_cdp.py'), addr, 'imap.gmail.com', GM_USER, GM_PASS, '993'] + print('[%s] start %s' % (ch_name, addr), flush=True) + t0 = time.time() + try: + r = subprocess.run(cmd, cwd=HERE, env=env, capture_output=True, text=True, timeout=420) + out = (r.stdout or '') + (r.stderr or '') + except subprocess.TimeoutExpired: + out = 'TIMEOUT' + tail = '\n'.join(out.strip().splitlines()[-6:]) + keys = re.findall(r'sk-[A-Za-z0-9]{20,}', out) + blocked = 'blocked by s' in out + rec = {'email': addr, 'channel': ch_name, 'sec': round(time.time() - t0, 1), + 'key': keys[-1] if keys else None, 'blocked': blocked, 'raw': tail[-400:]} + if keys: + ok += 1 + with open(OUT, 'a', encoding='utf-8') as f: + f.write(json.dumps(rec, ensure_ascii=False) + '\n') + with open(USED, 'a', encoding='utf-8') as f: + f.write(addr + '\n') + print('[%s] %s key=%s blocked=%s %.0fs' % (ch_name, addr, bool(keys), blocked, rec['sec']), flush=True) + time.sleep(20) + +print('WAVE DONE ok=%d/%d' % (ok, len(addrs)), flush=True) \ No newline at end of file