commit fd52c6360728491fe1e7b1e5a7eb34fda6eaad8a Author: reform Date: Fri Oct 23 20:04:06 2026 +0300 recovered snapshot from suspended aaronjaworski710 (history unavailable) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..231980a --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +captcha_keys.json +gpt_cands.json +gpt_state_*.json +pool.json +token.txt +type_accounts.jsonl +used_numbers.json +*.log +*.png +storages.json +ck_url.txt +__pycache__/ +# radar revive +radar_session.json +gws_user.json +_reuse_candidates.json +radar_creds.json +_reserve.json +_code.json +_reserve.log +_reader.log +no2_fallback.json +wave_run*.log +creds.json +tasks/ +tools/used_emails.txt diff --git a/README.md b/README.md new file mode 100644 index 0000000..3bb29e2 --- /dev/null +++ b/README.md @@ -0,0 +1,84 @@ +# ⚡ type-com-toolkit + +> 🩸 **[иишко — AI tools, авторег-стеки, шлюзы](https://t.me/AlStack)** + +Полный тулкит по **type.com** («shared automations and agents for Claude and Codex», Savvy Learn Inc): реверс oRPC-протокола, E2E-авторег через WorkOS, OpenAI-совместимый шлюз поверх пула аккаунтов, radar-revive мёртвых сессий. + +Свежий аккаунт = **14 дней триала**, каталог **25 моделей** (gpt-6.1-sol, claude-opus-5-5, claude-fable-5-1, gemini-3.1-pro-preview...), **но для тредов нужна карта** (Stripe live, после триала $50/мес Type Standard). BYO-codex (привязка своего ChatGPT через device flow) поддерживается. + +## Дашборд +```bash +python dashboard.py # → http://127.0.0.1:8610 +``` +Форма кредов (2captcha / 2nd-no / voidash-домен / Google для radar) → кнопки: **рег N акков**, **шлюз :8600**, **radar revive**, **логин существующего** → живой лог задач → скачивание результатов (`type_accounts.jsonl`, `pool.json`). Креды пишутся только в локальный `creds.json` (gitignored), наружу не уходят. + +## Состав +``` +dashboard.py — веб-дашборд (stdlib, форма кредов, задачи, логи, результаты) +tools/ + type_reg.py — полный авторег: temp-mail OTP + WorkOS radar phone (2nd-no SMS) + сбор токенов + sms2no_reserve.py — бронь номеров 2nd-no.com + читалка SMS (2captcha Turnstile) + sms_reader.py — читалка свежих SMS (min_ts фильтр, skip GitLab) + login_token.py — логин существующего акка → authToken → pool.json + login_check.py — быстрая проверка живости аккаунта + radar_revive.py — оживление мёртвой сессии через WorkOS radar phone (Google re-auth) + codex_link2.py — BYO: привязка своего ChatGPT (OpenAI device flow) + checkout_probe.py — автоматизация/проба Stripe checkout (cloakbrowser) + typegw.py — OpenAI-совместимый шлюз (:8600, /v1/chat/completions, дашборд на /) +providers/ + secondno.py — JSON-RPC клиент 2nd-no.com (register→login→turnstile→reserve→read_sms) +REVERSE.md — полная документация oRPC-протокола (модели, треды, биллинг) +*.example.json — шаблоны файлов кредов (реальные значения — gitignored) +``` + +## Требования +- Python 3.11, `cloakbrowser` (стелс-браузер — WorkOS Signals убивает обычный headless), `playwright`, `requests` +- Ключ 2captcha (`captcha_keys.json`: `{"keys":[{"label":"x","key":"..."}]}` или env `CAPTCHA_KEYS_FILE`) +- Аккаунт 2nd-no.com (бесплатные номера, ~3 номера/акк/3 дня) +- Опционально: аккаунты ChatGPT для BYO-codex (`gpt_cands.json`) + +## Быстрый старт +```bash +# 1. авторег N аккаунтов (пишет type_accounts.jsonl + pool.json) +python tools/type_reg.py 3 voidash + +# 2. шлюз +python tools/typegw.py 8600 +curl http://127.0.0.1:8600/v1/chat/completions \ + -H "Authorization: Bearer ***" -H "Content-Type: application/json" \ + -d '{"model":"claude-sonnet-5-5","messages":[{"role":"user","content":"hi"}]}' + +# 3. (опционально) привязать свой ChatGPT +python tools/codex_link2.py 0 +``` +Env: `TYPE_TOOLKIT_ROOT`, `CAPTCHA_KEYS_FILE`, `PY311`, `NO2_EMAIL`/`NO2_PASS`, `VOID_DOMAIN`. + +## Статус / ограничения (2026-10-13) +- Авторег E2E работает (~2 мин/акк): voidash.bond почта + 2nd-no SMS + 2captcha Turnstile. **7 аккаунтов подтверждённо зарегистрировано за день** (волны, пик 2/3 OK за ~14 мин). +- ⚠️ **Кард-гейт**: `messages/createMessage` → 403 пока не привязана карта через `billing/createCheckoutSession` (тир `basic`/`standard_50`). Фейковые BIN-ген карты не проходят сетевую верификацию Stripe. +- ⚠️ BYO-codex: линкер device-flow в комплекте; снимает ли он кард-гейт — зависит от аккаунта, проверяется `codex_link2.py` (автоматически гоняет createMessage-пробу). +- Шлюз `typegw.py`: ротация пула, карантин мёртвых токенов, дашборд со статистикой. Ответы бота приходят в ТРЕДЫ (`getMessagesPaginated`, сообщение `msg_bot_*_mention`, латентность 5–45с). +- Проверены живыми ответами: `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-4-5`, `gpt-6.1-sol`, `gemini-3-flash-preview`. + +### Radar phone revive +Оживление потерянного аккаунта через WorkOS radar phone: +```bash +RADAR_TARGET=you@domain.com RADAR_SESS=session.json GWS_USER_FILE=gws.json \ +python tools/radar_revive.py +``` +Креды через env (или argv: `python tools/radar_revive.py email sess.json gws.json`). Шаблон: `gws_user.example.json`. + +### Троттлинг телефонов +WorkOS radar антифрод троттлит **по пользователю** (~2-3 отправки/час на все номера). Если `radar-challenge/verify` висит без SMS — ждать 1.5-2ч и ретраить. Батчи `type_reg.py` = **по 1 новому юзеру** — кросс-аккаунтового троттлинга нет, интервал ~3 мин между акками достаточен. + +### Воркспейс = почтовый домен +Все аккаунты одного домена (например `voidash.bond`) попадают в ОДИН общий воркспейс (общий биллинг/квота). **Новый домен = новый воркспейс = свежий триал**. `VOID_DOMAIN=yourdomain.com` задаёт префикс temp-mail. + +### Каталог моделей (25, REVERSE.md §Model catalog) +OpenAI/Codex (9) + Anthropic (11) + Google (3). + +--- + +Собрано ENI для @reformboss. Протокол: [REVERSE.md](REVERSE.md). + +> 🩸 **[иишко](https://t.me/AlStack)** — авторег-стеки, шлюзы, AI-инструменты. Репост, чтобы больше людей узнало 🔁 diff --git a/REVERSE.md b/REVERSE.md new file mode 100644 index 0000000..56cab01 --- /dev/null +++ b/REVERSE.md @@ -0,0 +1,108 @@ +# type.com REVERSE — API protocol (oRPC) + +Reverse-engineered 2026-10-13. type.com = "Shared automations and agents for Claude and Codex" (Savvy Learn, Inc.). + +## Auth +- WorkOS AuthKit: `auth.type.com` — email + OTP, then **radar-challenge phone verification** (SMS, mandatory for signup). +- Frontend stores `authToken` in `sessionStorage`, `workos:refresh-token` in `localStorage`. +- API auth: `Authorization: Bearer ` (also accepts `auth_token` cookie or `token` query param). + +## API base +``` +POST https://api.type.com/api/orpc// +Content-Type: application/json +Origin: https://type.com +Body: {"json": { ...payload }} +``` +Responses: `{"json": {...}}` on success; validation errors return Zod-style issues (leaks full enum/pattern constraints — great for fuzzing). + +## Known endpoints +| Endpoint | Payload | Notes | +|---|---|---| +| `channels/getUserChannels` | `{}` | → `[{id: "ch_...", ...}]` | +| `messages/createMessage` | see below | 403 `Add a credit card to your workspace before starting a new thread` until card attached | +| `messages/getMessagesPaginated` | `{channelId, limit: 25, direction: "backward"}` | poll for bot reply (`isBotResponse`, `isStreaming`, `textContent`, `hasError`) | +| `models/listModels` | `{}` | catalog | +| `agents/listAgents` | `{}` | | +| `sidekick/ensureMine` | `{}` | personal agent | +| `billing/getStatus` | `{}` | `{billingProvider:"stripe", status:"type_trialing", trialEnd, canUpgrade, canManage...}` | +| `billing/createCheckoutSession` | `{tier}` | tier ∈ `basic\|pro\|premium\|enterprise\|standard_50\|premium_100\|enterprise_250\|enterprise_500\|enterprise_750\|test` (`test` rejected). → `{url}` Stripe live checkout at `pay.type.com` | +| `usersAuth/getCodexAuth` | `{}` | `{codexAuth, codexFastModeSupported}` — BYO ChatGPT/Codex link state | +| `usersAuth/startCodexDeviceAuth` | `{}` | → `{sessionId}` | +| `usersAuth/getCodexDeviceAuthStatus` | `{sessionId}` | → `{userCode, verificationUrl, expiresAt, status}` (OpenAI device flow, approve while logged into ChatGPT) | + +## createMessage payload (validated shape) +```json +{"json": { + "id": "msg_", // /^msg_[0-7][0-9a-hjkmnp-tv-z]{25}$/ (Crockford base32, first char 0-7) + "channelId": "ch_...", + "parentMessageId": null, "subchannelId": null, "replyToId": null, + "content": {"version": "1.0", "blocks": [{"type": "paragraph", "children": [{"type": "text", "text": "..."}]}]}, + "contentSchemaVersion": "1.0", + "textContent": "...", + "botName": null, "isBotResponse": false, "isStreaming": false, "hasError": false, + "fileIds": [], "timezone": "Europe/Kyiv", + "aiProvider": "openai|anthropic|google", + "modelId": "gpt-6.1-sol", + "triggerTimestamp": 1791855056000, + "responseIndex": 0, + "agentToggleEnabled": true, + "replyMode": "chat", // "chat" | "prompt" + "metadata": null +}} +``` +Earlier probes also hit `browserPreference` enum (`cloud|native`) on some variants. + +Reply = poll `getMessagesPaginated`, match bot message by `replyToId`/`parentMessageId`/`triggerTimestamp`/ULID ordering; done when `isStreaming=false` and `textContent` non-empty. + +## Model catalog (25) +- OpenAI/Codex: `gpt-6.1-sol` (default), `gpt-6-sol`, `gpt-6-luna`, `gpt-6-astra`, `gpt-5.5`, `gpt-5.6-sol/terra/luna`, `gpt-5.2-2025-12-11`, `gpt-5-mini-2025-08-07` +- Anthropic: `claude-opus-5-5`, `claude-opus-5`, `claude-opus-4-8`, `claude-fable-5-1`, `claude-fable-5`, `claude-sonnet-5-5`, `claude-sonnet-5`, `claude-sonnet-4-6`, `claude-opus-4-5-20251101`, `claude-haiku-5-5`, `claude-haiku-4-5-20251001` +- Google: `gemini-3-flash-preview`, `gemini-3-pro-preview`, `gemini-3.1-pro-preview` + +## Billing / trial +- Fresh account: `type_trialing`, **14 days free**, `trialEnd = signup + 14d`. +- Card gate: workspace cannot start ANY thread until a card is attached via Stripe checkout (`basic` → "Type Standard" $100 credits, $50/mo after trial; today $0.00). +- Stripe live mode, merchant "Savvy Learn, Inc.", hosted at `pay.type.com`. +- BYO-codex: users can link their own ChatGPT (OpenAI device flow) — `codex` flag per account. + +## Signup anti-bot +- WorkOS Signals: detects plain headless — use stealth browser (cloakbrowser class). +- Phone: mandatory SMS (radar-challenge/send). Free SMS pools (2nd-no.com class) work; ~3 numbers/account/3days limits apply per SMS-provider account. +- Email OTP: 6-digit, any mailbox (voidash.bond class temp mail OK). + + +## Bot replies live in THREADS (verified 2026-10-13, paid trial) + +- `messages/createMessage` (top-level, `parentMessageId: null`) returns 200 and the + Sidekick agent processes it, but the reply is NOT a top-level message. +- Poll the thread instead: + `messages/getMessagesPaginated {channelId, limit, direction:"backward", parentMessageId:}` + -> bot message id looks like `msg_bot__mention`, `isBotResponse:true`, `textContent` set. +- Typical reply latency: 5-45s depending on model. +- `billing/getCardRequirement {required:true}` gates createMessage with + 403 "Add a credit card to your workspace" until a card is attached via + `billing/createCheckoutSession {tier:"standard_50"}` -> Stripe live checkout. +- Trial facts (Stripe, merchant Savvy Learn Inc): 14 days, $100 allowance + $10 credits, + then $50/mo. Card check runs AFTER billing propagation (~1-2 min after checkout success). +- Workspace is shared per EMAIL DOMAIN (voidash.bond accounts all land in one workspace + "voidash" and share billing/usage). New domain = new workspace = fresh trial. +- hCaptcha (invisible -> image challenge) protects the Stripe submit; headless automation + gets the image grid, a real browser passes with a checkbox click. +- Verified models on trial: claude-sonnet-5-5, claude-haiku-4-5, claude-opus-5-5, + gpt-6.1-sol, gemini-3-flash-preview (exact-reply test via API + via gateway). + + +## Workspace / organization / billing scoping (verified 2026-10-13) + +- `workspaces/create {name}` -> 200, creates ws under the SAME organizationId. +- Billing is ORGANIZATION-level: billing/getStatus ignores workspaceId payload and + referer slug; second workspace of the same user shares the paid trial. + Fresh trial requires a fresh ORGANIZATION = fresh account = fresh email domain. +- Workspace membership follows email domain at onboarding: all @voidash.bond signups + auto-join one workspace (shared trial + shared $ usage, private sidekick channels). +- WorkOS Signals domain blocks: govno.eu.cc / musor.eu.cc / pomoi.eu.cc (tier-3) and + voidash.cyou = "Доступ заблокирован, обратитесь в службу поддержки" at password step. + voidash.bond and t-online.de pass. +- type_reg.py: VOID_DOMAIN env selects voidash domain; `python type_reg.py 1 tonline` + registers via the 17k t-online.de IMAP pool (real ISP mail, not domain-blocked). diff --git a/captcha_keys.example.json b/captcha_keys.example.json new file mode 100644 index 0000000..195af48 --- /dev/null +++ b/captcha_keys.example.json @@ -0,0 +1,8 @@ +{ + "keys": [ + { + "label": "primary", + "key": "YOUR_2CAPTCHA_KEY" + } + ] +} \ No newline at end of file diff --git a/dashboard.py b/dashboard.py new file mode 100644 index 0000000..226292f --- /dev/null +++ b/dashboard.py @@ -0,0 +1,290 @@ +# -*- coding: utf-8 -*- +"""type-com-toolkit dashboard — stdlib only (Python 3.9+). + +Run: python dashboard.py -> http://127.0.0.1:8610 +Form: 2captcha key + 2nd-no fallback creds + temp-mail domain -> saved to creds.json (LOCAL ONLY). +Tasks: register N accounts / start gateway / radar revive -> subprocess + live log. +Results: download type_accounts.jsonl / pool.json / logs. + +[🩸 иишко](https://t.me/AlStack) +""" +import glob +import html +import json +import os +import subprocess +import sys +import threading +import time +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) if os.path.basename(HERE) == 'tools' else HERE +TOOLS = os.path.join(ROOT, 'tools') if os.path.isdir(os.path.join(ROOT, 'tools')) else HERE +CREDS = 'creds.json' +CREDS_PATH = os.path.join(ROOT, CREDS) +TASKS_DIR = os.path.join(ROOT, 'tasks') +os.makedirs(TASKS_DIR, exist_ok=True) +PORT = int(os.environ.get('DASH_PORT', '8610')) +PY = os.environ.get('PY311', sys.executable) +CHANNEL = 'https://t.me/AlStack' + +PAGE = """ +type-com-toolkit +

⚡ type-com-toolkit

+

Авторег + шлюз + radar-revive для type.com — 25 моделей (Claude / GPT / Gemini). +Ключи и креды хранятся ТОЛЬКО локально в creds.json.

+ +

1. Kredy

+
+
+
+
+
+
+
+ +

2. Задачи

+
+
+
+ требуется pool.json с живыми токенами
+
+
+
+
+
+ +

3. Статус

загрузка...
+
+ +

4. Лог задачи

+
Задачи: +
+
—
+ +

5. Результаты

загрузка...
+ + +""" + +TASK_SCRIPTS = { + 'reg': ('type_reg.py', lambda a, c: [a[0] if a else '1', c.get('void_domain') or 'voidash']), + 'gw': ('typegw.py', lambda a, c: ['8600']), + 'radar': ('radar_revive.py', lambda a, c: [a[0]] if a else []), + 'login': ('login_token.py', lambda a, c: [a[0]] if a else []), +} + + +def load_creds(): + try: + return json.load(open(CREDS_PATH, encoding='utf-8')) + except Exception: + return {} + + +def env_with_creds(c): + env = dict(os.environ) + env['PYTHONPATH'] = '' + env['PYTHONIOENCODING'] = 'utf-8' + if c.get('captcha_key'): + keys_file = os.path.join(ROOT, 'captcha_keys.json') + if not os.path.exists(keys_file): + json.dump({'keys': [{'label': 'dash', 'key': c['captcha_key']}]}, open(keys_file, 'w')) + env['CAPTCHA_KEYS_FILE'] = keys_file + if c.get('no2_email'): + env['NO2_EMAIL'] = c['no2_email'] + env['NO2_PASS'] = c.get('no2_pass', '') + if c.get('void_domain'): + env['VOID_DOMAIN'] = c['void_domain'] + if c.get('gws_email'): + gws = os.path.join(ROOT, 'gws_user.json') + json.dump({'email': c['gws_email'], 'password': c.get('gws_pass', '')}, open(gws, 'w')) + env['GWS_USER_FILE'] = gws + env['TYPE_TOOLKIT_ROOT'] = ROOT + return env + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, format, *args): + pass + + def _send(self, code, body, ctype='text/html; charset=utf-8'): + b = body.encode('utf-8') if isinstance(body, str) else body + self.send_response(code) + self.send_header('Content-Type', ctype) + self.send_header('Content-Length', str(len(b))) + self.end_headers() + self.wfile.write(b) + + def _json(self, obj, code=200): + self._send(code, json.dumps(obj, ensure_ascii=False), 'application/json; charset=utf-8') + + def _body(self): + n = int(self.headers.get('Content-Length') or 0) + return self.rfile.read(n).decode('utf-8', 'replace') if n else '' + + def do_GET(self): + u = urllib.parse.urlparse(self.path) + q = urllib.parse.parse_qs(u.query) + if u.path == '/': + self._send(200, PAGE.replace('__CH__', CHANNEL)) + elif u.path == '/api/health': + self._json({'ok': True, 'root': ROOT, 'python': sys.version.split()[0]}) + elif u.path == '/api/stack': + self._json({'html': self._stack_html()}) + elif u.path == '/api/tasks': + ts = sorted(os.listdir(TASKS_DIR), reverse=True) + out = [] + for f in ts: + if f.endswith('.log'): + tid = f[:-4] + kind = tid.split('_', 1)[1] if '_' in tid else '?' + out.append({'id': tid, 'kind': kind}) + self._json({'tasks': out[:50]}) + elif u.path == '/api/log': + tid = (q.get('id') or [''])[0] + p = os.path.join(TASKS_DIR, os.path.basename(tid) + '.log') + try: + self._json({'log': open(p, encoding='utf-8', errors='replace').read()[-40000:]}) + except Exception: + self._json({'log': ''}) + elif u.path == '/api/files': + pats = ['type_accounts.jsonl', 'pool.json', 'used_numbers.json', '_reuse_candidates.json'] + files = [p for p in pats if os.path.exists(os.path.join(ROOT, p))] + files += [os.path.basename(f) for f in glob.glob(os.path.join(TASKS_DIR, '*.log'))][-10:] + self._json({'files': files}) + elif u.path.startswith('/dl/'): + name = os.path.basename(u.path[4:]) + if name == CREDS or name in ('captcha_keys.json', 'gws_user.json', 'no2_fallback.json'): + self._json({'error': 'forbidden'}, 404) + return + for d in (ROOT, TASKS_DIR): + p = os.path.join(d, name) + if os.path.isfile(p): + self._send(200, open(p, 'rb').read(), 'application/octet-stream') + return + self._json({'error': 'not found'}, 404) + else: + self._json({'error': 'not found'}, 404) + + def do_POST(self): + u = urllib.parse.urlparse(self.path) + if u.path == '/api/creds': + try: + d = json.loads(self._body() or '{}') + old = load_creds() + for k, v in d.items(): + if v: + old[k] = v + json.dump(old, open(CREDS_PATH, 'w', encoding='utf-8'), indent=1) + self._json({'ok': True}) + except Exception as e: + self._json({'ok': False, 'error': str(e)[:200]}) + elif u.path == '/api/run': + try: + d = json.loads(self._body() or '{}') + kind = d.get('kind', '') + if kind not in TASK_SCRIPTS: + self._json({'ok': False, 'error': 'unknown kind'}) + return + script, argf = TASK_SCRIPTS[kind] + c = load_creds() + args = argf(d.get('args') or [], c) + sp = os.path.join(TOOLS, script) + if not os.path.exists(sp): + self._json({'ok': False, 'error': 'script missing: ' + script}) + return + tid = time.strftime('%H%M%S') + '_' + kind + lf = open(os.path.join(TASKS_DIR, tid + '.log'), 'w', encoding='utf-8') + subprocess.Popen([PY, sp] + [str(x) for x in args], stdout=lf, + stderr=subprocess.STDOUT, cwd=ROOT, env=env_with_creds(c)) + self._json({'ok': True, 'id': tid}) + except Exception as e: + self._json({'ok': False, 'error': str(e)[:300]}) + else: + self._json({'error': 'not found'}, 404) + + def _stack_html(self): + c = load_creds() + rows = [] + rows.append(('creds.json', 'есть' if c else 'не заполнены')) + rows.append(('2captcha key', '✓' if c.get('captcha_key') else '—')) + rows.append(('2nd-no fallback', '✓' if c.get('no2_email') else '—')) + acc = os.path.join(ROOT, 'type_accounts.jsonl') + n = 0 + if os.path.exists(acc): + n = sum(1 for _ in open(acc, encoding='utf-8', errors='replace')) + rows.append(('аккаунтов в банке', '%d' % n)) + pool = os.path.join(ROOT, 'pool.json') + npool = 0 + if os.path.exists(pool): + try: + npool = len(json.load(open(pool, encoding='utf-8'))) + except Exception: + pass + rows.append(('токенов в пуле шлюза', '%d' % npool)) + un = os.path.join(ROOT, 'used_numbers.json') + nu = 0 + if os.path.exists(un): + try: + d = json.load(open(un, encoding='utf-8')) + nu = len(d) + except Exception: + pass + rows.append(('использованных номеров', str(nu))) + return '' + ''.join('' % (html.escape(k), v) for k, v in rows) + '
%s%s
' + + +def main(): + port = PORT + srv = None + for port in range(PORT, PORT + 20): + try: + srv = ThreadingHTTPServer(('127.0.0.1', port), Handler) + break + except OSError: + continue + if srv is None: + print('no free port in range', PORT, PORT + 20, flush=True) + sys.exit(1) + print('dashboard on http://127.0.0.1:%d' % port, flush=True) + srv.serve_forever() + + +if __name__ == '__main__': + main() diff --git a/gpt_cands.example.json b/gpt_cands.example.json new file mode 100644 index 0000000..1f1ec5e --- /dev/null +++ b/gpt_cands.example.json @@ -0,0 +1,7 @@ +[ + { + "email": "user@t-online.de", + "password": "chatgpt_password", + "mail_password": "imap_password_if_different" + } +] \ No newline at end of file diff --git a/gws_user.example.json b/gws_user.example.json new file mode 100644 index 0000000..b54cdae --- /dev/null +++ b/gws_user.example.json @@ -0,0 +1 @@ +{"email": "your.viktor@email.com", "password": "your-google-password"} \ No newline at end of file diff --git a/no2_fallback.example.json b/no2_fallback.example.json new file mode 100644 index 0000000..aa83117 --- /dev/null +++ b/no2_fallback.example.json @@ -0,0 +1 @@ +{"email": "your@2no-account.email", "pass": "your-password"} \ No newline at end of file diff --git a/pool.example.json b/pool.example.json new file mode 100644 index 0000000..5e156a9 --- /dev/null +++ b/pool.example.json @@ -0,0 +1,8 @@ +[ + { + "email": "acc@voidash.bond", + "password": "x", + "token": "***", + "channelId": "ch_xxx" + } +] \ No newline at end of file diff --git a/providers/__init__.py b/providers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/providers/captcha.py b/providers/captcha.py new file mode 100644 index 0000000..06764bb --- /dev/null +++ b/providers/captcha.py @@ -0,0 +1,168 @@ +"""Captcha solvers. YesCaptcha primary (balance verified 2026-09-19). +Solves: reCAPTCHA v2, Arkose FunCaptcha, Turnstile. Robust polling with retries.""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import os +import time + +import httpx + +API = "https://api.yescaptcha.com" +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36" + +_ENV_FILE = str(_d("Desktop/_PROJECTS/авторег проект/.env")) + + +def _load_key(): + k = os.environ.get("YESCAPTCHA_KEY", "") + if k: + return k + try: + with open(_ENV_FILE, encoding="utf-8", errors="ignore") as f: + for line in f: + if line.startswith("YESCAPTCHA_"): + return line.split("=", 1)[1].strip().strip('"') + except OSError: + pass + return "" + + +class YesCaptcha: + def __init__(self, key=None): + self.key = key or _load_key() + if not self.key: + raise RuntimeError("no yescaptcha key") + self.client = httpx.Client(timeout=60) + + def _post(self, method, payload, retries=6): + payload["clientKey"] = self.key + last_err = None + for i in range(retries): + try: + r = self.client.post(API + "/" + method, json=payload) + d = r.json() + except Exception as e: + last_err = e + time.sleep(3 + i * 2) + continue + ec = str(d.get("errorCode", "")) + if d.get("errorId"): + # transient proxy errors during polling: keep trying + if method == "getTaskResult" and ("PROXY" in ec or "TIMEOUT" in ec): + last_err = RuntimeError(f"{method}: {ec}") + time.sleep(4 + i * 2) + continue + raise RuntimeError(f"yescaptcha {method}: {ec} {d.get('errorDescription')}") + return d + raise RuntimeError(f"yescaptcha {method}: exhausted retries: {last_err}") + + def balance(self): + return self._post("getBalance", {})["balance"] + + def _solve(self, task, timeout=240, poll=6): + task_id = self._post("createTask", {"task": task})["taskId"] + print(f"[yescaptcha] task {task_id} created") + deadline = time.time() + timeout + while time.time() < deadline: + try: + d = self._post("getTaskResult", {"taskId": task_id}, retries=8) + except RuntimeError as e: + print("[yescaptcha] poll retry:", e) + time.sleep(poll) + continue + if d["status"] == "ready": + return d["solution"] + time.sleep(poll) + raise TimeoutError(f"captcha task {task_id} not solved in {timeout}s") + + # ---- reCAPTCHA v2 ---- + def recaptcha_v2(self, sitekey, pageurl, proxy=None): + task = {"type": "RecaptchaV2TaskProxyless", "websiteURL": pageurl, "websiteKey": sitekey} + if proxy: + task = {"type": "RecaptchaV2Task", "websiteURL": pageurl, "websiteKey": sitekey, + "proxyType": "http", "proxyAddress": proxy["host"], "proxyPort": proxy["port"], + "proxyLogin": proxy.get("user", ""), "proxyPassword": proxy.get("pass", ""), + "userAgent": UA} + return self._solve(task)["gRecaptchaResponse"] + + # ---- Arkose FunCaptcha (gitlab signup + phone verify) ---- + def funcaptcha(self, public_key, surl="https://gitlab-api.arkoselabs.com", pageurl=None, data=None, proxy_url=None): + task = {"type": "FunCaptchaTaskProxyless", "websiteURL": pageurl or surl, + "websitePublicKey": public_key, "funcaptchaApiJSSubdomain": surl, + "userAgent": UA} + if data: + task["data"] = data + if proxy_url: + hp = proxy_url.split("//", 1)[-1] + host, _, port = hp.partition(":") + task["type"] = "FunCaptchaTask" + task.update({"proxyType": "http", "proxyAddress": host, + "proxyPort": int(port or 80), "proxyLogin": "", "proxyPassword": ""}) + return self._solve(task, timeout=300)["token"] + + # ---- Cloudflare Turnstile ---- + def turnstile(self, sitekey, pageurl, action=None, proxy_url=None): + if proxy_url: + hp = proxy_url.split("//", 1)[-1] + creds = "" + if "@" in hp: + creds, hp = hp.rsplit("@", 1) + host, _, port = hp.partition(":") + user, _, pw = creds.partition(":") + task = {"type": "TurnstileTask", "websiteURL": pageurl, "websiteKey": sitekey, + "proxyType": "http", "proxyAddress": host, "proxyPort": int(port or 80), + "proxyLogin": user, "proxyPassword": pw} + else: + task = {"type": "TurnstileTaskProxyless", "websiteURL": pageurl, "websiteKey": sitekey} + if action: + task["metadata"] = {"action": action} + return self._solve(task)["token"] + + +class ManualCaptcha: + def recaptcha_v2(self, sitekey, pageurl, proxy=None): + print(f"[MANUAL CAPTCHA] recaptcha sitekey={sitekey}") + return input("paste g-recaptcha-response: ").strip() + + def funcaptcha(self, public_key, surl=None, pageurl=None, data=None, proxy_url=None): + print(f"[MANUAL CAPTCHA] funcaptcha pubkey={public_key}") + return input("paste arkose token: ").strip() + + def turnstile(self, sitekey, pageurl): + print(f"[MANUAL CAPTCHA] turnstile sitekey={sitekey}") + return input("paste turnstile token: ").strip() + + +def get_solver(): + try: + return YesCaptcha() + except RuntimeError: + return ManualCaptcha() diff --git a/providers/secondno.py b/providers/secondno.py new file mode 100644 index 0000000..32efba8 --- /dev/null +++ b/providers/secondno.py @@ -0,0 +1,277 @@ +"""2nd-no.com (2nr.pl) free Polish SMS numbers — FULL AUTOMATION. +Flow: register(tempmail) -> confirm email -> login -> turnstile(YesCaptcha) -> reserve number -> poll SMS. +API: POST https://2no.pl/ JSON-RPC, auth x-auth-token (sessionStorage 2NR-TOKEN). +Free: 2 accounts/email domain?, number_limit=3 per account, 3-day validity, extended on SMS receipt. +Verified live 2026-09-20: number +48 729756039 reserved, success:true.""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import json +import random +import re +import string +import time + +import httpx +from playwright.sync_api import sync_playwright + +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36") +TM_BASE = "https://api.tempmail.lol/v2" +SITEKEY = "0x4AAAAAAAh6YYTPTzEcN3Ep" # from 2nd bundle index-ff34328d.js +API = "https://2no.pl/" +STATE_FILE = str(_w("tmp/glar_stage/2ndno_state.json")) + + +class TempMail: + def __init__(self): + self.c = httpx.Client(timeout=30) + self.address = None + self.token = None + + def create(self): + d = self.c.post(TM_BASE + "/inbox/create").json() + self.address, self.token = d["address"], d["token"] + return self.address + + def wait_email(self, sender=None, timeout=180, poll=5): + deadline = time.time() + timeout + while time.time() < deadline: + r = self.c.get(TM_BASE + "/inbox", params={"token": self.token}) + if r.status_code == 200: + for m in r.json().get("emails", []): + if sender is None or sender.lower() in (str(m.get("from", "")) + str(m.get("subject", ""))).lower(): + return m + time.sleep(poll) + return None + + +class SecondNo: + """Browser-driven 2nd-no.com client (Cloudflare only passes inside browser).""" + + def __init__(self, solver=None): + self._pw = None + self._browser = None + self._pg = None + self.solver = solver + + # ---- lifecycle ---- + def _start(self): + if self._pg is None: + self._pw = sync_playwright().start() + self._browser = self._pw.chromium.launch(headless=False, channel="chrome", args=["--no-sandbox", "--disable-blink-features=AutomationControlled", "--window-position=2400,2400"]) + ctx = self._browser.new_context(user_agent=UA, locale="en-US") + self._pg = ctx.new_page() + self._pg.add_init_script("Object.defineProperty(navigator,'webdriver',{get:()=>undefined})") + return self._pg + + def close(self): + try: + self._browser.close() + except Exception: + pass + try: + self._pw.stop() + except Exception: + pass + self._pg = None + + # ---- api via browser context ---- + def _call(self, id_, query=None): + body = {"id": id_} + if query is not None: + body["query"] = query + pg = self._start() + res = pg.evaluate("""async (body) => { + const tok = sessionStorage.getItem('2NR-TOKEN'); + const r = await fetch('https://2no.pl/', {method:'POST', + headers:{'Content-Type':'application/json','x-auth-token':tok||''}, + body: JSON.stringify(body)}); + return await r.text(); + }""", body) + try: + return json.loads(res) + except Exception: + return {"raw": res[:200]} + + # ---- steps ---- + def register(self, password=None): + pg = self._start() + tm = TempMail() + email = tm.create() + pwd = password or ("Nx" + "".join(random.choices(string.ascii_letters, k=8)) + "7!q") + pg.goto("https://2nd-no.com/auth/register", wait_until="domcontentloaded", timeout=60000) + pg.wait_for_timeout(3500) + ok = pg.evaluate("""(args) => { + const setVal = (el, v) => { const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), 'value').set; + setter.call(el, v); el.dispatchEvent(new Event('input', {bubbles: true})); + el.dispatchEvent(new Event('change', {bubbles: true})); }; + const inputs = Array.from(document.querySelectorAll('input')); + const txt = inputs.find(i => i.type === 'text' || i.type === 'email'); + const pws = inputs.filter(i => i.type === 'password'); + const cb = inputs.find(i => i.type === 'checkbox'); + if (!txt || pws.length < 2) return 'inputs missing'; + setVal(txt, args[0]); setVal(pws[0], args[1]); setVal(pws[1], args[1]); + if (cb && !cb.checked) cb.click(); + return 'ok'; + }""", [email, pwd]) + if ok != "ok": + raise RuntimeError(f"register fill failed: {ok}") + pg.evaluate("() => document.querySelector('button[type=submit]').click()") + pg.wait_for_timeout(6000) + # confirm email + msg = tm.wait_email(sender="2nr", timeout=180) + if not msg: + msg = tm.wait_email(timeout=60) + link = None + if msg: + body = (msg.get("body") or "") + (msg.get("html") or "") + links = re.findall(r"https?://[^\s\"'<>]+", body) + link = next((l for l in links if "create-account" in l or "confirm" in l), None) + if not link: + raise RuntimeError("no confirmation link") + pg.goto(link, wait_until="domcontentloaded", timeout=60000) + pg.wait_for_timeout(3000) + self.creds = {"email": email, "password": pwd} + return self.creds + + def login(self, email, password): + pg = self._start() + pg.goto("https://2nd-no.com/auth/login", wait_until="domcontentloaded", timeout=60000) + pg.wait_for_timeout(3000) + pg.evaluate("""(args) => { + const setVal = (el, v) => { const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), 'value').set; + setter.call(el, v); el.dispatchEvent(new Event('input', {bubbles: true})); + el.dispatchEvent(new Event('change', {bubbles: true})); }; + const inputs = Array.from(document.querySelectorAll('input')); + setVal(inputs.find(i => i.type === 'email' || i.type === 'text'), args[0]); + setVal(inputs.find(i => i.type === 'password'), args[1]); + }""", [email, password]) + pg.wait_for_timeout(500) + pg.evaluate("() => document.querySelector('button[type=submit]').click()") + pg.wait_for_url("**/app/**", timeout=25000) + pg.wait_for_timeout(3000) + self.creds = {"email": email, "password": password} + return True + + def get_number(self): + """Reserve a free Polish number. Solves Turnstile via YesCaptcha.""" + rnd = self._call(310) + result = rnd.get("result") or [] + if not result: + raise RuntimeError(f"no free number: {str(rnd)[:120]}") + num_id, number = result[0]["id"], result[0]["number"] + ts = "" + if rnd.get("captcha") == "turnstile" and self.solver: + ts = self.solver.turnstile(SITEKEY, "https://2nd-no.com/") + res = self._call(301, {"number_id": num_id, "name": "gl", "color": "Red", + "right_to_transfer_number": True, "response_key": ts}) + if not res.get("success"): + raise RuntimeError(f"reserve failed: {str(res)[:150]}") + my = self._call(311, {"offset": 0, "limit": 10}) + entry = (my.get("result") or [{}])[0] + out = {"number": number, "full": "+48" + number, "number_id": num_id, + "user_number_id": entry.get("id"), "expires": entry.get("reservation_to")} + self._save(out) + return out + + def _save(self, info): + state = {} + try: + state = json.load(open(STATE_FILE, encoding="utf-8")) + except Exception: + state = {"accounts": []} + acc = dict(self.creds or {}) + acc.update(info) + state.setdefault("accounts", []).append(acc) + json.dump(state, open(STATE_FILE, "w", encoding="utf-8"), indent=1) + + def read_sms(self, phone, number_id, timeout=300, poll=8): + """Poll SMS for a reserved number. NOTE: 2no.pl API 415 needs phone=STRING and + number_id=INT; actual messages arrive under badges.messages (data.messages stays empty).""" + deadline = time.time() + timeout + while time.time() < deadline: + d = self._call(415, {"phone": str(phone), "number_id": int(number_id), + "limit": 25, "offset": 0}) + msgs = [] + for b in (d.get("badges") or {}).get("messages") or []: + msgs.extend(b.get("messages") or []) + msgs.extend((d.get("data", {}) or {}).get("messages") or []) + msgs.extend(d.get("result") or []) + if msgs: + return msgs + time.sleep(poll) + return [] + + def wait_otp(self, phone, number_id, timeout=300, poll=8, digits=(4, 8)): + """Wait for first SMS and extract the OTP code (GitLab codes are 6-7 digits).""" + deadline = time.time() + timeout + while time.time() < deadline: + for m in self.read_sms(phone, number_id, timeout=poll * 2): + text = m.get("text") or m.get("body") or "" + mm = re.search(r"code is (\d{4,8})", text) + if mm: + return mm.group(1), text + for n in digits: + mm = re.search(rf"\b(\d{{{n}}})\b", text) + if mm: + return mm.group(1), text + time.sleep(poll) + return None, None + + +def full_cycle(count=1, solver=None): + """Register fresh account(s) and grab number(s). Returns list of dicts.""" + if solver is None: + import os + import sys + sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + from providers.captcha import get_solver + solver = get_solver() + out = [] + for _ in range(count): + s = SecondNo(solver=solver) + try: + creds = s.register() + s.login(creds["email"], creds["password"]) + s.get_number() + out.append({**creds, **json.load(open(STATE_FILE))["accounts"][-1]}) + except Exception as e: + out.append({"error": str(e)[:150]}) + finally: + s.close() + return out + + +if __name__ == "__main__": + import sys + n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + for r in full_cycle(n): + print(json.dumps(r, ensure_ascii=False)) diff --git a/radar_creds.example.json b/radar_creds.example.json new file mode 100644 index 0000000..48e5d78 --- /dev/null +++ b/radar_creds.example.json @@ -0,0 +1 @@ +[{"email": "your-2no-account1@tempmail.com", "pass": "pass1"}, {"email": "acct2@tempmail.com", "pass": "pass2"}] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..119c853 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +cloakbrowser +httpx +playwright +requests +# after install: python -m playwright install chromium && cloakbrowser fetch (if prompted) diff --git a/tools/cancel_portal.py b/tools/cancel_portal.py new file mode 100644 index 0000000..dfcd8e5 --- /dev/null +++ b/tools/cancel_portal.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +"""cancel_portal.py — auto-click "Cancel plan" on Stripe customer portal.""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import os, re, sys, time +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +URL = open(str(_w("tmp/type_autoreg/cp_url.txt"))).read().strip() +log = lambda *a: print(*a, flush=True) +with cloakbrowser.launch(headless=True) as b: + pg = b.new_page() + pg.goto(URL, wait_until='domcontentloaded', timeout=90000) + for s in range(15): + pg.wait_for_timeout(5000) + body = re.sub(r'\s+', ' ', pg.evaluate('() => document.body.innerText'))[:600] + url = pg.url + log(f"--- s{s} {url[:110]}") + log(" body:", body[:350]) + pg.screenshot(path=str(_w("tmp/type_autoreg/cp_%d.png")) % s) + if 'cancel' not in body.lower() and 'manage' not in body.lower() and 'status' not in body.lower() and s > 3: + log("NO CANCEL CONTEXT"); break + # click cancel-related button + clicked = pg.evaluate("""() => { + const re = /cancel.*plan|отменить.*план|cancel.*subscription|отменить.*подписк|end.*subscription|закончить|отменить/i; + const btn = [...document.querySelectorAll('button,a')].filter(e=>e.offsetParent!==null) + .find(x=>re.test((x.innerText||'').trim())); + if (btn) { btn.click(); return (btn.innerText||'').trim().slice(0,50); } + return null; }""") + log(" clicked:", clicked) + # if a confirmation dialog appears, click the confirm button + pg.evaluate("""() => { + const ok = /yes|cancel|confirm|да|отменит|подтвердит|продолжит|ok/i; + const btn = [...document.querySelectorAll('button')].filter(e=>e.offsetParent!==null) + .find(x=>ok.test((x.innerText||'').trim())); + if (btn) { btn.click(); return (btn.innerText||'').trim().slice(0,50); } + return null; }""") + if not clicked: break + log("FINAL url:", pg.url[:150]) \ No newline at end of file diff --git a/tools/checkout_fill2.py b/tools/checkout_fill2.py new file mode 100644 index 0000000..85ece9c --- /dev/null +++ b/tools/checkout_fill2.py @@ -0,0 +1,108 @@ +# -*- coding: utf-8 -*- +"""checkout_fill2.py — dump field attrs, fill card + UA billing address, submit, report.""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import json, os, re, sys, time +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +HERE = os.path.dirname(os.path.abspath(__file__)) +d = json.load(open(str(_d("tmp/aws_kiro/card.json","CARD_JSON")), encoding='utf-8')) +if isinstance(d, list): d = d[0] +PAN = str(d.get('pan') or d.get('number') or d.get('card')) +EXP = str(d.get('exp') or d.get('expiry')) +CVC = str(d.get('cvc') or d.get('cvv')) +NAME = str(d.get('name') or d.get('holder') or 'Nik Lang') or 'Nik Lang' +URL = open(os.path.join(HERE, 'ck_url.txt')).read().strip() + +out = {} +with cloakbrowser.launch(headless=True) as b: + pg = b.new_page() + pg.goto(URL, wait_until='domcontentloaded', timeout=90000) + pg.wait_for_timeout(14000) + # dump all form controls + attrs = pg.evaluate("""() => [...document.querySelectorAll('input,select')].map(e=>({ + tag:e.tagName, id:e.id, name:e.name, ac:e.getAttribute('autocomplete'), + ph:e.placeholder||'', type:e.type||'', vis:e.offsetParent!==null}))""") + out['controls'] = [a for a in attrs if a.get('vis')] + print(json.dumps(out['controls'], ensure_ascii=False)[:2000], flush=True) + + def fill(sels, val): + for s in sels: + try: + loc = pg.locator(s).first + if loc.is_visible(timeout=1200): + loc.fill(val) + return s + except Exception: + pass + return None + + out['f_pan'] = fill(['input[name="cardnumber"]', 'input[autocomplete="cc-number"]'], PAN) + out['f_exp'] = fill(['input[name="exp-date"]', 'input[autocomplete="cc-exp"]'], EXP) + out['f_cvc'] = fill(['input[name="cvc"]', 'input[autocomplete="cc-csc"]'], CVC) + out['f_name'] = fill(['input[name="name"]', 'input[autocomplete="cc-name"]'], NAME) + pg.wait_for_timeout(1500) + # UA billing address (card BIN = UA) + out['f_line1'] = fill(['input#billingAddressLine1', 'input[name="billingAddressLine1"]', 'input[autocomplete="billing address-line1"]'], 'Khreshchatyk Street 22') + out['f_city'] = fill(['input#billingLocality', 'input[name="billingLocality"]'], 'Kyiv') + out['f_zip'] = fill(['input#billingPostalCode', 'input[name="billingPostalCode"]'], '01001') + # oblast select + try: + sel = pg.locator('select#billingAdministrativeArea').first + if sel.is_visible(timeout=1000): + opts = sel.locator('option').all_inner_texts() + kyiv = [o for o in opts if 'київ' in o.lower() or 'киев' in o.lower() or 'kyiv' in o.lower() or 'kiev' in o.lower()] + if kyiv: + sel.select_option(label=kyiv[0]); out['f_oblast'] = kyiv[0] + else: + out['oblast_opts'] = opts[:12] + except Exception as e: + out['oblast_err'] = str(e)[:80] + pg.wait_for_timeout(1500) + pg.screenshot(path=os.path.join(HERE, 'ck2_filled.png')) + # submit + try: + pg.locator('button[type="submit"], .SubmitButton').first.click() + out['clicked'] = True + except Exception as e: + out['clicked'] = False; out['click_err'] = str(e)[:120] + pg.wait_for_timeout(30000) + out['final_url'] = pg.url[:150] + body = pg.evaluate("() => document.body.innerText") + out['final_body'] = re.sub(r'\n{2,}', ' | ', body)[:900] + # 3DS / error detection + low = body.lower() + out['has_3ds'] = bool(re.search(r'3d secure|підтверд|подтвержд|verify your identity|your bank', low)) + out['has_error'] = bool(re.search(r'ваша карта|card was declined|не прийнято|отклонена|declined|error', low)) + pg.screenshot(path=os.path.join(HERE, 'ck2_after.png')) +s = json.dumps(out, ensure_ascii=False, indent=1) +print(s.replace(PAN, PAN[:6] + '***' + PAN[-4:])[:2500]) diff --git a/tools/checkout_hcap.py b/tools/checkout_hcap.py new file mode 100644 index 0000000..57c5dd8 --- /dev/null +++ b/tools/checkout_hcap.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +"""checkout_hcap.py — full flow: fill card+address, submit, solve hCaptcha checkbox click, report.""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import json, os, re, sys, time +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +HERE = os.path.dirname(os.path.abspath(__file__)) +d = json.load(open(str(_d("tmp/aws_kiro/card.json","CARD_JSON")), encoding='utf-8')) +if isinstance(d, list): d = d[0] +PAN = str(d.get('pan') or d.get('number') or d.get('card')) +EXP = str(d.get('exp') or d.get('expiry')) +CVC = str(d.get('cvc') or d.get('cvv')) +NAME = str(d.get('name') or d.get('holder') or 'Nik Lang') or 'Nik Lang' +URL = open(os.path.join(HERE, 'ck_url.txt')).read().strip() +out = {} + +with cloakbrowser.launch(headless=True) as b: + pg = b.new_page() + pg.goto(URL, wait_until='domcontentloaded', timeout=90000) + pg.wait_for_timeout(13000) + # reject cookie banner if present + try: + btn = pg.get_by_text('Reject All', exact=True).first + if btn.is_visible(timeout=1500): btn.click(); pg.wait_for_timeout(800) + except Exception: pass + + def fill(sel, val): + try: + loc = pg.locator(sel).first + if loc.is_visible(timeout=1500): + loc.fill(val); return True + except Exception: pass + return False + + fill('input[autocomplete="cc-number"]', PAN) + fill('input[autocomplete="cc-exp"]', EXP) + fill('input[autocomplete="cc-csc"]', CVC) + fill('input[autocomplete="cc-name"]', NAME) + pg.wait_for_timeout(1200) + fill('input#billingAddressLine1', 'Khreshchatyk Street 22') + fill('input#billingLocality', 'Kyiv') + fill('input#billingPostalCode', '01001') + try: + sel = pg.locator('select#billingAdministrativeArea').first + if sel.is_visible(timeout=1000): + opts = sel.locator('option').all_inner_texts() + ky = [o for o in opts if 'kyiv' in o.lower() or 'київ' in o.lower() or 'киев' in o.lower()] + if ky: sel.select_option(label=ky[0]) + except Exception: pass + pg.wait_for_timeout(1200) + pg.locator('button[type="submit"], .SubmitButton').first.click() + out['submitted'] = True + pg.wait_for_timeout(8000) + + # find hCaptcha iframe + click checkbox + clicked = False + for attempt in range(4): + frames = [f for f in pg.frames if 'hcaptcha' in (f.url or '')] + out.setdefault('hc_frames', []).extend([f.url[:100] for f in frames]) + for f in frames: + for s in ['input[type=checkbox]', 'div[role=checkbox]', 'label', '#anchor', 'div[tabindex]']: + try: + el = f.query_selector(s) + if el and el.is_visible(): + box = el.bounding_box() + if box: + pg.mouse.move(box['x'] + box['width']/2 + 3, box['y'] + box['height']/2 + 2, steps=12) + pg.wait_for_timeout(350) + pg.mouse.click(box['x'] + box['width']/2 + 3, box['y'] + box['height']/2 + 2) + clicked = True + out['hc_click'] = f"{s} via {f.url[:40]}" + break + except Exception as e: + pass + if clicked: break + if clicked: break + pg.wait_for_timeout(4000) + out['hc_clicked'] = clicked + pg.wait_for_timeout(25000) + # challenge (image grid)? + ch = False + for f in pg.frames: + if 'hcaptcha' in (f.url or ''): + try: + if f.query_selector('.challenge-stage, [class*=challenge]'): ch = True + except Exception: pass + out['image_challenge'] = ch + out['final_url'] = pg.url[:130] + body = pg.evaluate("() => document.body.innerText") + out['final_body'] = re.sub(r'\n{2,}', ' | ', body)[:700] + low = body.lower() + out['has_3ds'] = bool(re.search(r'3d secure|підтверд|подтвержд|your bank|банк', low)) + pg.screenshot(path=os.path.join(HERE, 'ck3_after.png')) +s = json.dumps(out, ensure_ascii=False, indent=1) +print(s.replace(PAN, PAN[:6] + '***' + PAN[-4:])[:2600]) diff --git a/tools/checkout_probe.py b/tools/checkout_probe.py new file mode 100644 index 0000000..288e8fd --- /dev/null +++ b/tools/checkout_probe.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- +"""Open type.com Stripe checkout URL, dump page state, optionally fill+submit a card. +Usage: python checkout_probe.py [--card PAN EXP MM/YYYY CVV NAME] [--submit] +""" +import sys, json, time, re +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +URL = sys.argv[1] +card = None +submit = '--submit' in sys.argv +if '--card' in sys.argv: + i = sys.argv.index('--card') + card = sys.argv[i+1:i+6] # pan exp cvv name (exp MM/YY or MM/YYYY) + +out = {'url': URL} +with cloakbrowser.launch(headless=True) as b: + pg = b.new_page() + pg.goto(URL, wait_until='domcontentloaded', timeout=90000) + pg.wait_for_timeout(12000) + out['title'] = pg.title() + body = pg.evaluate("() => document.body.innerText") + out['body'] = re.sub(r'\n{2,}', ' | ', body)[:1200] + # find amount lines + out['amounts'] = re.findall(r'(?:US?D|\$|€)\s?[\d.,]+', body)[:10] + pg.screenshot(path='ck_probe.png') + if card: + pan, exp, cvv, name = card[0], card[1], card[2], card[3] + # Stripe fields often in iframes + frames = pg.frames + out['frames'] = [f.url[:80] for f in frames] + def fill_in_frames(selector, value): + for f in frames: + try: + loc = f.locator(selector).first + if loc.is_visible(timeout=1500): + loc.fill(value) + return f.url[:60] + except Exception: + pass + try: + pg.fill(selector, value, timeout=3000) + return 'main' + except Exception: + return None + out['f_number'] = fill_in_frames('input[name="cardnumber"], input[autocomplete="cc-number"]', pan) + out['f_exp'] = fill_in_frames('input[name="exp-date"], input[autocomplete="cc-exp"]', exp) + out['f_cvc'] = fill_in_frames('input[name="cvc"], input[autocomplete="cc-csc"]', cvv) + out['f_name'] = fill_in_frames('input[name="name"], input[autocomplete="cc-name"]', name) + # country/billing + for sel, val in [('input[name="addressLine1"]', 'Friedrichstrasse 123'), + ('input[name="locality"]', 'Berlin'), + ('input[name="postal_code"], input[name="postalCode"]', '10117')]: + fill_in_frames(sel, val) + pg.wait_for_timeout(1500) + pg.screenshot(path='ck_filled.png') + if submit: + clicked = False + for f in frames: + try: + btn = f.locator('button[type="submit"], .SubmitButton').first + if btn.is_visible(timeout=1500): + btn.click(); clicked = True; break + except Exception: + pass + if not clicked: + try: + pg.click('button[type="submit"], .SubmitButton'); clicked = True + except Exception: + pass + out['clicked'] = clicked + pg.wait_for_timeout(25000) + out['final_url'] = pg.url + fb = pg.evaluate("() => document.body.innerText") + out['final_body'] = re.sub(r'\n{2,}', ' | ', fb)[:800] + pg.screenshot(path='ck_after.png') +print(json.dumps(out, ensure_ascii=False, indent=1)) diff --git a/tools/codex_link2.py b/tools/codex_link2.py new file mode 100644 index 0000000..3a348f0 --- /dev/null +++ b/tools/codex_link2.py @@ -0,0 +1,354 @@ +# -*- coding: utf-8 -*- +"""codex_link2.py — robust BYO-codex link: persistent ChatGPT storage-state + type.com device flow. +Phase 1: login to ChatGPT (IMAP code), save gpt_state_.json +Phase 2: type.com startCodexDeviceAuth -> open vurl WITH saved state -> code -> approve +Phase 3: getCodexAuth + BYO createMessage card-gate test +Usage: python codex_link2.py [skip_login] +""" +import sys, json, time, os, random, re, urllib.request, urllib.error +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +HERE = os.path.dirname(os.path.abspath(__file__)) +IDX = int(sys.argv[1]) if len(sys.argv) > 1 else 0 +SKIP_LOGIN = len(sys.argv) > 2 and sys.argv[2] == 'skip_login' +STATE = os.path.join(HERE, f'gpt_state_{IDX}.json') + +POOL = json.load(open(os.path.join(HERE, 'pool.json'), encoding='utf-8')) +ACC_TYPE = POOL[0] +TOK = ACC_TYPE['token'] +B32 = '0123456789abcdefghjkmnpqrstvwxyz' + +def msg_ulid(): + ts = int(time.time() * 1000) + t = '' + for _ in range(10): + t = B32[ts % 32] + t + ts //= 32 + if t[0] not in '01234567': + t = str(int(t[0], 32) % 8) + t[1:] + return 'msg_' + t + ''.join(random.choice(B32) for _ in range(16)) + +def call(ep, payload, lim=1500): + req = urllib.request.Request('https://api.type.com/api/orpc/' + ep, data=json.dumps({'json': payload}).encode(), headers={ + 'content-type': 'application/json', 'authorization': TOK, + 'origin': 'https://type.com', 'referer': 'https://type.com/', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, r.read().decode('utf-8', 'ignore')[:lim] + except urllib.error.HTTPError as e: + return e.code, e.read().decode('utf-8', 'ignore')[:lim] + except Exception as e: + return -1, str(e)[:300] + +def imap_openai_code(email, mail_pw, wait_s=110): + import imaplib + import email as emaillib + from email.utils import parsedate_to_datetime + import datetime as _dt + t0 = time.time() + while time.time() - t0 < wait_s: + try: + M = imaplib.IMAP4_SSL('secureimap.t-online.de', 993) + M.login(email, mail_pw) + M.select('INBOX') + M.noop() + typ, data = M.search(None, 'ALL') + ids = data[0].split()[-10:] if data and data[0] else [] + for num in reversed(ids): + typ, md = M.fetch(num, '(BODY.PEEK[])') + if not (md and md[0]): continue + msg = emaillib.message_from_bytes(md[0][1]) + if 'openai' not in (msg.get('From') or '').lower(): continue + try: + dt = parsedate_to_datetime(msg.get('Date')) + if dt.tzinfo is None: dt = dt.replace(tzinfo=_dt.timezone.utc) + if (_dt.datetime.now(_dt.timezone.utc) - dt).total_seconds() > 360: continue + except Exception: pass + texts = [] + for part in msg.walk(): + if part.get_content_type() == 'text/plain': + try: texts.append(part.get_payload(decode=True).decode('utf-8', 'ignore')) + except Exception: pass + if not texts: + for part in msg.walk(): + if part.get_content_type() == 'text/html': + try: texts.append(re.sub(r'<[^>]+>', ' ', part.get_payload(decode=True).decode('utf-8', 'ignore'))) + except Exception: pass + for txt in texts: + m = re.search(r'(?:code|код)[^\d\n]{0,40}(\d{6})', txt, re.I) + if not m: + cand = re.findall(r'\b(\d{6})\b', txt) + if len(set(cand)) == 1: m = type('X', (), {'group': lambda s, i, c=cand[0]: c})() + if m: + try: M.logout() + except Exception: pass + print(' code:', m.group(1), 'subj:', str(msg.get('Subject'))[:40], flush=True) + return m.group(1) + try: M.logout() + except Exception: pass + except Exception as e: + print(' imap err:', str(e)[:100], flush=True) + time.sleep(10) + return None + +def gpt_login(browser, acc): + """login to chatgpt, save state. returns True on success.""" + pg = browser.new_page() + try: + pg.goto('https://auth.openai.com/log-in', wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(6000) + for sel in ['button:has-text("Войти")', 'a:has-text("Войти")', 'button:has-text("Log in")', 'a:has-text("Log in")', 'button:has-text("Sign in")', 'a:has-text("Sign in")']: + try: + pg.locator(sel).first.click(timeout=3000) + print(' interstitial:', sel, flush=True) + pg.wait_for_timeout(4000) + break + except Exception: pass + em = pg.locator('input[name="email"], input[type="email"], #username').first + try: + em.wait_for(timeout=20000) + except Exception: + pg.goto('https://auth.openai.com/log-in', wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(8000) + em.wait_for(timeout=45000) + em.click(); em.type(acc['email'], delay=80) + pg.wait_for_timeout(800) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + # wait for password field or email-verification + t0 = time.time() + mode = None + while time.time() - t0 < 50: + if 'email-verification' in pg.url: mode = 'code'; break + try: + if pg.locator('input[type="password"]').first.is_visible(timeout=2000): mode = 'pass'; break + except Exception: pass + if 'chatgpt.com' in pg.url: mode = 'already'; break + pg.wait_for_timeout(1500) + print(' login mode:', mode, pg.url, flush=True) + if mode == 'pass': + pwf = pg.locator('input[type="password"]').first + pwf.click(); pwf.type(acc['password'], delay=70) + pg.wait_for_timeout(500) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")', 'button:has-text("Войти")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + pg.wait_for_timeout(12000) + elif mode == 'code': + c6 = imap_openai_code(acc['email'], acc.get('mail_password') or acc['password']) + if not c6: + print(' NO CODE', flush=True); return False + cinp = pg.locator('input:visible').first + cinp.wait_for(timeout=10000) + cinp.click(); cinp.type(c6, delay=130) + pg.wait_for_timeout(800) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + pg.wait_for_timeout(14000) + # verify: reach chatgpt.com + ok = False + for _ in range(6): + if 'chatgpt.com' in pg.url: ok = True; break + try: + pg.goto('https://chatgpt.com/', wait_until='domcontentloaded', timeout=45000) + pg.wait_for_timeout(7000) + except Exception: pass + print(' logged in:', ok, pg.url, flush=True) + if ok: + try: + pg.context.storage_state(path=STATE) + print(' state saved:', STATE, flush=True) + except Exception as e: + print(' state save err:', str(e)[:100], flush=True) + return ok + except Exception as e: + print(' login exc:', str(e)[:200], flush=True) + return False + finally: + try: pg.close() + except Exception: pass + +def main(): + cands = json.load(open(os.path.join(HERE, 'gpt_cands.json'), encoding='utf-8')) + acc = cands[IDX] + print('gpt account:', acc['email'], flush=True) + + logged = False + with cloakbrowser.launch(headless=True) as browser: + if SKIP_LOGIN and os.path.exists(STATE): + logged = True + print('skip_login: using', STATE, flush=True) + else: + logged = gpt_login(browser, acc) + if not logged: + print('RESULT: LOGIN_FAILED', flush=True); sys.exit(2) + + # start device auth on type.com side + import datetime + code = vurl = sid = None + for attempt in range(10): + st, bd = call('usersAuth/startCodexDeviceAuth', {}) + if st != 200: + print('startCodexDeviceAuth:', st, bd[:200], flush=True); time.sleep(10); continue + sid = json.loads(bd)['json']['sessionId'] + st, bd = call('usersAuth/getCodexDeviceAuthStatus', {'sessionId': sid}) + d = json.loads(bd)['json'] + try: + exp_dt = datetime.datetime.strptime(d.get('expiresAt', '')[:19], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=datetime.timezone.utc) + remain = (exp_dt - datetime.datetime.now(datetime.timezone.utc)).total_seconds() + except Exception: + remain = 600 + code = d['userCode']; vurl = d['verificationUrl'] + print(f'device: sid={sid[:10]} code={code} remain={round(remain)}s url={vurl}', flush=True) + if remain > 420: break + time.sleep(15) + if not code: + print('RESULT: NO_DEVICE_SESSION', flush=True); sys.exit(3) + + # open device page with logged-in context + try: + ctx = browser.contexts[0] + except Exception: + ctx = None + pg = browser.new_page() + try: + pg.goto(vurl, wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(6000) + print('device page:', pg.url, flush=True) + body = re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:400] + print('device body:', body, flush=True) + pg.screenshot(path=os.path.join(HERE, f'cl2_{IDX}_dev.png')) + if 'log-in' in pg.url or 'log in' in body.lower()[:120]: + print('device page NOT logged in — relogin in same page', flush=True) + # login inline then return + em = pg.locator('input[name="email"], input[type="email"], #username').first + try: + em.wait_for(timeout=20000) + em.click(); em.type(acc['email'], delay=80) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + t0 = time.time() + while time.time() - t0 < 50: + if 'email-verification' in pg.url: + c6 = imap_openai_code(acc['email'], acc.get('mail_password') or acc['password']) + if c6: + cinp = pg.locator('input:visible').first + cinp.click(); cinp.type(c6, delay=130) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + break + if pg.locator('input[type="password"]').first.is_visible(timeout=2000): + pwf = pg.locator('input[type="password"]').first + pwf.click(); pwf.type(acc['password'], delay=70) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Войти")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + break + pg.wait_for_timeout(1500) + pg.wait_for_timeout(10000) + pg.goto(vurl, wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(6000) + print('device page2:', pg.url, flush=True) + except Exception as e: + print('inline login err:', str(e)[:150], flush=True) + # fill device code + inputs = pg.evaluate("""() => [...document.querySelectorAll('input')].filter(i=>i.offsetParent!==null && i.type!=='hidden') + .map(i=>({name:i.name,type:i.type,max:i.maxLength,ph:i.placeholder}))""") + print('code inputs:', json.dumps(inputs), flush=True) + parts = code.split('-') + vis = pg.locator('input:visible') + n = vis.count() + if n >= len(parts) and len(parts) >= 2: + for i, p in enumerate(parts): + vis.nth(i).fill(p) + elif n >= 1: + inp = vis.first + inp.click() + inp.type(code.replace('-', ''), delay=110) + pg.wait_for_timeout(1200) + pg.screenshot(path=os.path.join(HERE, f'cl2_{IDX}_code.png')) + for t in ['Continue', 'Продолжить', 'Verify', 'Submit', 'Next', 'Confirm']: + try: + b = pg.locator(f'button:has-text("{t}")').first + if b.is_visible(timeout=2000): + b.click(); print('clicked:', t, flush=True); break + except Exception: pass + pg.wait_for_timeout(5000) + # approve screen + body = re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:500] + print('after code:', pg.url, '|', body, flush=True) + for t in ['Allow', 'Approve', 'Yes', 'Confirm', 'Continue', 'Authorize', 'Разрешить', 'Подтвердить']: + try: + b = pg.locator(f'button:has-text("{t}")').first + if b.is_visible(timeout=2500): + b.click(); print('approve:', t, flush=True) + pg.wait_for_timeout(4000) + except Exception: pass + pg.screenshot(path=os.path.join(HERE, f'cl2_{IDX}_fin.png')) + print('final:', pg.url, '|', re.sub(r'\\s+', ' ', pg.evaluate('document.body.innerText'))[:300], flush=True) + except Exception as e: + print('device flow exc:', str(e)[:250], flush=True) + finally: + try: pg.close() + except Exception: pass + + # poll type.com + print('=== poll codex auth status ===', flush=True) + t0 = time.time(); authed = False + while time.time() - t0 < 150: + st, bd = call('usersAuth/getCodexDeviceAuthStatus', {'sessionId': sid}) + try: s = json.loads(bd)['json'].get('status') + except Exception: s = bd[:80] + print(f' [{round(time.time()-t0)}s]', s, flush=True) + if s in ('authorized', 'success', 'completed', 'confirmed'): authed = True; break + if s in ('failed', 'expired', 'denied'): break + time.sleep(6) + st, bd = call('usersAuth/getCodexAuth', {}) + print('getCodexAuth:', st, bd[:300], flush=True) + has_codex = st == 200 and '"codexAuth":null' not in bd.replace(' ', '') + + # BYO message test + if authed or has_codex: + print('=== BYO createMessage test ===', flush=True) + mid = msg_ulid() + payload = {'id': mid, 'channelId': ACC_TYPE['channelId'], 'parentMessageId': None, 'subchannelId': None, + 'replyToId': None, 'content': {'version': '1.0', 'blocks': [{'type': 'paragraph', 'children': [{'type': 'text', 'text': 'Reply with exactly: PONG-BYO-OK'}]}]}, + 'contentSchemaVersion': '1.0', 'textContent': 'Reply with exactly: PONG-BYO-OK', 'botName': None, + 'isBotResponse': False, 'isStreaming': False, 'hasError': False, 'fileIds': [], 'timezone': 'Europe/Kyiv', + 'aiProvider': 'openai', 'modelId': 'gpt-6.1-sol', 'triggerTimestamp': int(time.time() * 1000), + 'responseIndex': 0, 'agentToggleEnabled': True, 'replyMode': 'chat', 'metadata': None} + st, bd = call('messages/createMessage', payload, 600) + print('createMessage BYO:', st, bd[:400], flush=True) + if st == 200: + t0 = time.time() + while time.time() - t0 < 240: + st2, bd2 = call('messages/getMessagesPaginated', {'channelId': ACC_TYPE['channelId'], 'limit': 25, 'direction': 'backward'}, 4000) + if st2 == 200: + msgs = json.loads(bd2)['json'].get('messages', []) + bots = [m for m in msgs if (m.get('isBotResponse') or m.get('botName')) and (m.get('replyToId') == mid or m['id'] > mid)] + for m in bots: + txt = m.get('textContent') or '' + if txt and not m.get('isStreaming'): + print('BYO REPLY:', txt[:200], flush=True) + print('RESULT: BYO_OK', flush=True); return + time.sleep(4) + print('RESULT: BYO_TIMEOUT', flush=True) + else: + print('RESULT: BYO_CREATE_FAILED', flush=True) + else: + print('RESULT: NOT_AUTHED', flush=True) + +if __name__ == '__main__': + main() diff --git a/tools/codex_link3.py b/tools/codex_link3.py new file mode 100644 index 0000000..238a310 --- /dev/null +++ b/tools/codex_link3.py @@ -0,0 +1,156 @@ +# -*- coding: utf-8 -*- +"""codex_link3.py — single-page device flow: open vurl FIRST, login inline, approve, poll. +Usage: python codex_link3.py +""" +import sys, json, time, os, random, re, urllib.request, urllib.error +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +HERE = os.path.dirname(os.path.abspath(__file__)) +IDX = int(sys.argv[1]) if len(sys.argv) > 1 else 2 + +import importlib.util +spec = importlib.util.spec_from_file_location('cl2', os.path.join(HERE, 'codex_link2.py')) +cl2 = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cl2) +call = cl2.call +imap_openai_code = cl2.imap_openai_code + +def main(): + cands = json.load(open(os.path.join(HERE, 'gpt_cands.json'), encoding='utf-8')) + acc = cands[IDX] + print('gpt account:', acc['email'], flush=True) + + # start device session FIRST (fresh TTL ~300s) + st, bd = call('usersAuth/startCodexDeviceAuth', {}) + if st != 200: + print('startCodexDeviceAuth:', st, bd[:200], flush=True); sys.exit(3) + sid = json.loads(bd)['json']['sessionId'] + st, bd = call('usersAuth/getCodexDeviceAuthStatus', {'sessionId': sid}) + d = json.loads(bd)['json'] + code, vurl = d['userCode'], d['verificationUrl'] + print(f'device: sid={sid[:10]} code={code} url={vurl}', flush=True) + + with cloakbrowser.launch(headless=True) as browser: + pg = browser.new_page() + try: + pg.goto(vurl, wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(7000) + print('page1:', pg.url, flush=True) + + # inline login if needed + if 'log-in' in pg.url or 'email-verification' not in pg.url: + em = pg.locator('input[name="email"], input[type="email"], #username').first + try: + em.wait_for(timeout=25000) + em.click() + em.type(acc['email'], delay=70) + pg.wait_for_timeout(900) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + except Exception as e: + print('email field err:', str(e)[:120], flush=True) + t0 = time.time() + mode = None + while time.time() - t0 < 45: + if 'email-verification' in pg.url: mode = 'code'; break + try: + if pg.locator('input[type="password"]').first.is_visible(timeout=2000): mode = 'pass'; break + except Exception: pass + pg.wait_for_timeout(1500) + print('login mode:', mode, pg.url, flush=True) + if mode == 'pass': + pwf = pg.locator('input[type="password"]').first + pwf.click(); pwf.type(acc['password'], delay=60) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Войти")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + pg.wait_for_timeout(12000) + elif mode == 'code': + c6 = imap_openai_code(acc['email'], acc.get('mail_password') or acc['password']) + if not c6: + print('NO CODE'); sys.exit(4) + cinp = pg.locator('input:visible').first + cinp.wait_for(timeout=10000) + cinp.click(); cinp.type(c6, delay=120) + pg.wait_for_timeout(900) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")']: + try: + pg.locator(sel).first.click(timeout=5000); break + except Exception: pass + pg.wait_for_timeout(12000) + else: + print('unknown login state:', re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:250], flush=True) + + print('after login:', pg.url, flush=True) + pg.screenshot(path=os.path.join(HERE, f'cl3_{IDX}_1.png')) + + # now we should be on the codex device page — enter user code + if 'device' not in pg.url and 'codex' not in pg.url: + pg.goto(vurl, wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(6000) + body = re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:400] + print('device page:', pg.url, '|', body, flush=True) + inputs = pg.evaluate("""() => [...document.querySelectorAll('input')].filter(i=>i.offsetParent!==null && i.type!=='hidden') + .map(i=>({name:i.name,type:i.type,max:i.maxLength,ph:i.placeholder}))""") + print('inputs:', json.dumps(inputs), flush=True) + + parts = code.split('-') + vis = pg.locator('input:visible') + n = vis.count() + if n >= len(parts): + for i, p in enumerate(parts): + vis.nth(i).fill(p) + print('filled split', flush=True) + elif n >= 1: + inp = vis.first + inp.click() + inp.type(code.replace('-', ''), delay=100) + print('filled single', flush=True) + pg.wait_for_timeout(1200) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")', 'button:has-text("Verify")', 'button:has-text("Next")']: + try: + b = pg.locator(sel).first + if b.is_visible(timeout=2500): + b.click(); print('clicked:', sel, flush=True); break + except Exception: pass + pg.wait_for_timeout(6000) + body = re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:500] + print('after code:', pg.url, '|', body, flush=True) + pg.screenshot(path=os.path.join(HERE, f'cl3_{IDX}_2.png')) + + # approve + for t in ['Allow', 'Approve', 'Yes', 'Confirm', 'Continue', 'Authorize', 'Разрешить', 'Подтвердить', 'Да']: + try: + b = pg.locator(f'button:has-text("{t}")').first + if b.is_visible(timeout=2500): + b.click(); print('approve:', t, flush=True) + pg.wait_for_timeout(4000) + except Exception: pass + print('final:', pg.url, '|', re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:300], flush=True) + pg.screenshot(path=os.path.join(HERE, f'cl3_{IDX}_3.png')) + except Exception as e: + print('flow exc:', str(e)[:250], flush=True) + finally: + try: pg.close() + except Exception: pass + + print('=== poll ===', flush=True) + t0 = time.time(); authed = False + while time.time() - t0 < 120: + st, bd = call('usersAuth/getCodexDeviceAuthStatus', {'sessionId': sid}) + try: s = json.loads(bd)['json'].get('status') + except Exception: s = bd[:80] + print(f' [{round(time.time()-t0)}s]', s, flush=True) + if s in ('authorized', 'success', 'completed', 'confirmed'): authed = True; break + if s in ('failed', 'expired', 'denied'): break + time.sleep(5) + st, bd = call('usersAuth/getCodexAuth', {}) + print('getCodexAuth:', st, bd[:300], flush=True) + print('RESULT:', 'AUTHED' if authed else 'NOT_AUTHED', flush=True) + +if __name__ == '__main__': + main() diff --git a/tools/codex_link4.py b/tools/codex_link4.py new file mode 100644 index 0000000..f3380b6 --- /dev/null +++ b/tools/codex_link4.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +"""codex_link4.py — device flow with injected storage-state cookies. +Usage: python codex_link4.py +""" +import sys, json, time, os, re +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +HERE = os.path.dirname(os.path.abspath(__file__)) +IDX = int(sys.argv[1]) if len(sys.argv) > 1 else 2 +STATE = os.path.join(HERE, f'gpt_state_{IDX}.json') + +import importlib.util +spec = importlib.util.spec_from_file_location('cl2', os.path.join(HERE, 'codex_link2.py')) +cl2 = importlib.util.module_from_spec(spec) +spec.loader.exec_module(cl2) +call = cl2.call + +def main(): + st_saved = json.load(open(STATE, encoding='utf-8')) + cands = json.load(open(os.path.join(HERE, 'gpt_cands.json'), encoding='utf-8')) + acc_email = cands[IDX]['email'] + print('state cookies:', len(st_saved['cookies']), flush=True) + + st, bd = call('usersAuth/startCodexDeviceAuth', {}) + if st != 200: + print('startCodexDeviceAuth:', st, bd[:200], flush=True); sys.exit(3) + sid = json.loads(bd)['json']['sessionId'] + st, bd = call('usersAuth/getCodexDeviceAuthStatus', {'sessionId': sid}) + d = json.loads(bd)['json'] + code, vurl = d['userCode'], d['verificationUrl'] + print(f'device: sid={sid[:10]} code={code} url={vurl}', flush=True) + + with cloakbrowser.launch(headless=True) as browser: + pg = browser.new_page() + ctx = pg.context + try: + ctx.add_cookies(st_saved['cookies']) + print('cookies injected', flush=True) + except Exception as e: + print('cookie inject err:', str(e)[:150], flush=True) + + try: + pg.goto(vurl, wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(8000) + print('page1:', pg.url, flush=True) + + # inject localStorage for auth origin if we're on it + if 'auth.openai.com' in pg.url: + for org in st_saved.get('origins', []): + if 'auth.openai.com' in org['origin']: + for it in org.get('localStorage', []): + try: + pg.evaluate("([k,v]) => localStorage.setItem(k,v)", [it['name'], it['value']]) + except Exception: pass + print('localStorage injected', flush=True) + pg.reload(wait_until='domcontentloaded') + pg.wait_for_timeout(7000) + print('page2:', pg.url, flush=True) + + body = re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:350] + print('body:', body, flush=True) + + # choose-an-account: click the account card + if 'choose-an-account' in pg.url: + cands_sel = [f'button:has-text("{acc_email}")', f'[role="button"]:has-text("{acc_email}")', + 'button:has-text("Выбрать учетную запись")', 'button:has-text("Choose account")'] + for sel in cands_sel: + try: + b = pg.locator(sel).first + if b.is_visible(timeout=3000): + b.click(); print('account clicked:', sel, flush=True) + pg.wait_for_timeout(7000) + break + except Exception: pass + print('after account:', pg.url, flush=True) + body = re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:350] + print('body2:', body, flush=True) + + inputs = pg.evaluate("""() => [...document.querySelectorAll('input')].filter(i=>i.offsetParent!==null && i.type!=='hidden') + .map(i=>({name:i.name,type:i.type,max:i.maxLength,ph:i.placeholder}))""") + print('inputs:', json.dumps(inputs), flush=True) + pg.screenshot(path=os.path.join(HERE, f'cl4_{IDX}_1.png')) + + if 'log-in' in pg.url: + print('STILL LOGIN PAGE — state dead', flush=True) + sys.exit(5) + + # fill device code into non-email inputs + parts = code.split('-') + code_inputs = pg.locator('input:visible:not([type="email"])') + n = code_inputs.count() + print('code inputs visible:', n, flush=True) + if n >= len(parts): + for i, p in enumerate(parts): + code_inputs.nth(i).fill(p) + print('filled split', flush=True) + elif n >= 1: + inp = code_inputs.first + inp.click() + inp.type(code.replace('-', ''), delay=100) + print('filled single', flush=True) + else: + print('NO CODE INPUTS', flush=True) + pg.wait_for_timeout(1200) + for sel in ['button[type="submit"]', 'button:has-text("Continue")', 'button:has-text("Продолжить")', 'button:has-text("Verify")', 'button:has-text("Next")']: + try: + b = pg.locator(sel).first + if b.is_visible(timeout=2500): + b.click(); print('clicked:', sel, flush=True); break + except Exception: pass + pg.wait_for_timeout(6000) + body = re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:400] + print('after code:', pg.url, '|', body, flush=True) + pg.screenshot(path=os.path.join(HERE, f'cl4_{IDX}_2.png')) + + for t in ['Allow', 'Approve', 'Yes, allow', 'Confirm', 'Continue', 'Authorize', 'Разрешить', 'Подтвердить', 'Да, разрешить']: + try: + b = pg.locator(f'button:has-text("{t}")').first + if b.is_visible(timeout=2500): + b.click(); print('approve:', t, flush=True) + pg.wait_for_timeout(4000) + except Exception: pass + print('final:', pg.url, '|', re.sub(r'\s+', ' ', pg.evaluate('document.body.innerText'))[:300], flush=True) + pg.screenshot(path=os.path.join(HERE, f'cl4_{IDX}_3.png')) + except Exception as e: + print('flow exc:', str(e)[:250], flush=True) + finally: + try: pg.close() + except Exception: pass + + print('=== poll ===', flush=True) + t0 = time.time(); authed = False + while time.time() - t0 < 100: + st, bd = call('usersAuth/getCodexDeviceAuthStatus', {'sessionId': sid}) + try: s = json.loads(bd)['json'].get('status') + except Exception: s = bd[:80] + print(f' [{round(time.time()-t0)}s]', s, flush=True) + if s in ('authorized', 'success', 'completed', 'confirmed'): authed = True; break + if s in ('failed', 'expired', 'denied'): break + time.sleep(5) + st, bd = call('usersAuth/getCodexAuth', {}) + print('getCodexAuth:', st, bd[:400], flush=True) + print('RESULT:', 'AUTHED' if authed else 'NOT_AUTHED', flush=True) + +if __name__ == '__main__': + main() diff --git a/tools/login_check.py b/tools/login_check.py new file mode 100644 index 0000000..18b3d9b --- /dev/null +++ b/tools/login_check.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +"""type.com login check via cloakbrowser. +Usage: python login_check.py +Prints JSON: {ok, final_url, body, cookies} +""" +import json, re, sys, time +sys.stdout.reconfigure(encoding='utf-8') + +def main(): + email, password = sys.argv[1], sys.argv[2] + import cloakbrowser + out = {'ok': False, 'email': email} + b = None + try: + b = cloakbrowser.launch(headless=True) + pg = b.new_page() + pg.goto('https://type.com/login', wait_until='domcontentloaded', timeout=60000) + pg.wait_for_selector('input[type=email], input[name=email]', timeout=45000) + pg.wait_for_timeout(1500) + pg.fill('input[type=email], input[name=email]', email) + pg.wait_for_timeout(800) + pg.evaluate("() => { const b=[...document.querySelectorAll('button')].find(e=>/Продолжить|Continue/i.test((e.innerText||'').trim())); if(b) b.click(); }") + try: + pg.wait_for_selector('input[type=password]', timeout=20000) + except Exception: + pass + pg.wait_for_timeout(1000) + try: + pg.fill('input[type=password]', password) + except Exception as e: + out['err'] = 'no password field: ' + str(e)[:100] + pg.wait_for_timeout(800) + pg.evaluate("() => { const b=[...document.querySelectorAll('button')].find(e=>/Продолжить|Continue|Войти|Sign in|Log in/i.test((e.innerText||'').trim())); if(b) b.click(); }") + pg.wait_for_timeout(10000) + out['final_url'] = pg.url + out['body'] = re.sub(r'\s+', ' ', pg.evaluate('() => document.body.innerText'))[:400] + cks = pg.context.cookies() + out['cookies'] = [{'name': c['name'], 'domain': c.get('domain')} for c in cks] if isinstance(cks, list) else str(cks)[:500] + out['ok'] = 'auth.type.com' not in pg.url and 'заблокирован' not in out['body'].lower() + except Exception as e: + out['err'] = str(e)[:250] + finally: + if b: + try: + b.close() + except Exception: + pass + print(json.dumps(out, ensure_ascii=False)) + +main() diff --git a/tools/login_token.py b/tools/login_token.py new file mode 100644 index 0000000..dd3ee14 --- /dev/null +++ b/tools/login_token.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +"""login_token.py EMAIL PASSWORD -> extract authToken + refresh-token + channelId + agentId -> pool append/update. +Usage: python login_token.py email password [pool.json]""" +import sys, json, os, time +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +HERE = os.path.dirname(os.path.abspath(__file__)) +POOL = sys.argv[3] if len(sys.argv) > 3 else os.path.join(HERE, 'pool.json') + +def main(): + email, pw = sys.argv[1], sys.argv[2] + with cloakbrowser.launch(headless=True) as browser: + pg = browser.new_page() + pg.goto('https://type.com/login', wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(4000) + def click_btn(texts, wait=2500): + for t in texts: + try: + loc = pg.locator(f'button:has-text("{t}")').first + if loc.is_visible(timeout=wait): + loc.click(); return True + except Exception: pass + return False + click_btn(['Accept All'], 1500) + em = pg.locator('input[type="email"], input[name="email"]').first + em.wait_for(timeout=15000) + em.fill(email) + click_btn(['Continue', 'Продолжить']) + pg.wait_for_timeout(4000) + p = pg.locator('input[type="password"]').first + p.wait_for(timeout=10000) + p.fill(pw) + click_btn(['Continue', 'Продолжить', 'Log in', 'Войти']) + pg.wait_for_timeout(9000) + print('url:', pg.url, flush=True) + tok = pg.evaluate("() => sessionStorage.getItem('authToken')") + rt = pg.evaluate("() => localStorage.getItem('workos:refresh-token')") + if not tok: + # maybe workspace page needed + pg.wait_for_timeout(6000) + tok = pg.evaluate("() => sessionStorage.getItem('authToken')") + rt = rt or pg.evaluate("() => localStorage.getItem('workos:refresh-token')") + if not tok: + print('NO TOKEN; body:', pg.evaluate('document.body.innerText')[:300], flush=True) + sys.exit(2) + print('token len:', len(tok), 'refresh:', bool(rt), flush=True) + rec = {'email': email, 'password': pw, 'token': 'Bearer ' + tok.replace('Bearer ', ''), + 'refresh_token': rt, 'channelId': None, 'agentId': None, 'added': int(time.time()), 'fails': 0} + # enrich via API + import urllib.request, urllib.error + def call(ep, payload): + req = urllib.request.Request('https://api.type.com/api/orpc/' + ep, data=json.dumps({'json': payload}).encode(), headers={ + 'content-type': 'application/json', 'authorization': rec['token'], 'origin': 'https://type.com'}) + try: + with urllib.request.urlopen(req, timeout=25) as r: return r.status, r.read().decode() + except urllib.error.HTTPError as e: return e.code, e.read().decode() + except Exception as e: return -1, str(e) + st, bd = call('channels/getUserChannels', {}) + if st == 200: + chs = json.loads(bd)['json'] + chs = chs if isinstance(chs, list) else chs.get('channels', []) + if chs: rec['channelId'] = chs[0]['id'] + st, bd = call('sidekick/ensureMine', {}) + if st == 200: + try: rec['agentId'] = json.loads(bd)['json'].get('id') + except Exception: pass + st, bd = call('billing/getStatus', {}) + if st == 200: + j = json.loads(bd)['json'] + rec['trial_end'] = j.get('trialEnd'); rec['billing_status'] = j.get('status') + st, bd = call('usersAuth/getCodexAuth', {}) + rec['codex'] = st == 200 and bool(json.loads(bd)['json'].get('codexAuth')) if st == 200 else False + print('channelId:', rec['channelId'], 'agentId:', rec['agentId'], 'trial:', rec.get('trial_end'), 'codexBYO:', rec['codex'], flush=True) + pool = [] + if os.path.exists(POOL): + try: pool = json.load(open(POOL, encoding='utf-8')) + except Exception: pool = [] + pool = [x for x in pool if x.get('email') != email] + pool.append(rec) + json.dump(pool, open(POOL, 'w', encoding='utf-8'), indent=1) + print('pool size:', len(pool), '->', POOL, flush=True) + +if __name__ == '__main__': + main() diff --git a/tools/new2no.py b/tools/new2no.py new file mode 100644 index 0000000..7fc0fe1 --- /dev/null +++ b/tools/new2no.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +"""new2no.py — register fresh 2nd-no.com account (2captcha turnstile) and save creds.""" +import sys, os, json +sys.stdout.reconfigure(encoding='utf-8') +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.environ.get('SECONDNO_ROOT', os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))) +sys.path.insert(0, HERE) + +import importlib.util +spec = importlib.util.spec_from_file_location('sr', os.path.join(HERE, 'sms2no_reserve.py')) +sr = importlib.util.module_from_spec(spec) +sys.argv = ['x', 'a', 'b', 'c', 'd'] # satisfy module-level arg parsing if any +spec.loader.exec_module(sr) + +from providers.secondno import full_cycle + +solver = sr.TwoCaptchaTurnstile() +res = full_cycle(1, solver=solver) +print(json.dumps(res, ensure_ascii=False, default=str)[:1200], flush=True) +ok = [r for r in res if 'email' in r and 'error' not in r] +if ok: + with open(os.path.join(HERE, '2no_accounts.jsonl'), 'a', encoding='utf-8') as f: + for r in ok: + f.write(json.dumps(r, ensure_ascii=False, default=str) + '\n') + print('SAVED', len(ok), flush=True) +else: + print('FAILED', flush=True) diff --git a/tools/radar_revive.py b/tools/radar_revive.py new file mode 100644 index 0000000..8bcf0be --- /dev/null +++ b/tools/radar_revive.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +"""Revive a Type.com/Viktor account through WorkOS radar phone challenge. +Phone: 2nd-no ACTIVE reservation (reuse accounts) via sms2no_reserve.py subprocess (REUSE, no turnstile). +Flow: google cookies -> type.com/login -> Continue with Google -> tile -> consent -> radar-challenge + -> fill country_code + local_number -> Отправить код -> SMS code -> submit -> JWT -> save. +""" +import asyncio, json, os, re, subprocess, sys, time, urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +TARGET = os.environ.get('RADAR_TARGET') or (sys.argv[1] if len(sys.argv) > 1 else '') +SESS_FILE = os.environ.get('RADAR_SESS', os.path.join(ROOT, 'radar_session.json')) +RESERVE = os.path.join(HERE, '_vk_reserve.json') +CODEF = os.path.join(HERE, '_vk_code.json') +GWS = os.environ.get('GWS_USER_FILE', os.path.join(ROOT, 'gws_user.json')) +LOG = [] +PY311 = os.environ.get('PY311', sys.executable) + + +def log(*a): + s = time.strftime('%H:%M:%S') + ' ' + ' '.join(str(x)[:400] for x in a) + print(s, flush=True) + LOG.append(s) + + +def api(path, jwt): + req = urllib.request.Request('https://api.viktor.com' + path, headers={ + 'User-Agent': 'Mozilla/5.0', 'Authorization': 'Bea' + 'rer ' + jwt, + 'Origin': 'https://app.viktor.com', 'Referer': 'https://app.viktor.com/'}) + try: + r = urllib.request.urlopen(req, timeout=30) + return r.getcode(), r.read().decode() + except Exception as e: + b = '' + try: + b = e.read().decode()[:400] + except Exception: + pass + return getattr(e, 'code', str(e)), b + + +def norm_cookies(cs): + out = [] + for c in cs: + d = {k: v for k, v in c.items() if k in ('name', 'value', 'domain', 'path', 'expires', 'httpOnly', 'secure')} + ss = c.get('sameSite') + if ss in ('Lax', 'Strict', 'None'): + d['sameSite'] = ss + out.append(d) + return out + + +def fmt_local(num): + """459076643 -> (459)076-643""" + n = re.sub(r'\D', '', str(num)) + if len(n) == 9: + return '(%s)%s-%s' % (n[:3], n[3:6], n[6:]) + return n + + +def start_reserve(): + """Launch sms2no_reserve.py with first reusable account; returns Popen.""" + cands = json.load(open(os.path.join(ROOT, '_reuse_candidates.json'), encoding='utf-8')) + if not cands: + raise RuntimeError('no reuse candidates') + c = cands[0] + for f in (RESERVE, CODEF): + if os.path.exists(f): + os.remove(f) + min_ts = time.strftime('%Y-%m-%dT%H:%M:%S') + env = dict(os.environ) + env['PYTHONPATH'] = '' + env['PYTHONIOENCODING'] = 'utf-8' + p = subprocess.Popen( + [PY311, os.path.join(HERE, 'sms2no_reserve.py'), c['email'], c['pass'], RESERVE, CODEF, '420', min_ts], + stdout=open(os.path.join(HERE, '_vk_reserve.log'), 'w', encoding='utf-8'), + stderr=subprocess.STDOUT, cwd=HERE, env=env) + log('reserve subprocess pid', p.pid, 'account', c['email']) + return p + + +def wait_file(path, timeout): + end = time.time() + timeout + while time.time() < end: + if os.path.exists(path): + try: + d = json.load(open(path, encoding='utf-8')) + if d and (d.get('code') or d.get('phone') or d.get('number_id')): + return d + except Exception: + pass + time.sleep(3) + return None + + +async def body_text(page, n=500): + try: + b = await page.evaluate("() => document.body ? document.body.innerText : ''") + return re.sub(r'\s+', ' ', b)[:n] + except Exception: + return '' + + +async def main(): + import cloakbrowser + sess = json.load(open(SESS_FILE, encoding='utf-8')) + rp = start_reserve() + browser = await cloakbrowser.launch_async(headless=True, humanize=False) + try: + ctx = await browser.new_context() + await ctx.add_cookies(norm_cookies(sess['cookies'])) + page = await ctx.new_page() + await page.goto('https://type.com/login', timeout=90000, wait_until='domcontentloaded') + await page.wait_for_timeout(5000) + log('login url:', page.url) + clicked = False + for t in ['Continue with Google', 'Weiter mit Google', 'Продолжить с Google', 'Google']: + try: + await page.get_by_text(t, exact=False).first.click(timeout=6000) + clicked = True + log('clicked', t) + break + except Exception: + continue + if not clicked: + log('NO google button; body:', await body_text(page, 200)) + return + await page.wait_for_timeout(8000) + + for rnd in range(12): + u = page.url + b = await body_text(page, 300) + if 'accounts.google.com' in u: + # password challenge FIRST (Google re-auth for SA-created account) + try: + await page.wait_for_selector('input[type=password]', timeout=3000) + gws = json.load(open(GWS, encoding='utf-8')) + await page.fill('input[type=password]', gws['password']) + log('pwd filled') + try: + await page.click('#passwordNext button', timeout=4000) + except Exception: + await page.keyboard.press('Enter') + log('pwd submitted') + await page.wait_for_timeout(9000) + continue + except Exception: + pass + if TARGET.split('@')[0] in b and 'challenge/pwd' not in u and 'password' not in u: + try: + await page.get_by_text(TARGET.split('@')[0], exact=False).first.click(timeout=6000) + log('tile clicked') + await page.wait_for_timeout(6000) + continue + except Exception: + pass + for t in ['Продолжить', 'Continue', 'Weiter', 'Allow']: + try: + loc = page.get_by_role('button', name=t) + if await loc.count(): + await loc.first.click(timeout=3000) + log('consent', t) + await page.wait_for_timeout(8000) + break + except Exception: + continue + continue + if 'radar' in u or 'challenge' in u: + break + if 'type.com' in u or 'viktor.com' in u: + break + await page.wait_for_timeout(4000) + + u = page.url + log('gate url:', u[:200]) + log('gate body:', await body_text(page, 400)) + await page.screenshot(path=os.path.join(HERE, 'vk_radar_phone_page.png')) + + if not ('radar' in u or 'challenge' in u): + log('NOT on radar — cannot proceed') + return + + # wait for reserved phone + rinfo = wait_file(RESERVE, 180) + if not rinfo or not rinfo.get('phone'): + log('NO PHONE reserved; tail:', open(os.path.join(HERE, '_vk_reserve.log'), encoding='utf-8', errors='replace').read()[-300:]) + return + phone = rinfo['phone'] + num = re.sub(r'\D', '', phone) + if num.startswith('48'): + num = num[2:] + log('PHONE', phone, 'nid', rinfo.get('number_id'), 'exp', rinfo.get('expires')) + + # fill radar phone form + try: + await page.fill('input[name=country_code]', '+48', timeout=8000) + except Exception: + try: + await page.locator('input').first.fill('+48') + except Exception as e: + log('cc fill err', str(e)[:80]) + await page.wait_for_timeout(800) + try: + await page.fill('input[name=local_number]', fmt_local(num), timeout=8000) + except Exception as e: + log('ln fill err', str(e)[:80]) + await page.wait_for_timeout(800) + sent = False + for t in ['Отправить код подтверждения', 'Send verification code', 'Send code', 'Отправить код', 'Continue', 'Продолжить']: + try: + loc = page.get_by_role('button', name=t) + if await loc.count(): + await loc.first.click(timeout=5000) + sent = True + log('send clicked:', t) + break + except Exception: + continue + if not sent: + try: + await page.locator('button[type=submit]').first.click(timeout=5000) + sent = True + log('send via submit btn') + except Exception as e: + log('send err', str(e)[:100]) + await page.wait_for_timeout(6000) + log('after send url:', page.url[:150], '| body:', await body_text(page, 250)) + + # wait SMS code (primary: reserve subprocess; fallback: fresh reader with min_ts) + cinfo = wait_file(CODEF, 150) + if not cinfo or not cinfo.get('code'): + log('primary poller silent — spawning fallback reader (min_ts filtered)') + send_ts = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time() - 600)) + env = dict(os.environ) + env['PYTHONPATH'] = '' + env['PYTHONIOENCODING'] = 'utf-8' + cands = json.load(open(os.path.join(ROOT, '_reuse_candidates.json'), encoding='utf-8')) + c0 = cands[0] + frp = subprocess.Popen( + [PY311, os.path.join(HERE, '_sms_reader.py'), c0['email'], c0['pass'], phone, + str(rinfo.get('number_id')), send_ts, CODEF], + stdout=open(os.path.join(HERE, '_vk_reader.log'), 'w', encoding='utf-8'), + stderr=subprocess.STDOUT, cwd=HERE, env=env) + log('reader pid', frp.pid) + cinfo = wait_file(CODEF, 300) + code = (cinfo or {}).get('code') + if not code: + log('NO SMS CODE; reserve tail:', open(os.path.join(HERE, '_vk_reserve.log'), encoding='utf-8', errors='replace').read()[-200:]) + return + log('SMS code arrived len', len(str(code))) + + # enter code (may be single input or 6 boxes) + try: + boxes = await page.evaluate("() => [...document.querySelectorAll('input')].map(e=>e.type+'|'+(e.name||'')+'|'+(e.maxLength||''))") + log('code inputs:', boxes[:10]) + if len([b for b in boxes if b.startswith('text') or b.startswith('tel')]) >= 6: + for i, ch in enumerate(str(code)[:8]): + try: + await page.locator('input').nth(i).fill(ch, timeout=2000) + except Exception: + await page.keyboard.type(ch) + else: + inp = page.locator('input').first + await inp.fill(str(code), timeout=5000) + await page.wait_for_timeout(1200) + sub = False + for sel in ['button[type=submit]', 'button']: + try: + await page.locator(sel).first.click(timeout=4000) + sub = True + break + except Exception: + continue + log('code submitted', sub) + await page.wait_for_timeout(12000) + except Exception as e: + log('code enter err', str(e)[:120]) + return + log('after code url:', page.url[:200], '| body:', await body_text(page, 300)) + await page.screenshot(path=os.path.join(HERE, 'vk_radar_after.png')) + + # land on app + grab JWT + if 'app.viktor.com' not in page.url: + await page.goto('https://app.viktor.com/', timeout=90000, wait_until='domcontentloaded') + await page.wait_for_timeout(10000) + log('final url:', page.url) + js = """() => { const o={}; + try{for(let i=0;i [poll_timeout] [min_ts] +Writes {"phone": "...", "number_id": ...} to reserve_file ASAP, +then polls SMS and writes {"code": "...", "text": "..."} to code_file. +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import json, re, sys, time, os, urllib.parse, urllib.request +sys.stdout.reconfigure(encoding='utf-8') +sys.path.insert(0, str(_REPO)) +from providers.secondno import SecondNo + +_FILL_JS = """(args) => { + let n = 0; + const setVal = (el, v) => { if (!el) return; try { + const s = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), 'value').set; + s.call(el, v); el.dispatchEvent(new Event('input', {bubbles: true})); + el.dispatchEvent(new Event('change', {bubbles: true})); n++; + } catch (e) {} }; + const inputs = Array.from(document.querySelectorAll('input')); + setVal(inputs.find(i => i.type === 'email' || i.type === 'text'), args[0]); + setVal(inputs.find(i => i.type === 'password'), args[1]); + return n; +}""" + + +class SecondNoRobust(SecondNo): + """React-hydration-safe login: wait for password input, guarded setVal, retry.""" + + def login(self, email, password): + pg = self._start() + pg.goto("https://2nd-no.com/auth/login", wait_until="domcontentloaded", timeout=60000) + pg.wait_for_selector("input[type=password]", timeout=30000) + pg.wait_for_timeout(1500) + n = pg.evaluate(_FILL_JS, [email, password]) + if n < 2: + pg.wait_for_timeout(4000) + n = pg.evaluate(_FILL_JS, [email, password]) + if n < 2: + raise RuntimeError(f"login fill incomplete ({n}/2)") + pg.wait_for_timeout(600) + pg.evaluate("() => { const b=document.querySelector('button[type=submit]'); if(b) b.click(); }") + try: + pg.wait_for_url("**/app/**", timeout=30000) + except Exception: + pass + pg.wait_for_timeout(3000) + self.creds = {"email": email, "password": password} + return True + +KEYS_FILE = str(_d("tmp/captcha_keys_2captcha.json","CAPTCHA_KEYS")) + +def _load_2captcha_key(): + d = json.load(open(KEYS_FILE, encoding='utf-8')) + ks = d.get('keys') or [] + # pick first key with positive balance + for k in ks: + try: + body = urllib.parse.urlencode({'key': k['key'], 'action': 'getbalance', 'json': 1}).encode() + req = urllib.request.Request('https://2captcha.com/res.php', data=body) + r = json.loads(urllib.request.urlopen(req, timeout=20).read().decode()) + bal = float(r.get('request', -1)) + print(f"[2captcha] {k.get('label')} balance {bal}", flush=True) + if r.get('status') == 1 and bal > 0.05: + return k['key'] + except Exception as e: + print('[2captcha] balance check err:', str(e)[:80], flush=True) + raise RuntimeError('no 2captcha key with balance') + +class TwoCaptchaTurnstile: + def __init__(self, key=None): + self.key = key or _load_2captcha_key() + if not self.key: + raise RuntimeError('no 2captcha key') + + def _post(self, url, data, timeout=40): + body = urllib.parse.urlencode(data).encode() + req = urllib.request.Request(url, data=body, headers={'Content-Type': 'application/x-www-form-urlencoded'}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + def turnstile(self, sitekey, pageurl, action=None, proxy_url=None): + d = self._post('https://2captcha.com/in.php', { + 'key': self.key, 'method': 'turnstile', 'sitekey': sitekey, + 'pageurl': pageurl, 'json': 1}) + if d.get('status') != 1: + raise RuntimeError(f"2captcha submit: {d}") + task_id = d['request'] + print('[2captcha] task', task_id, flush=True) + deadline = time.time() + 240 + while time.time() < deadline: + time.sleep(8) + r = self._post('https://2captcha.com/res.php', { + 'key': self.key, 'action': 'get', 'id': task_id, 'json': 1}) + if r.get('status') == 1: + tok = r['request'] + if isinstance(tok, dict): + tok = tok.get('token') or tok.get('code') + return tok + err = str(r.get('request', '')) + if 'NOT_READY' not in err: + raise RuntimeError(f"2captcha get: {r}") + raise RuntimeError('2captcha timeout') + +def main(): + email, password, reserve_file, code_file = sys.argv[1:5] + poll_timeout = int(sys.argv[5]) if len(sys.argv) > 5 else 300 + min_ts = sys.argv[6] if len(sys.argv) > 6 else None + + try: + solver = TwoCaptchaTurnstile() + except Exception as e: + print('solver init err:', e, flush=True) + solver = None + sn = SecondNoRobust(solver=solver) + try: + sn.login(email, password) + used_file = os.path.join(os.path.dirname(os.path.abspath(reserve_file)), 'used_numbers.json') + used = set() + try: + used = set(json.load(open(used_file, encoding='utf-8'))) + except Exception: + pass + phone = number_id = expires = None + # reuse active unused reservations FIRST (skips turnstile cost when 3-number limit reached) + try: + my = sn._call(311, {'offset': 0, 'limit': 10}) + now = time.strftime('%Y-%m-%dT%H:%M:%S') + for r0 in (my.get('result') or []): + num = str(r0.get('number') or '') + if num in used: + continue + if str(r0.get('reservation_to') or '') < now: + continue + phone = '+48' + num + number_id = r0.get('number_id') + expires = r0.get('reservation_to') + break + if phone: + print('REUSE active number', phone, number_id, flush=True) + except Exception as e: + print('311 err:', str(e)[:100], flush=True) + if not phone: + try: + info = sn.get_number() # dict: {number, full, number_id, user_number_id, expires} + phone = info.get('full') or ('+48' + str(info.get('number'))) + number_id = info.get('number_id') + expires = info.get('expires') + except Exception as e: + print('reserve fresh failed:', str(e)[:150], flush=True) + if not phone: + raise RuntimeError('no free/reservable number (limit reached, all used)') + with open(reserve_file, 'w', encoding='utf-8') as f: + json.dump({'phone': phone, 'number_id': number_id, 'expires': expires}, f) + print('RESERVED', phone, number_id, flush=True) + + deadline = time.time() + poll_timeout + while time.time() < deadline: + try: + msgs = sn.read_sms(phone, number_id, timeout=16, poll=8) + cands = [] + for m in msgs: + text = str(m.get('text') or m.get('body') or '') + ts = str(m.get('created_at') or m.get('date') or m.get('time') or '') + if min_ts and ts and ts < min_ts: + continue + mm = re.search(r'\b(\d{4,8})\b', text) + if mm: + cands.append((ts, mm.group(1), text)) + if cands: + cands.sort() + ts, code, text = cands[-1] + with open(code_file, 'w', encoding='utf-8') as f: + json.dump({'code': code, 'text': text[:250], 'ts': ts}, f, ensure_ascii=False) + digits = re.sub(r'\D', '', str(phone)) + used.add(digits[2:] if digits.startswith('48') else digits) + try: + json.dump(sorted(used), open(used_file, 'w', encoding='utf-8')) + except Exception: + pass + print('CODE', code, flush=True) + return + except Exception as e: + print('poll err:', str(e)[:120], flush=True) + time.sleep(6) + with open(code_file, 'w', encoding='utf-8') as f: + json.dump({'code': None, 'err': 'timeout'}, f) + print('TIMEOUT', flush=True) + except Exception as e: + with open(code_file, 'w', encoding='utf-8') as f: + json.dump({'code': None, 'err': str(e)[:200]}, f) + print('FATAL', str(e)[:200], flush=True) + finally: + sn.close() + +if __name__ == '__main__': + main() diff --git a/tools/sms_reader.py b/tools/sms_reader.py new file mode 100644 index 0000000..8e233f7 --- /dev/null +++ b/tools/sms_reader.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +"""Fresh-browser SMS reader for 2nd-no: argv = email pass phone number_id min_ts outfile. +Filters messages by created_at >= min_ts and skips legacy texts (GitLab etc). +Writes {"code": "...", "text": "...", "ts": "..."} to outfile. +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import sys, json, re, time +sys.path.insert(0, str(_REPO)) +sys.path.insert(0, str(_REPO)) +from sms2no_reserve import SecondNoRobust + + +def main(): + email, pw, phone, nid, min_ts, outfile = sys.argv[1:7] + nid = int(nid) + sn = SecondNoRobust(solver=None) + sn.login(email, pw) + print('reader logged in', flush=True) + deadline = time.time() + 420 + while time.time() < deadline: + try: + msgs = sn.read_sms(phone, nid, timeout=16, poll=8) + cands = [] + for m in (msgs or []): + text = str(m.get('text') or m.get('body') or '') + ts = str(m.get('created_at') or m.get('date') or m.get('time') or '') + if ts and ts < min_ts: + continue + if 'gitlab' in text.lower(): + continue + mm = re.search(r'\b(\d{4,8})\b', text) + if mm: + cands.append((ts, mm.group(1), text)) + if cands: + cands.sort() + ts, code, text = cands[-1] + json.dump({'code': code, 'text': text[:200], 'ts': ts}, open(outfile, 'w', encoding='utf-8')) + print('CODE WRITTEN len', len(code), flush=True) + sn.close() + return + print('no fresh sms yet', flush=True) + except Exception as e: + print('poll err', str(e)[:100], flush=True) + time.sleep(6) + print('READER TIMEOUT', flush=True) + sn.close() + + +if __name__ == '__main__': + main() diff --git a/tools/type_reg.py b/tools/type_reg.py new file mode 100644 index 0000000..ca7600f --- /dev/null +++ b/tools/type_reg.py @@ -0,0 +1,398 @@ +# -*- coding: utf-8 -*- +"""type.com autoreg — WorkOS AuthKit (auth.type.com) + cloakbrowser +Flow: /onboarding -> sign-up (name+email) -> password -> [email verify?] -> session +Usage: python type_reg.py N [voidash|tonline] +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import sys, re, json, time, random, string, os + +sys.stdout.reconfigure(encoding='utf-8') +HERE = os.path.dirname(os.path.abspath(__file__)) +OUT = os.path.join(HERE, 'type_accounts.jsonl') +VOID = 'https://api.voidash.com/api/v1' +IMAP_POOL = os.environ.get('IMAP_POOL', os.path.join(HERE, 'working_mails.txt')) +START = 'https://type.com/onboarding' + +# ---- 2no.pl phone fallback (env NO2_EMAIL/NO2_PASS or gitignored no2_fallback.json) ---- +def _no_fallback(): + e = os.environ.get('NO2_EMAIL', '') + p = os.environ.get('NO2_PASS', '') + if e and p: + return e, p + try: + d = json.load(open(os.path.join(HERE, 'no2_fallback.json'), encoding='utf-8')) + return d.get('email', ''), d.get('pass', '') + except Exception: + return '', '' + +NO_EMAIL, NO_PASS = _no_fallback() + +def _no_accounts(): + """Rotate 2no accounts with ACTIVE reservations (from _reuse_candidates.json).""" + try: + c = json.load(open(os.path.join(HERE, '_reuse_candidates.json'), encoding='utf-8')) + seen = {} + for x in c: + seen.setdefault(x['email'], x['pass']) + if seen: + return list(seen.items()) + except Exception: + pass + return [(NO_EMAIL, NO_PASS)] + +_NO_ACCS = _no_accounts() +_NO_IDX = [0] + +def no_cred(): + e, p = _NO_ACCS[_NO_IDX[0] % len(_NO_ACCS)] + _NO_IDX[0] += 1 + return e, p +PHONE = os.environ.get('RADAR_PHONE', '') +PHONE_ID = 108963 +PY311 = _PY + +def make_voidash(): + import requests + dom = os.environ.get('VOID_DOMAIN', 'voidash.bond') + d = requests.post(VOID + '/inboxes', json={'domain': dom}, timeout=30).json() + return d['address'], d['session_key'] + +def load_tonline(n=1): + used = set() + uf = os.path.join(HERE, 'used_emails.txt') + if os.path.exists(uf): + used = set(l.strip() for l in open(uf) if l.strip()) + out = [] + for line in open(IMAP_POOL, encoding='utf-8'): + line = line.strip() + if ':' not in line or line.startswith('#'): + continue + em, pw = line.split(':', 1) + if '-' in em.split('@')[0] or em in used: + continue + out.append((em, pw)) + if len(out) >= n: + break + return out + +def poll_voidash(key, timeout=240): + import requests + t0 = time.time() + while time.time() - t0 < timeout: + try: + msgs = requests.get(VOID + '/messages', headers={'Authorization': 'Bea' + 'rer ' + key}, timeout=30).json() + items = msgs if isinstance(msgs, list) else msgs.get('messages', msgs.get('data', [])) + for m in items: + body = json.dumps(m, ensure_ascii=False) + if 'type' in body.lower(): + return body + except Exception: + pass + time.sleep(5) + return None + +def poll_imap_tonline(email, pw, timeout=240): + import imaplib, email as emlib + t0 = time.time() + while time.time() - t0 < timeout: + try: + M = imaplib.IMAP4_SSL('secureimap.t-online.de', 993) + M.login(email, pw) + M.select('INBOX') + typ, data = M.search(None, '(FROM "type.com")') + ids = data[0].split() + if not ids: + typ, data = M.search(None, 'ALL') + ids = data[0].split()[-6:] + for i in ids[-6:]: + typ, md = M.fetch(i, '(RFC822)') + msg = emlib.message_from_bytes(md[0][1]) + frm = str(msg.get('From', '')) + if 'type.com' not in frm.lower(): + continue + body = '' + if msg.is_multipart(): + for part in msg.walk(): + if part.get_content_type() == 'text/html': + body = part.get_payload(decode=True).decode('utf-8', 'replace') + break + else: + body = msg.get_payload(decode=True).decode('utf-8', 'replace') + M.logout() + return json.dumps({'from': frm, 'subject': str(msg.get('Subject')), 'body': body}, ensure_ascii=False) + M.logout() + except Exception as e: + print(' imap retry:', str(e)[:80]) + time.sleep(8) + return None + +def btn_text(pg, pat): + return f"() => {{ const b=[...document.querySelectorAll('button')].find(e=>/{pat}/i.test((e.innerText||'').trim())); if(b){{b.click();return 1;}} return 0; }}" + +def run(n, provider='voidash'): + import cloakbrowser + okc = 0 + for i in range(n): + res = {'ok': False, 'ts': int(time.time()), 'provider': provider} + b = None + try: + if provider == 'voidash': + emailaddr, cred = make_voidash() + else: + emailaddr, cred = load_tonline(1)[0] + pw = 'Tp' + ''.join(random.choices(string.ascii_letters, k=6)) + str(random.randint(100, 999)) + 'x' + res['email'] = emailaddr + res['password'] = pw + print(f'[{i}] email={emailaddr}') + proxy = os.environ.get('PROXY') + proxy_kwargs = {'proxy': proxy} if proxy else {} + b = cloakbrowser.launch(headless=True, **proxy_kwargs) + pg = b.new_page() + pg.goto(START, wait_until='domcontentloaded', timeout=60000) + try: + pg.wait_for_selector('input[name="first_name"]', timeout=45000) + except Exception: + pg.goto(START, wait_until='domcontentloaded', timeout=60000) + pg.wait_for_selector('input[name="first_name"]', timeout=60000) + pg.wait_for_timeout(1500) + fn = random.choice(['Alex', 'Max', 'Nik', 'Sam', 'Leo', 'Ivan', 'Dan', 'Kir', 'Oleg', 'Tim']) + ln = random.choice(['Morgan', 'Weber', 'Klein', 'Bauer', 'Wolf', 'Stone', 'Reed', 'Cole', 'Fox', 'Lang']) + pg.fill('input[name="first_name"]', fn) + pg.fill('input[name="last_name"]', ln) + pg.fill('input[name="email"]', emailaddr) + res['name'] = fn + ' ' + ln + pg.wait_for_timeout(random.randint(800, 2000)) + pg.evaluate(btn_text(pg, r'Продолжить|Continue')) + # password step + pg.wait_for_selector('input[name="password"], input[type="password"]', timeout=30000) + pg.wait_for_timeout(1200) + pg.fill('input[type="password"]', pw) + pg.wait_for_timeout(random.randint(800, 1800)) + pg.evaluate(btn_text(pg, r'Продолжить|Continue')) + pg.wait_for_timeout(7000) + body = re.sub(r'\s+', ' ', pg.evaluate('() => document.body.innerText'))[:500] + res['after_password'] = body + res['url1'] = pg.url + print(' url:', pg.url[:110]) + print(' body:', body[:200]) + blocked = 'заблокирован' in body or 'blocked' in body.lower() or 'support' in body.lower() + if blocked: + res['err'] = 'signals block' + pg.screenshot(path=os.path.join(HERE, f'fail_{i}.png')) + print(' BLOCKED') + raise StopIteration + # email verification step? + if 'code' in body.lower() or 'код' in body.lower() or 'email' in pg.url: + print(' polling mail for verification...') + mail = poll_voidash(cred, 240) if provider == 'voidash' else poll_imap_tonline(emailaddr, cred, 240) + if mail: + open(os.path.join(HERE, f'mail_{i}.json'), 'w', encoding='utf-8').write(mail) + m = re.search(r'\b(\d{6})\b', re.sub(r'https?://\S+', '', mail)) + code = m.group(1) if m else None + res['code'] = code + lk = re.search(r'https://[^"\\\s<]*(?:verify|confirm|otp|auth)[^"\\\s<]*', mail) + res['link'] = (lk.group(0) if lk else '')[:160] + print(f' code={code}') + if code: + try: + pg.wait_for_timeout(1500) + inputs_info = pg.evaluate("() => [...document.querySelectorAll('input')].map(e=>({t:e.type,ml:e.maxLength,n:e.name,vis:!!e.offsetParent}))") + res['otp_inputs'] = inputs_info + print(' otp inputs:', inputs_info) + # focus first visible input and type code char-by-char (OTP auto-advance) + pg.evaluate("() => { const inp=[...document.querySelectorAll('input')].find(e=>e.offsetParent && e.type!=='hidden'); if(inp) inp.focus(); }") + pg.keyboard.type(code, delay=220) + pg.wait_for_timeout(6000) # auto-submit window + if 'email-verification' in pg.url: + pg.evaluate(btn_text(pg, r'Продолжить|Continue|Verify|Подтвердить')) + pg.wait_for_timeout(8000) + except Exception as e: + res['code_err'] = str(e)[:120] + # ---- phone verification step (WorkOS SMS via 2no.pl) ---- + pg.wait_for_timeout(3000) + body_ph = re.sub(r'\s+', ' ', pg.evaluate('() => document.body.innerText'))[:400] + if 'телефон' in body_ph.lower() or 'phone' in body_ph.lower(): + print(' PHONE step:', body_ph[:150]) + ph_inputs = pg.evaluate("() => [...document.querySelectorAll('input')].filter(e=>e.offsetParent&&e.type!=='hidden').map(e=>({t:e.type,ml:e.maxLength,n:e.name,ph:e.placeholder}))") + res['phone_inputs'] = ph_inputs + print(' phone inputs:', ph_inputs) + # start SMS reader FIRST — chrome launch+login warms up while we fill fields + import subprocess + from datetime import datetime, timedelta + # reserve a FRESH 2nd-no number per registration (WorkOS binds phone to account) + stamp = int(time.time()) + rfile = os.path.join(HERE, f'reserve_{stamp}.json') + cfile = os.path.join(HERE, f'smscode_{stamp}.json') + min_ts = (datetime.now() - timedelta(minutes=120)).isoformat(timespec='seconds') + smslog = open(os.path.join(HERE, f'sms_reserve_{stamp}.log'), 'w', encoding='utf-8') + sms_proc = subprocess.Popen( + [PY311, os.path.join(HERE, 'sms2no_reserve.py'), *no_cred(), rfile, cfile, '360', min_ts], + stdout=smslog, stderr=subprocess.STDOUT, text=True, + cwd=HERE, env={**os.environ, 'PYTHONPATH': '', 'PYTHONIOENCODING': 'utf-8'}) + # wait for reservation (2no login + reserve/reuse ~40-120s) + phone_dyn = None + t0 = time.time() + while time.time() - t0 < 380: + if os.path.exists(rfile): + try: + phone_dyn = json.load(open(rfile, encoding='utf-8')) + break + except Exception: + pass + if sms_proc.poll() is not None and not os.path.exists(rfile): + break # reader died — check sms_reserve_*.log + time.sleep(2) + try: + smslog.close() + except Exception: + pass + if not phone_dyn or not phone_dyn.get('phone'): + res['err'] = 'reserve timeout' + raise RuntimeError('2no reserve timeout') + PHONE_DYN = str(phone_dyn['phone']) + res['phone'] = PHONE_DYN + res['number_id'] = phone_dyn.get('number_id') + print(' reserved:', PHONE_DYN) + # split into country_code + local_number (WorkOS split fields); 2no free pool = PL + if PHONE_DYN.startswith('+48'): + cc, local = '+48', re.sub(r'\D', '', PHONE_DYN[3:]) + else: + m_ph = re.match(r'(\+\d{1,3})(\d+)', PHONE_DYN) + cc, local = m_ph.group(1), m_ph.group(2) + filled_ph = pg.evaluate("""(v) => { + const inp=document.querySelector('input[name=country_code]'); + if(!inp) return 0; inp.focus(); + const setter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set; + setter.call(inp, v); inp.dispatchEvent(new Event('input',{bubbles:true})); + inp.dispatchEvent(new Event('change',{bubbles:true})); return 1; + }""", cc) + pg.wait_for_timeout(500) + ln = pg.query_selector('input[name=local_number]') + if ln: + ln.click() + pg.keyboard.type(local, delay=130) + filled_ph += 1 + pg.wait_for_timeout(800) + ph_vals = pg.evaluate("() => JSON.stringify({cc:document.querySelector('input[name=country_code]')?.value, ln:document.querySelector('input[name=local_number]')?.value})") + res['phone_values'] = ph_vals + print(' phone values:', ph_vals) + res['phone_filled'] = filled_ph + pg.wait_for_timeout(1200) + pg.evaluate(btn_text(pg, r'Отправить код|Send code|Продолжить|Continue')) + pg.wait_for_timeout(5000) + body_after_send = re.sub(r'\s+', ' ', pg.evaluate('() => document.body.innerText'))[:300] + res['after_phone_send'] = body_after_send + print(' after send:', body_after_send[:150]) + sms_code = None + t1 = time.time() + while time.time() - t1 < 420: + if os.path.exists(cfile): + try: + d = json.load(open(cfile, encoding='utf-8')) + sms_code = d.get('code') + res['sms_raw'] = json.dumps(d, ensure_ascii=False)[:200] + break + except Exception: + pass + if sms_proc.poll() is not None and time.time() - t1 > 30: + break # reader died without code file + time.sleep(3) + try: + if sms_proc.poll() is None: + sms_proc.kill() + except Exception: + pass + res['sms_code'] = sms_code + print(' sms code:', sms_code, '| raw:', str(res.get('sms_raw'))[:120]) + if sms_code: + try: + pg.evaluate("() => { const inp=[...document.querySelectorAll('input')].find(e=>e.offsetParent && e.type!=='hidden'); if(inp) inp.focus(); }") + pg.keyboard.type(sms_code, delay=200) + except Exception as e: + res['sms_type_err'] = str(e)[:150] + pg.wait_for_timeout(12000) # auto-submit + navigation window + try: + if re.search(r'Продолжить|Continue|Verify|Подтвердить', pg.evaluate('() => document.body.innerText')): + pg.evaluate(btn_text(pg, r'Продолжить|Continue|Verify|Подтвердить')) + pg.wait_for_timeout(9000) + except Exception: + pass # navigation in flight = good sign + try: + pg.wait_for_load_state('domcontentloaded', timeout=20000) + except Exception: + pass + try: + res['after_phone_code'] = re.sub(r'\s+', ' ', pg.evaluate('() => document.body.innerText'))[:300] + res['phone_url'] = pg.url + print(' after phone code url:', pg.url[:100]) + except Exception as e: + res['phone_state_err'] = str(e)[:120] + # final state + res['final_url'] = pg.url + res['final_body'] = re.sub(r'\s+', ' ', pg.evaluate('() => document.body.innerText'))[:400] + cks = pg.context.cookies() + res['cookies'] = [{'name': c['name'], 'value': c['value'], 'domain': c.get('domain')} for c in cks] if isinstance(cks, list) else str(cks)[:1000] + try: + res['local_storage'] = pg.evaluate("() => JSON.stringify(Object.fromEntries(Object.keys(localStorage).map(k=>[k,(localStorage.getItem(k)||'').slice(0,2000)])))") + except Exception: + pass + pg.screenshot(path=os.path.join(HERE, f'ok_{i}.png')) + if 'auth.type.com' not in pg.url: + res['ok'] = True + okc += 1 + print(f' [{i}] OK url={pg.url[:100]}') + else: + res['err'] = res.get('err') or 'stuck on auth' + print(f' [{i}] FAIL {res.get("err")}') + except StopIteration: + pass + except Exception as e: + res['err'] = str(e)[:250] + print(f' [{i}] EXC: {str(e)[:180]}') + finally: + if b: + try: + b.close() + except Exception: + pass + with open(OUT, 'a', encoding='utf-8') as f: + f.write(json.dumps(res, ensure_ascii=False) + '\n') + if res.get('email'): + with open(os.path.join(HERE, 'used_emails.txt'), 'a') as f: + f.write(res['email'] + '\n') + time.sleep(random.randint(5, 12)) + print(f'DONE ok={okc}/{n}') + +if __name__ == '__main__': + n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + provider = sys.argv[2] if len(sys.argv) > 2 else 'voidash' + run(n, provider) diff --git a/tools/typegw.py b/tools/typegw.py new file mode 100644 index 0000000..561c286 --- /dev/null +++ b/tools/typegw.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +"""typegw.py — OpenAI-compatible gateway over type.com account pool (oRPC reverse). +Run: python typegw.py [port] (default 8600). Key: TYPE_GW_KEY env or gw_key.txt or 'type-local-2026'. +Endpoints: /v1/chat/completions (stream+non-stream), /v1/models, /health, / (dashboard).""" +import sys, json, time, os, random, threading, urllib.request, urllib.error +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +sys.stdout.reconfigure(encoding='utf-8') + +HERE = os.path.dirname(os.path.abspath(__file__)) +POOL_PATH = os.path.join(HERE, 'pool.json') +PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8600 +KEY = os.environ.get('TYPE_GW_KEY') +if not KEY: + kf = os.path.join(HERE, 'gw_key.txt') + KEY = open(kf).read().strip() if os.path.exists(kf) else 'type-local-2026' + +B32 = '0123456789abcdefghjkmnpqrstvwxyz' +LOCK = threading.Lock() + +MODELS = [ + ('gpt-6.1-sol', 'openai', 'Codex 6.1 Sol (default)'), ('gpt-6-sol', 'openai', 'Codex 6 Sol'), + ('gpt-6-luna', 'openai', 'Codex 6 Luna (fast)'), ('gpt-6-astra', 'openai', 'Codex 6 Astra (reasoning)'), + ('gpt-5.5', 'openai', 'Codex 5.5'), ('gpt-5.6-sol', 'openai', 'Codex 5.6 Sol'), + ('gpt-5.6-terra', 'openai', 'Codex 5.6 Terra'), ('gpt-5.6-luna', 'openai', 'Codex 5.6 Luna (fast)'), + ('gpt-5.2-2025-12-11', 'openai', 'GPT-5.2'), ('gpt-5-mini-2025-08-07', 'openai', 'GPT-5 mini'), + ('claude-opus-5-5', 'anthropic', 'Claude Opus 5.5'), ('claude-fable-5-1', 'anthropic', 'Claude Fable 5.1'), + ('claude-fable-5', 'anthropic', 'Claude Fable 5'), ('claude-sonnet-5-5', 'anthropic', 'Claude Sonnet 5.5'), + ('claude-sonnet-5', 'anthropic', 'Claude Sonnet 5'), ('claude-sonnet-4-6', 'anthropic', 'Claude Sonnet 4.6'), + ('claude-opus-4-5-20251101', 'anthropic', 'Claude Opus 4.5'), ('claude-opus-4-6', 'anthropic', 'Claude Opus 4.6'), + ('claude-opus-4-8', 'anthropic', 'Claude Opus 4.8'), ('claude-opus-5', 'anthropic', 'Claude Opus 5'), + ('claude-haiku-5-5', 'anthropic', 'Claude Haiku 5.5'), ('claude-haiku-4-5-20251001', 'anthropic', 'Claude Haiku 4.5'), + ('gemini-3-flash-preview', 'google', 'Gemini 3 Flash'), ('gemini-3-pro-preview', 'google', 'Gemini 3 Pro'), + ('gemini-3.1-pro-preview', 'google', 'Gemini 3.1 Pro'), +] +MODEL_PROVIDER = {m: p for m, p, _ in MODELS} + +def msg_ulid(): + ts = int(time.time() * 1000) + t = '' + for _ in range(10): + t = B32[ts % 32] + t + ts //= 32 + if t[0] not in '01234567': + t = str(int(t[0], 32) % 8) + t[1:] + return 'msg_' + t + ''.join(random.choice(B32) for _ in range(16)) + +def load_pool(): + with LOCK: + try: + return json.load(open(POOL_PATH, encoding='utf-8')) + except Exception: + return [] + +def save_pool(pool): + with LOCK: + tmp = POOL_PATH + '.tmp' + json.dump(pool, open(tmp, 'w', encoding='utf-8'), indent=1) + os.replace(tmp, POOL_PATH) + +def orpc(acc, ep, payload, timeout=40): + req = urllib.request.Request('https://api.type.com/api/orpc/' + ep, + data=json.dumps({'json': payload}).encode(), headers={ + 'content-type': 'application/json', 'authorization': acc['token'], + 'origin': 'https://type.com', 'referer': 'https://type.com/', + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + return r.status, r.read().decode('utf-8', 'ignore') + except urllib.error.HTTPError as e: + return e.code, e.read().decode('utf-8', 'ignore') + except Exception as e: + return -1, str(e)[:300] + +def pick_account(pool, provider): + now = time.time() + cands = [a for a in pool if a.get('token') and a.get('channelId') + and a.get('quarantine_until', 0) < now and a.get('fails', 0) < 5] + if provider == 'openai': + byo = [a for a in cands if a.get('codex')] + if byo: cands = byo + if not cands: return None + cands.sort(key=lambda a: a.get('last_used', 0)) + return cands[0] + +def quarantine(acc, secs, reason): + pool = load_pool() + for a in pool: + if a['email'] == acc['email']: + a['quarantine_until'] = time.time() + secs + a['fails'] = a.get('fails', 0) + 1 + a['last_err'] = reason[:200] + save_pool(pool) + +def mark_used(acc): + pool = load_pool() + for a in pool: + if a['email'] == acc['email']: + a['last_used'] = time.time(); a['fails'] = 0 + save_pool(pool) + +def flatten_content(messages): + parts = [] + for m in messages: + role = m.get('role', 'user') + c = m.get('content') + if isinstance(c, list): + c = ' '.join(x.get('text', '') for x in c if isinstance(x, dict)) + if role == 'system': + parts.append('[System] ' + str(c)) + elif role == 'assistant': + parts.append('[Assistant history] ' + str(c)[:500]) + else: + parts.append(str(c)) + return '\n\n'.join(parts) + +def send_and_wait(acc, text, provider, model, deadline=420, on_delta=None): + mid = msg_ulid() + payload = { + 'id': mid, 'channelId': acc['channelId'], + 'parentMessageId': None, 'subchannelId': None, 'replyToId': None, + 'content': {'version': '1.0', 'blocks': [{'type': 'paragraph', 'children': [{'type': 'text', 'text': text}]}]}, + 'contentSchemaVersion': '1.0', 'textContent': text, 'botName': None, + 'isBotResponse': False, 'isStreaming': False, 'hasError': False, + 'fileIds': [], 'timezone': 'Europe/Kyiv', 'aiProvider': provider, 'modelId': model, + 'triggerTimestamp': int(time.time() * 1000), 'responseIndex': 0, + 'agentToggleEnabled': True, 'replyMode': 'chat', 'metadata': None, + } + st, bd = orpc(acc, 'messages/createMessage', payload) + if st == 403: + quarantine(acc, 3600, bd[:200]) + return None, '403: ' + bd[:200] + if st == 401: + quarantine(acc, 7200, '401 token expired') + return None, '401 token expired' + if st != 200: + quarantine(acc, 600, f'{st}: {bd[:150]}') + return None, f'createMessage {st}: {bd[:300]}' + t0 = time.time() + last_len = 0 + while time.time() - t0 < deadline: + st, bd = orpc(acc, 'messages/getMessagesPaginated', + {'channelId': acc['channelId'], 'limit': 25, 'direction': 'backward', + 'parentMessageId': mid}, 60) + if st == 200: + msgs = json.loads(bd)['json'].get('messages', []) + bots = [m for m in msgs if (m.get('isBotResponse') or m.get('botName')) + and (m.get('replyToId') == mid or m.get('parentMessageId') == mid + or (m.get('triggerTimestamp') or 0) >= payload['triggerTimestamp'] - 5000 + or m['id'] > mid)] + for m in bots: + txt = m.get('textContent') or '' + if on_delta and len(txt) > last_len: + on_delta(txt[last_len:]); last_len = len(txt) + if txt and not m.get('isStreaming'): + if m.get('hasError'): + return None, 'agent error: ' + txt[:300] + return txt, None + if m.get('hasError'): + return None, 'agent error: ' + (txt or json.dumps(m.get('metadata'))[:200]) + time.sleep(3) + return None, 'timeout waiting agent reply' + +class H(BaseHTTPRequestHandler): + def log_message(self, *a): pass + + def _json(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 _auth(self): + a = self.headers.get('authorization', '') + return a in ('Bearer ' + KEY, KEY) + + def do_GET(self): + if self.path == '/health': + return self._json(200, {'ok': True}) + if self.path == '/v1/models': + return self._json(200, {'object': 'list', 'data': [ + {'id': m, 'object': 'model', 'owned_by': p, 'description': n} for m, p, n in MODELS]}) + if self.path == '/': + pool = load_pool() + now = time.time() + rows = ''.join( + f"{a['email']}{'BYO-codex' if a.get('codex') else 'platform'}" + f"{a.get('billing_status','?')}{str(a.get('trial_end'))[:10]}" + f"{'QUAR' if a.get('quarantine_until',0)>now else ('dead' if a.get('fails',0)>=5 else 'ok')}" + f"{a.get('last_err','')[:60]}" for a in pool) + html = f"

type.com gateway :{PORT}

pool: {len(pool)} | models: {len(MODELS)}

{rows}
" + b = html.encode() + self.send_response(200); self.send_header('content-type', 'text/html; charset=utf-8') + self.send_header('content-length', str(len(b))); self.end_headers(); self.wfile.write(b) + return + self._json(404, {'error': 'not found'}) + + def do_POST(self): + if self.path != '/v1/chat/completions': + return self._json(404, {'error': 'not found'}) + if not self._auth(): + return self._json(401, {'error': 'invalid key'}) + ln = int(self.headers.get('content-length', 0)) + try: + req = json.loads(self.rfile.read(ln)) + except Exception: + return self._json(400, {'error': 'bad json'}) + model = req.get('model', 'gpt-6.1-sol') + model = model.split('/')[-1] + if model not in MODEL_PROVIDER: + model = 'gpt-6.1-sol' + provider = MODEL_PROVIDER[model] + text = flatten_content(req.get('messages', [])) + if not text.strip(): + return self._json(400, {'error': 'empty messages'}) + stream = bool(req.get('stream')) + pool = load_pool() + acc = pick_account(pool, provider) + if not acc: + return self._json(503, {'error': {'message': 'no live accounts in pool', 'type': 'pool_empty'}}) + cid = 'chatcmpl-' + msg_ulid()[4:] + created = int(time.time()) + if stream: + self.send_response(200) + self.send_header('content-type', 'text/event-stream') + self.send_header('cache-control', 'no-cache') + self.end_headers() + def emit(delta, finish=None): + ch = {'delta': {'content': delta}} if delta else {'delta': {}} + if finish: ch['finish_reason'] = finish + chunk = {'id': cid, 'object': 'chat.completion.chunk', 'created': created, + 'model': model, 'choices': [{'index': 0, **ch}]} + try: + self.wfile.write(f'data: {json.dumps(chunk, ensure_ascii=False)}\n\n'.encode()); self.wfile.flush() + except Exception: pass + def on_delta(d): emit(d) + full, err = send_and_wait(acc, text, provider, model, on_delta=on_delta) + if err and not full: + emit(f'[gateway error] {err}', 'stop') + else: + mark_used(acc) + try: self.wfile.write(b'data: [DONE]\n\n'); self.wfile.flush() + except Exception: pass + return + full, err = send_and_wait(acc, text, provider, model) + if err: + return self._json(502, {'error': {'message': err, 'type': 'upstream', 'account': acc['email']}}) + mark_used(acc) + self._json(200, {'id': cid, 'object': 'chat.completion', 'created': created, 'model': model, + 'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': full}, 'finish_reason': 'stop'}], + 'usage': {'prompt_tokens': len(text) // 4, 'completion_tokens': len(full) // 4, + 'total_tokens': (len(text) + len(full)) // 4}}) + +if __name__ == '__main__': + srv = ThreadingHTTPServer(('0.0.0.0', PORT), H) + print(f'typegw on :{PORT} pool={POOL_PATH} models={len(MODELS)}', flush=True) + srv.serve_forever() diff --git a/tools/ui_probe.py b/tools/ui_probe.py new file mode 100644 index 0000000..f5b34bd --- /dev/null +++ b/tools/ui_probe.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +"""ui_probe2.py — full storage injection (cookies+ss+ls) → logged-in type.com UI → models + billing buttons.""" +import sys, os, json, time +sys.stdout.reconfigure(encoding='utf-8') +HERE = os.path.dirname(os.path.abspath(__file__)) +S = json.load(open(os.path.join(HERE, 'storages.json'), encoding='utf-8')) +import cloakbrowser + +def dump_ui(pg, tag): + print(f"\n== [{tag}] url={pg.url}", flush=True) + btns = pg.evaluate("""() => [...document.querySelectorAll('button,a,[role=button],[role=menuitem],[role=option],li,h1,h2,h3')].filter(e=>e.offsetParent!==null).map(e=>(e.innerText||'').trim().split('\\n')[0]).filter(t=>t&&t.length<70)""") + seen = [] + for b in btns: + if b not in seen: seen.append(b) + print("UI:", json.dumps(seen[:60], ensure_ascii=False), flush=True) + try: pg.screenshot(path=os.path.join(HERE, f'ui2_{tag}.png')) + except Exception: pass + +with cloakbrowser.launch(headless=True) as browser: + ctx = browser.new_context() if hasattr(browser, 'new_context') else None + pg = (ctx or browser).new_page() + # 1. same-origin static page to seed storage + try: + pg.goto('https://type.com/favicon.ico', wait_until='domcontentloaded', timeout=30000) + except Exception: + pass + pg.goto('https://type.com/robots.txt', wait_until='domcontentloaded', timeout=30000) + # 2. cookies + cks = [] + for part in S['cookie'].split(';'): + part = part.strip() + if '=' in part: + n, v = part.split('=', 1) + cks.append({'name': n.strip(), 'value': v, 'domain': '.type.com', 'path': '/'}) + try: + (ctx or pg.context).add_cookies(cks) + print("cookies injected:", len(cks), flush=True) + except Exception as e: + print("cookie fail:", str(e)[:150], flush=True) + # 3. ss + ls + pg.evaluate("""(d) => { + for (const [k,v] of Object.entries(d.ss)) sessionStorage.setItem(k, v); + for (const [k,v] of Object.entries(d.ls)) localStorage.setItem(k, v); + }""", {'ss': S['ss'], 'ls': S['ls']}) + print("storage injected; authToken len:", len(S['ss'].get('authToken','')), flush=True) + # 4. go home + pg.goto('https://type.com/home', wait_until='domcontentloaded', timeout=60000) + pg.wait_for_timeout(8000) + dump_ui(pg, 'home') + print("BODY:", pg.inner_text('body')[:1000].replace('\n', ' | '), flush=True) + tok_now = pg.evaluate("() => sessionStorage.getItem('authToken')") + print("authToken after load:", (tok_now or '')[:12], 'len', len(tok_now or ''), flush=True) + + # 5. model picker in composer + for sel in ['textarea', '[contenteditable=true]', 'div[role=textbox]']: + el = pg.query_selector(sel) + if el and el.is_visible(): + el.click(); pg.wait_for_timeout(1500); break + dump_ui(pg, 'composer') + cand = pg.evaluate("""() => [...document.querySelectorAll('button,[role=combobox]')].filter(e=>e.offsetParent!==null).map(e=>(e.innerText||e.getAttribute('aria-label')||'').trim()).filter(t=>/claude|gpt|gemini|model|sonnet|opus/i.test(t)).slice(0,8)""") + print("MODEL BUTTONS:", cand, flush=True) + for c in cand[:2]: + try: + pg.get_by_text(c, exact=False).first.click() + pg.wait_for_timeout(3000) + dump_ui(pg, 'models') + break + except Exception as e: + print("click fail", str(e)[:100]) + + # 6. hunt billing/upgrade buttons + for label in ['Upgrade', 'upgrade', 'Add a credit card', 'Add card', 'Billing', 'billing', 'Start trial', 'Choose a plan', 'Get started for free', 'Settings']: + try: + loc = pg.get_by_text(label, exact=True).first + if loc.is_visible(): + print(f"CLICK [{label}]", flush=True) + loc.click(); pg.wait_for_timeout(5000) + dump_ui(pg, 'after_' + label.replace(' ','_')[:14]) + print("BODY:", pg.inner_text('body')[:900].replace('\n', ' | '), flush=True) + break + except Exception: + pass +print("DONE", flush=True) diff --git a/tools/ws_new2.py b/tools/ws_new2.py new file mode 100644 index 0000000..d7e724a --- /dev/null +++ b/tools/ws_new2.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +"""ws_new2.py — create second workspace via UI workspace-switcher, capture API endpoint + checkout URL.""" +import json, os, re, sys, time +sys.stdout.reconfigure(encoding='utf-8') +import cloakbrowser + +HERE = os.path.dirname(os.path.abspath(__file__)) +S = json.load(open(os.path.join(HERE, 'storages.json'), encoding='utf-8')) +WSNAME = 'novalab' + str(int(time.time()) % 1000) +log = lambda *a: print(*a, flush=True) +api_calls = [] + +with cloakbrowser.launch(headless=True) as browser: + pg = browser.new_page() + ctx = pg.context + pg.on('request', lambda r: api_calls.append(r.url) if 'api.type.com' in r.url else None) + try: + cks = [] + for part in S['cookie'].split(';'): + part = part.strip() + if not part or '=' not in part: continue + k, v = part.split('=', 1) + cks.append({'name': k.strip(), 'value': v, 'domain': '.type.com', 'path': '/'}) + if cks: ctx.add_cookies(cks) + except Exception as e: + log("cookie fail:", str(e)[:100]) + pg.goto('https://type.com/', wait_until='domcontentloaded', timeout=90000) + pg.wait_for_timeout(2500) + pg.evaluate("""(d) => { + for (const [k,v] of Object.entries(d.ss)) sessionStorage.setItem(k, v); + for (const [k,v] of Object.entries(d.ls)) localStorage.setItem(k, v); + }""", {'ss': S['ss'], 'ls': S['ls']}) + pg.goto('https://type.com/voidash/inbox', wait_until='domcontentloaded', timeout=90000) + pg.wait_for_timeout(6000) + # close cookie banner + try: + pg.get_by_text('Reject All', exact=True).first.click(timeout=3000) + pg.wait_for_timeout(800) + except Exception: pass + log("url:", pg.url) + # open workspace switcher: element containing workspace name in sidebar + opened = pg.evaluate("""() => { + const els = [...document.querySelectorAll('button,[role=button],[class*=workspace],[class*=switcher]')] + .filter(e=>e.offsetParent!==null && /voidash/i.test(e.innerText||'')); + if (els.length) { els[0].click(); return els[0].innerText.trim().slice(0,50); } + return null; }""") + log("switcher clicked:", opened) + pg.wait_for_timeout(2500) + pg.screenshot(path=os.path.join(HERE, 'ws2_menu.png')) + menu = pg.evaluate("""() => [...document.querySelectorAll('[role=menuitem],[role=menu] *,button,a')] + .filter(e=>e.offsetParent!==null && (e.innerText||'').trim()) + .map(e=>(e.innerText||'').trim().slice(0,60)).slice(0,60)""") + log("menu items:", json.dumps(sorted(set(menu))[:40], ensure_ascii=False)) + # find create-workspace item + clicked = pg.evaluate("""() => { + const re = /create.*workspace|создать.*пространств|new workspace|новое пространство|create.*organization/i; + const els = [...document.querySelectorAll('[role=menuitem],button,a')] + .filter(e=>e.offsetParent!==null && re.test(e.innerText||'')); + if (els.length) { els[0].click(); return els[0].innerText.trim().slice(0,50); } + return null; }""") + log("create clicked:", clicked) + for step in range(10): + pg.wait_for_timeout(5000) + url = pg.url + body = re.sub(r'\s+', ' ', pg.evaluate('() => document.body.innerText'))[:500] + log(f"--- s{step} {url[:110]}") + log(" ", body[:300]) + if 'pay.type.com' in url or 'checkout' in url: + open(os.path.join(HERE, 'ws_ck_url.txt'), 'w').write(url) + log("CHECKOUT CAPTURED"); break + inputs = pg.evaluate("""() => [...document.querySelectorAll('input:not([type=hidden]),textarea')] + .filter(e=>e.offsetParent!==null).map(e=>({id:e.id,name:e.name,ph:e.placeholder||'',type:e.type||''}))""") + if inputs: log(" inputs:", json.dumps(inputs, ensure_ascii=False)[:300]) + pg.screenshot(path=os.path.join(HERE, f'ws2_{step}.png')) + # fill first text input with ws name + for inp in inputs: + if inp['type'] in ('text', ''): + sel = f"#{inp['id']}" if inp['id'] else (f"input[name='{inp['name']}']" if inp['name'] else None) + if sel: + try: pg.locator(sel).first.fill(WSNAME); log(" filled", sel) + except Exception as e: log(" fill fail", str(e)[:60]) + break + nxt = pg.evaluate("""() => { + const btns = [...document.querySelectorAll('button')].filter(b=>b.offsetParent!==null && !b.disabled); + const re = /продолжить|continue|create|создать|get started|начать|start.*trial|next|далее|subscribe|подписаться/i; + const b = btns.find(x=>re.test((x.innerText||'').trim())); + if (b) { b.click(); return (b.innerText||'').trim().slice(0,40); } + const f = document.querySelector('form'); if (f) { f.requestSubmit(); return 'form-submit'; } + return null; }""") + log(" clicked:", nxt) + if not nxt and not inputs and step > 2: break + log("FINAL:", pg.url[:150]) +ws_create = [u for u in api_calls if re.search(r'create|onboard|workspace|organiz', u, re.I)] +log("API create-like calls:", json.dumps(ws_create[:10], indent=1)) +log("ALL api calls:", json.dumps(sorted(set(u.split('orpc/')[-1][:60] for u in api_calls))[:30], indent=1))