ctxdev autoreg v2: t-online flow, grant banner form, VPS IMAP read, proxy pool loop, dash login
This commit is contained in:
+14
-10
@@ -1,12 +1,16 @@
|
||||
gmail_env.json
|
||||
2cap_key.txt
|
||||
bank.jsonl
|
||||
bank2.jsonl
|
||||
acct_ctx*.json
|
||||
apikeys.json
|
||||
mail_pool.txt
|
||||
bank*.jsonl
|
||||
t_used.json
|
||||
z_acct_*.json
|
||||
t_acct_*.json
|
||||
r_acct_*.json
|
||||
proxies_live.json
|
||||
proxies_fast.json
|
||||
z_page_*.txt
|
||||
*.log
|
||||
*.png
|
||||
chrome_prof*/
|
||||
js/
|
||||
js2/
|
||||
*.session
|
||||
chrome_*/
|
||||
.env
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyc
|
||||
|
||||
@@ -1,99 +1,136 @@
|
||||
# contextdev-autoreg
|
||||
|
||||
Автоматическая регистрация аккаунтов [context.dev](https://www.context.dev/) через
|
||||
агентский claim-флоу и сбор API-ключей `ctxt_secret_*` в банк для локального шлюза.
|
||||
Авторегистрация аккаунтов [context.dev](https://www.context.dev/) через агентский
|
||||
claim-флоу и сбор API-ключей `ctxt_secret_*` в банк для локального шлюза `ctx_shim`.
|
||||
|
||||
Промо-код `SPOOKY10K` (10 000 кредитов на новый аккаунт) в этой сборке **мёртв** —
|
||||
платформа закрыла его и массово отключила ключи фермы. Репозиторий оставлен как
|
||||
рабочая механика флоу: полезен, когда появляется новый промокод/оффер.
|
||||
Сборка 2026-10-31: переписана под актуальный флоу (грант «1,000 extra credits» на
|
||||
странице claim, форма за грант-баннером, почта t-online, подтверждение email в браузере).
|
||||
|
||||
## Что делает
|
||||
## Статус платформы (проверено 31.10.2026)
|
||||
|
||||
1. `POST https://www.context.dev/agent/identity` (`type=service_auth`) — создаёт
|
||||
registration и отдаёт `claim_token` + `user_code` (6 цифр) + `verification_uri`.
|
||||
2. Реальный Chrome по CDP открывает `verification_uri`, закрывает cookie-баннер,
|
||||
заполняет форму (full name / work email / password) и проходит Firebase App Check
|
||||
+ reCAPTCHA Enterprise.
|
||||
3. Ветка Firebase: `accounts:signUp` → `/api/auth/ensure-user` → `/api/login`.
|
||||
4. `user_code` подтверждает claim (`/api/agent/claim/confirm`), затем письмо из Gmail
|
||||
по IMAP даёт ссылку подтверждения email.
|
||||
5. Редим промокода через tRPC: `organization.redeemCreditPackage`, `organization_id`
|
||||
берётся из URL `/o/<uuid>`.
|
||||
6. API-ключ и метаданные аккаунта пишутся в `bank.jsonl`.
|
||||
| Что | Факт |
|
||||
|---|---|
|
||||
| Free tier | 1 000 кредитов/мес, без карты, 2 concurrent — `/pricing` 200 |
|
||||
| Промо `SPOOKY10K` | мёртв: `400 That credit code is invalid, expired, or unavailable` |
|
||||
| Грант за регистрацию | баннер «Your agent found you **1,000 extra credits**» есть, но после `verify-email` часто `Your account has been flagged for manual review` → `token 400 invalid_grant "Unable to provision credentials"` |
|
||||
| gmail +алиасы | `Account blocked` сразу после verify — домен в чёрном списке |
|
||||
| t-online | регистрация проходит, письмо доходит, `Email verified` — самая рабочая почва |
|
||||
| reCAPTCHA Enterprise | sitekey `6LeuusEtAAAAAPqPz6YMwE55dkvrusHbmzipL11N`, action `agent_signup_details_submit`. Датацентр/мобильный/free-прокси проходят нестабильно. Camoufox и 2captcha-токены → `403 App attestation failed` |
|
||||
| Ключи прошлой фермы | 16/16 `401 Your API key is disabled`, балансы 0 — платформа вычистила пачку |
|
||||
|
||||
## Почему нужен именно настоящий Chrome
|
||||
Вывод: 1–2 аккуратных аккаунта в сутки с чистого residential-прокси; пачкой бессмысленно.
|
||||
|
||||
Firebase App Check проверяет attestation. Camoufox и токены 2captcha дают
|
||||
`403 App attestation failed` на `exchangeRecaptchaEnterpriseToken`. Проходит только
|
||||
реальный Chrome (`--remote-debugging-port`), подключённый Playwright'ом через
|
||||
`connect_over_cdp`. С датацентр-IP reCAPTCHA обычно отбивает (`recaptcha rejected`),
|
||||
нужен residential/мобильный egress.
|
||||
## Флоу (что делает `reg_t3.py`)
|
||||
|
||||
## Файлы
|
||||
1. `POST https://www.context.dev/agent/identity` (`type=service_auth`, `login_hint=<mail>`)
|
||||
→ `claim_token`, `claim.verification_uri`, `claim.user_code` (6 цифр), `claim_url`.
|
||||
Делается через `CTX_ID_PROXY` (капчи на этом шаге нет).
|
||||
2. Реальный Chrome по CDP (`chrome_up.py`) открывает `verification_uri` через `CTX_CHROME_PROXY`.
|
||||
На странице — **грант-баннер сверху и та же форма ниже** (`#name`, `input[type=email]`,
|
||||
`#password`, чекбокс политики). Кнопка `Create account & connect` в HTML `disabled`,
|
||||
пока поля пустые — ждать её состояния бессмысленно, надо проверять наличие `#password`.
|
||||
3. Submit → «Confirm agent setup» → ввод 6-значного `user_code` → «Your setup code is confirmed.
|
||||
We sent a verification link».
|
||||
4. Письмо читается **через VPS по SSH** (`CTX_VPS`), потому что t-online IMAP рвёт соединение
|
||||
с домашнего IP. Скрипт отдаёт ссылку `verify-email?...`.
|
||||
5. Ссылка открывается **в том же Chrome**, кнопка `Verify email address` → `Email verified`.
|
||||
6. Возврат на `verification_uri`, при необходимости `I've verified my email`, повторный ввод кода.
|
||||
7. `POST /oauth2/token` `grant_type=urn:workos:agent-auth:grant-type:claim` → `access_token`
|
||||
= API-ключ `ctxt_secret_*` (44 симв.). Пишется в `bank.jsonl`, страница дампится в
|
||||
`z_page_<mail>.txt` (ключ может быть показан прямо там).
|
||||
|
||||
| Файл | Назначение |
|
||||
|------|------------|
|
||||
| `chrome_up.py` | поднимает Chrome с CDP-портом и прокси (`CTX_CDP_PORT`, `CTX_CHROME_PROF`, `CTX_CHROME_PROXY`) |
|
||||
| `ctx_farm2.py` | воркер одного аккаунта: identity → браузер → код → email → claim → редим → ключ |
|
||||
| `ctx_wave.py` | волна: батчи по `CTX_BATCH`, пауза `CTX_PAUSE`, опциональная ротация egress |
|
||||
| `ctx_shim.py` | локальный OpenAI-независимый шлюз `:8913` (`/search /scrape /map /answers /status`) с ротацией ключей |
|
||||
| `verify_keys.py` | проверка банка через `GET /v1/org/logs` → `credits_remaining` |
|
||||
|
||||
## Установка
|
||||
## Быстрый старт
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
playwright install chromium # для connect_over_cdp нужен установленный Chromium-драйвер
|
||||
|
||||
`gmail_env.json` в рабочем каталоге:
|
||||
cp env.example .env && vi .env # пул почт, VPS, прокси
|
||||
cp mail_pool.txt.example mail_pool.txt # формат: email:password (по строке)
|
||||
|
||||
```json
|
||||
{"gm": "you@gmail.com", "gp": "app-password"}
|
||||
```
|
||||
# 1) поднять Chrome + пройти полный цикл на одном адресе
|
||||
python reg_t3.py
|
||||
|
||||
Плюс-алиасы (`you+ctx450@gmail.com`) читаются тем же ящиком.
|
||||
# 2) перебор прокси до успеха (стоп по SAVED)
|
||||
python t3_loop.py 10
|
||||
|
||||
## Запуск
|
||||
# 3) логин в дашборд (если claim завершён, а ключ надо достать из UI)
|
||||
python login_dash3.py <email> <password>
|
||||
|
||||
```bash
|
||||
# 1. Chrome с CDP и прокси
|
||||
CTX_CDP_PORT=9225 CTX_CHROME_PROF=chrome_prof \
|
||||
CTX_CHROME_PROXY=http://127.0.0.1:8899 python chrome_up.py
|
||||
|
||||
# 2. Волна на 30 аккаунтов
|
||||
CTX_CDP=http://127.0.0.1:9225 CTX_CDP_PORT=9225 \
|
||||
CTX_CHROME_PROXY=http://127.0.0.1:8899 CTX_PROXY=http://127.0.0.1:8899 \
|
||||
CTX_ID_PROXIES="http://127.0.0.1:8899" CTX_BANK=bank.jsonl \
|
||||
CTX_PAUSE=75 CTX_BATCH=2 CTX_ROTATE=0 python ctx_wave.py 460 30
|
||||
|
||||
# 3. Шлюз
|
||||
python ctx_shim.py --port 8913 --bank bank.jsonl
|
||||
|
||||
# 4. Проверка банка
|
||||
python verify_keys.py
|
||||
# 4) собрать/обновить пул free-прокси
|
||||
python get_proxies.py
|
||||
```
|
||||
|
||||
## Переменные окружения
|
||||
|
||||
`CTX_CDP`, `CTX_CDP_PORT`, `CTX_CHROME_PROF`, `CTX_CHROME_PROXY`, `CTX_PROXY`,
|
||||
`CTX_ID_PROXIES` (пул для шага identity, через запятую), `CTX_BANK`, `CTX_PAUSE`,
|
||||
`CTX_BATCH`, `CTX_ROTATE`.
|
||||
| Переменная | Смысл | Дефолт |
|
||||
|---|---|---|
|
||||
| `CTX_MAIL_POOL` | файл `email:password` | `./mail_pool.txt` |
|
||||
| `CTX_VPS` | SSH-хост для чтения IMAP (`root@host`) | пусто (обязательна) |
|
||||
| `CTX_IMAP_HOST` | IMAP-сервер почты | `secureimap.t-online.de` |
|
||||
| `CTX_CHROME_PROXY` | прокси для браузера (residential) | пусто = напрямую |
|
||||
| `CTX_ID_PROXY` | прокси для `/agent/identity` | `http://127.0.0.1:8899` |
|
||||
| `CTX_CDP_PORT` | порт CDP | `9311` (reg_t3), `9223` (chrome_up) |
|
||||
| `CTX_CHROME_PROF` | каталог профиля Chrome | `./chrome_prof` |
|
||||
| `CTX_CHROME_BIN` | путь к chrome.exe | стандартный Windows-путь |
|
||||
|
||||
## Гейты, на которые упирается флоу
|
||||
## Питфолы (все проверены на живой платформе)
|
||||
|
||||
- **Cloudflare по egress.** После серии регистраций IP получает `403` на весь домен,
|
||||
включая главную. Лечится сменой IP (мобильный PPP), не заголовками: `curl`,
|
||||
`requests`, `curl_cffi` получают одинаковый `403`.
|
||||
- **reCAPTCHA Enterprise на датацентр-IP.** `recaptcha rejected` при заполненной форме.
|
||||
- **Промокод одноразовый на организацию.** Повторный редим → `400 That credit code is
|
||||
invalid, expired, or unavailable` или `403 You cannot redeem credits for this
|
||||
organization`.
|
||||
- **Флаг антифрода.** `Your account has been flagged for manual review` — аккаунт
|
||||
живёт, но редим закрыт.
|
||||
- **Отзыв кредитов и отключение ключей.** Итог этой сборки: 16 аккаунтов, ~15 000
|
||||
кредитов, затем все ключи → `401 Your API key is disabled`, баланс `0`.
|
||||
- **Один Chrome на профиль.** Второй `connect_over_cdp` к занятому профилю висит 60 с.
|
||||
Перед прогоном убивать `chrome.exe` с этим `--user-data-dir` через psutil и чистить
|
||||
`SingletonLock / SingletonSocket / SingletonCookie / DevToolsActivePort`.
|
||||
- **env не пробрасывается сам.** `subprocess.run([... chrome_up.py])` без `env=os.environ`
|
||||
поднимает Chrome на дефолтном порту → «CDP: up» и сразу «chrome down» в логах.
|
||||
- **CDP-адрес.** `ctx_farm2.py` исторически читал `CTX_CDP`, а не `CTX_CDP_PORT` — из-за
|
||||
этого connect шёл на 9223 при живом Chrome на другом порту.
|
||||
- **claim_token живёт ~10 минут.** Если письмо ищется дольше — `400 expired_token`
|
||||
(«Claim link expired»), цикл надо начинать заново.
|
||||
- **verify-ссылка одноразовая.** Один `GET` (даже curl'ом) — и в браузере
|
||||
«Verification link did not work». Открывать только браузером и сразу.
|
||||
- **Письмо приходит не всегда.** У части t-online-ящиков `FROM context.dev` = 0 писем
|
||||
(антиспам провайдера), проверять `IMAP SEARCH FROM context.dev`, а не «последние 10».
|
||||
- **После пароля в логине** форма может вернуться на `/login` — это recaptcha на втором
|
||||
шаге, а не неверный пароль. `POST /api/login` без токена всегда
|
||||
`400 {"error":"recaptcha_invalid_request"}`.
|
||||
- **`chrome_up.py` с прокси** требует `--proxy-bypass-list=<-loopback>`, иначе CDP-порт
|
||||
уходит в прокси и Playwright не подключается.
|
||||
- **ZTE-модем**: `newapi_lib.zte_rotate` не работает на Python 3.11 (`POST data should be bytes`),
|
||||
рабочий модуль — свой `rotate.py`; внешний IP может не меняться часами (sticky).
|
||||
|
||||
## Статус
|
||||
## Файлы
|
||||
|
||||
Механика отработана, промо закрыто. Цифры последнего прогона: 16 аккаунтов с ключами,
|
||||
пик 15 000 кредитов, через несколько часов — `0` живых ключей.
|
||||
| Файл | Роль |
|
||||
|---|---|
|
||||
| `reg_t3.py` | основной воркер: identity → signup → код → письмо → verify → token → `bank.jsonl` |
|
||||
| `chrome_up.py` | запуск реального Chrome с CDP и прокси |
|
||||
| `t3_loop.py` | перебор прокси-пула до первого `SAVED` |
|
||||
| `login_dash3.py` | логин в дашборд и выемка ключа из UI |
|
||||
| `fin_one.py` | доводка конкретного `claim_token` (когда Chrome умер посреди флоу) |
|
||||
| `get_proxies.py` | сбор и проверка free-прокси (`proxies_live.json`, `proxies_fast.json`) |
|
||||
| `login_loop.py` | перебор прокси для логина |
|
||||
| `ctx_shim.py` | локальный OpenAI-совместимый шлюз над банком ключей (`:8913`, `/search /scrape /map /answers /status`) |
|
||||
| `verify_keys.py` | проверка живости ключей через `/v1/org/logs` |
|
||||
|
||||
## Шим
|
||||
|
||||
```bash
|
||||
python ctx_shim.py # :8913, ротация ключей из bank.jsonl раз в 30 с
|
||||
curl -s localhost:8913/status
|
||||
curl -s -X POST localhost:8913/scrape -d '{"url":"https://example.com"}'
|
||||
```
|
||||
|
||||
`401/402/403` — ключ паркуется, `429` — ротация (free plan: 2 concurrent на ключ).
|
||||
|
||||
## Эндпоинты, на которых всё держится
|
||||
|
||||
- `POST https://www.context.dev/agent/identity`
|
||||
- `POST https://www.context.dev/oauth2/token` (`urn:workos:agent-auth:grant-type:claim`)
|
||||
- `https://www.context.dev/verify-email?code=...` (одноразовая)
|
||||
- `GET https://api.context.dev/v1/org/logs` (проверка ключа и остатка кредитов)
|
||||
- `POST https://api.context.dev/v1/web/scrape|search|urls|answers`
|
||||
|
||||
## Этическая рамка
|
||||
|
||||
Репозиторий — про автоматизацию собственных регистраций и тестирование лимитов
|
||||
free-тира. Ключи чужих аккаунтов не собираются, пароли в репозиторий не попадают
|
||||
(`mail_pool.txt`, `bank.jsonl`, `*.json` с кредами — в `.gitignore`).
|
||||
+4
-3
@@ -1,9 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
"""Launch real Chrome with CDP on 9223 (detached) for context.dev flow."""
|
||||
import os, subprocess, time, json, urllib.request
|
||||
import os, sys, subprocess, time, json, urllib.request
|
||||
|
||||
CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
|
||||
PROF = os.environ.get("CTX_CHROME_PROF", r"C:\Users\User\tmp\ctxdev\chrome_prof")
|
||||
CHROME = os.environ.get("CTX_CHROME_BIN", r"C:\Program Files\Google\Chrome\Application\chrome.exe")
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
PROF = os.environ.get("CTX_CHROME_PROF", os.path.join(BASE, "chrome_prof"))
|
||||
PORT = int(os.environ.get("CTX_CDP_PORT", "9223"))
|
||||
PROXY = os.environ.get("CTX_CHROME_PROXY", "")
|
||||
os.makedirs(PROF, exist_ok=True)
|
||||
|
||||
-351
@@ -1,351 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""Context.dev farm v2: robust chrome lifecycle + tRPC redeem + email verify retries.
|
||||
|
||||
Usage: ctx_farm2.py <start_idx> <count>
|
||||
"""
|
||||
import json, os, sys, time, re, random, string, subprocess, imaplib, email
|
||||
import requests
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
START, COUNT = int(sys.argv[1]), int(sys.argv[2])
|
||||
PROMO = "SPOOKY10K"
|
||||
CDP = os.environ.get("CTX_CDP", "http://127.0.0.1:9223")
|
||||
PROXY_URL = os.environ.get("CTX_PROXY", "")
|
||||
PXY = {"http": PROXY_URL, "https": PROXY_URL} if PROXY_URL else None
|
||||
ID_PROXIES = [p for p in os.environ.get("CTX_ID_PROXIES", "").split(",") if p.strip()]
|
||||
|
||||
|
||||
def id_pxy():
|
||||
"""identity runs on a rotating pool (datacenter IPv6 is fine - no captcha there)."""
|
||||
if ID_PROXIES:
|
||||
p = random.choice(ID_PROXIES).strip()
|
||||
return {"http": p, "https": p}
|
||||
return PXY
|
||||
NAMES = ["Nikita Refor", "Alex Grobman", "Dan Vorobets", "Max Koval", "Yuri Larin", "Oleg Sydor", "Kirill Bolt"]
|
||||
G = json.load(open(r"gmail_env.json"))
|
||||
|
||||
|
||||
def log(*a):
|
||||
print(*a, flush=True)
|
||||
|
||||
|
||||
def cdp_ok():
|
||||
try:
|
||||
return requests.get(CDP + "/json/version", timeout=3).status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def ensure_chrome():
|
||||
if cdp_ok():
|
||||
return True
|
||||
subprocess.run([sys.executable, os.path.join(BASE, "chrome_up.py")], check=False)
|
||||
for _ in range(20):
|
||||
if cdp_ok():
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def identity(mail, tag):
|
||||
r = requests.post("https://www.context.dev/agent/identity", json={
|
||||
"type": "service_auth", "login_hint": mail,
|
||||
"api_key_name": "hermes-%s" % tag, "client_name": "Hermes"}, timeout=60, proxies=id_pxy())
|
||||
try:
|
||||
return r.status_code, r.json()
|
||||
except Exception:
|
||||
return r.status_code, {}
|
||||
|
||||
|
||||
def txt(pg, n=260):
|
||||
try:
|
||||
return re.sub(r"\s+", " ", pg.inner_text("body"))[:n]
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def click_btn(pg, rx, exact_first=True):
|
||||
js = """(() => {const bs=[...document.querySelectorAll('button')];
|
||||
let x=bs.find(e=>new RegExp(%s,'i').test(e.innerText||''));
|
||||
if(!x) return null; const r=x.getBoundingClientRect();
|
||||
return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2,t:(x.innerText||'').trim()})})()""" % json.dumps(rx)
|
||||
b = pg.evaluate(js)
|
||||
if not b:
|
||||
return False
|
||||
c = json.loads(b)
|
||||
try:
|
||||
pg.mouse.move(c["x"], c["y"], steps=8); time.sleep(0.2)
|
||||
pg.mouse.click(c["x"], c["y"])
|
||||
except Exception:
|
||||
pg.evaluate("""(() => {const bs=[...document.querySelectorAll('button')];
|
||||
const x=bs.find(e=>new RegExp(%s,'i').test(e.innerText||'')); if(x)x.click();})()""" % json.dumps(rx))
|
||||
return True
|
||||
|
||||
|
||||
def go(pg, url, **kw):
|
||||
"""goto with retries - the mobile egress drops TLS now and then."""
|
||||
kw.setdefault("timeout", 90000)
|
||||
kw.setdefault("wait_until", "domcontentloaded")
|
||||
last = None
|
||||
for i in range(4):
|
||||
try:
|
||||
return pg.goto(url, **kw)
|
||||
except Exception as e:
|
||||
last = e
|
||||
log(" goto retry %d: %s" % (i + 1, str(e)[:70]))
|
||||
time.sleep(5)
|
||||
if pg.is_closed():
|
||||
raise
|
||||
raise last
|
||||
|
||||
|
||||
def find_code_input(pg):
|
||||
return pg.evaluate("""(() => {const els=[...document.querySelectorAll('input')].filter(e=>e.offsetWidth||e.offsetHeight);
|
||||
let c=els.find(e=>/code|otp|verif/i.test((e.id||'')+(e.name||'')+(e.placeholder||'')+(e.getAttribute('aria-label')||'')));
|
||||
if(!c && els.length===1 && els[0].maxLength>3 && els[0].maxLength<=8) c=els[0];
|
||||
if(!c) return null; c.focus(); return c.id||'x'})()""")
|
||||
|
||||
|
||||
def clear_session(pg):
|
||||
# keep Google/reCAPTCHA cookies (they carry trust score), drop only app session
|
||||
try:
|
||||
for c in pg.context.cookies():
|
||||
if str(c.get("name", "")).startswith("BrandDev"):
|
||||
pg.context.clear_cookies(name=c["name"])
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pg.evaluate("""async ()=>{try{localStorage.clear();sessionStorage.clear()}catch(e){}
|
||||
try{const dbs=await indexedDB.databases();for(const d of dbs){if(/firebase/i.test(d.name||'')){try{indexedDB.deleteDatabase(d.name)}catch(e){}}}}catch(e){}}""")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def get_verify_link(alias, timeout=200, not_before=0):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
try:
|
||||
m = imaplib.IMAP4_SSL("imap.gmail.com")
|
||||
m.login(G["gm"], G["gp"].strip())
|
||||
m.select("INBOX")
|
||||
typ, data = m.search(None, "ALL")
|
||||
for i in reversed(data[0].split()[-15:]):
|
||||
typ, d = m.fetch(i, "(RFC822)")
|
||||
msg = email.message_from_bytes(d[0][1])
|
||||
if alias.lower() not in msg.get("To", "").lower():
|
||||
continue
|
||||
subj = str(email.header.make_header(email.header.decode_header(msg.get("Subject", ""))))
|
||||
if "Verify your email" not in subj:
|
||||
continue
|
||||
body = ""
|
||||
for part in msg.walk():
|
||||
if part.get_content_type() in ("text/plain", "text/html"):
|
||||
try:
|
||||
body += part.get_payload(decode=True).decode(part.get_content_charset() or "utf-8", "replace")
|
||||
except Exception:
|
||||
pass
|
||||
ls = re.findall(r"https://www\.context\.dev/verify-email\?[^\s\"'<>]+", body)
|
||||
if ls:
|
||||
m.logout()
|
||||
return ls[0].replace("&", "&")
|
||||
m.logout()
|
||||
except Exception as e:
|
||||
log(" imap:", str(e)[:70])
|
||||
time.sleep(10)
|
||||
return ""
|
||||
|
||||
|
||||
def api_credits(key):
|
||||
try:
|
||||
r = requests.get("https://api.context.dev/v1/org/logs",
|
||||
headers={"Authorization": "Bearer " + key}, timeout=60)
|
||||
return r.json().get("key_metadata", {}).get("credits_remaining")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def redeem_trpc(pg, promo, org_hint=None):
|
||||
"""Redeem via tRPC (needs organization_id + code)."""
|
||||
js = """async ([code, org]) => {
|
||||
if (!org) {
|
||||
try {
|
||||
const r0 = await fetch('/api/trpc/organization.get?batch=1&input=' + encodeURIComponent(JSON.stringify({"0":{"json":null}})));
|
||||
const t0 = await r0.text();
|
||||
const m = t0.match(/"id"\\s*:\\s*"([0-9a-f-]{36})"/);
|
||||
if (m) org = m[1];
|
||||
} catch(e) {}
|
||||
}
|
||||
const body = {"0":{"json":{"code":code,"organization_id":org}}};
|
||||
const r = await fetch('/api/trpc/organization.redeemCreditPackage?batch=1', {
|
||||
method:'POST', headers:{'content-type':'application/json'}, body: JSON.stringify(body)});
|
||||
const t = await r.text();
|
||||
return JSON.stringify({org:org, status:r.status, body:t.slice(0,400)});
|
||||
}"""
|
||||
try:
|
||||
out = pg.evaluate(js, [promo, org_hint])
|
||||
log(" redeem api:", str(out)[:280])
|
||||
if '"credits_added"' in str(out):
|
||||
return True
|
||||
except Exception as e:
|
||||
log(" redeem err:", str(e)[:100])
|
||||
return False
|
||||
|
||||
|
||||
def run_one(pg, mail, tag):
|
||||
code, ident = identity(mail, tag)
|
||||
log("[%s] identity %s" % (tag, code))
|
||||
if code != 200 or "claim" not in ident:
|
||||
log(" fail:", json.dumps(ident)[:200])
|
||||
return None
|
||||
vuri, ucode, ct = ident["claim"]["verification_uri"], ident["claim"]["user_code"], ident["claim_token"]
|
||||
pw = "Kq7" + "".join(random.choice(string.ascii_letters + string.digits) for _ in range(9)) + "!2"
|
||||
json.dump({"email": mail, "tag": tag, "pw": pw, "claim_token": ct, "vuri": vuri, "user_code": ucode,
|
||||
"offer": ident.get("offer"), "created": time.time()},
|
||||
open(os.path.join(BASE, "acct_%s.json" % tag), "w"), indent=1)
|
||||
log(" VURI", vuri)
|
||||
log(" CODE", ucode)
|
||||
|
||||
go(pg, "https://www.context.dev/claim", wait_until="domcontentloaded", timeout=90000)
|
||||
time.sleep(3)
|
||||
clear_session(pg)
|
||||
go(pg, vuri, wait_until="domcontentloaded", timeout=90000)
|
||||
time.sleep(7)
|
||||
t = txt(pg, 200)
|
||||
log(" page:", t[:100])
|
||||
if "We use cookies" in t or "cookie" in t[:90].lower():
|
||||
for rx in (r"^accept", r"^reject", r"^continue", r"^got it", r"^allow", r"^ok"):
|
||||
if click_btn(pg, rx):
|
||||
log(" consent:", rx)
|
||||
break
|
||||
time.sleep(3)
|
||||
t = txt(pg, 220)
|
||||
log(" page2:", t[:90])
|
||||
|
||||
if "Full name" in t or "Create account" in t:
|
||||
need = pg.evaluate("""(() => {const e=document.querySelector('input[name=username]')||document.querySelector('input[type=email]');
|
||||
if(!e) return 'none'; if(e.value && e.value.trim()) return 'ok'; e.readOnly=false; e.focus(); return 'need'})()""")
|
||||
if need == "need":
|
||||
pg.keyboard.type(mail, delay=45); time.sleep(0.7)
|
||||
pg.evaluate("""(() => {const e=document.querySelector('input[name=username]')||document.querySelector('input[type=email]');
|
||||
if(e && e.value !== %s){const s=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; s.call(e,%s); e.dispatchEvent(new Event('input',{bubbles:true}))}})()""" % (json.dumps(mail), json.dumps(mail)))
|
||||
log(" email field:", need)
|
||||
pg.focus("#name"); pg.keyboard.type(random.choice(NAMES), delay=55)
|
||||
pg.focus("#password"); pg.keyboard.type(pw, delay=55)
|
||||
pg.evaluate("(()=>{const c=document.querySelector('input[type=checkbox]'); if(!c.checked)c.click()})()")
|
||||
time.sleep(4)
|
||||
if not click_btn(pg, r"^create account"):
|
||||
log(" no signup button")
|
||||
return None
|
||||
for _ in range(35):
|
||||
time.sleep(4)
|
||||
t = txt(pg, 220)
|
||||
if "Confirm agent setup" in t or "Setup code" in t:
|
||||
break
|
||||
if "couldn't verify" in t or "Security check failed" in t:
|
||||
log(" recaptcha rejected")
|
||||
return None
|
||||
if "Confirm agent setup" not in t and "Setup code" not in t:
|
||||
log(" no code screen:", t[:130])
|
||||
return None
|
||||
elif "Confirm agent setup" not in t:
|
||||
log(" unexpected page")
|
||||
return None
|
||||
|
||||
if find_code_input(pg):
|
||||
pg.keyboard.type(ucode, delay=90); time.sleep(1)
|
||||
click_btn(pg, r"confirm setup|^confirm$|continue")
|
||||
time.sleep(7)
|
||||
log(" after code:", txt(pg, 130)[:110])
|
||||
|
||||
# verify email
|
||||
if "Check your inbox" in txt(pg, 260) or "verification link" in txt(pg, 260):
|
||||
link = get_verify_link(mail)
|
||||
if not link:
|
||||
log(" NO link")
|
||||
return None
|
||||
go(pg, link, wait_until="domcontentloaded", timeout=90000); time.sleep(5)
|
||||
click_btn(pg, r"verify email address|verify email")
|
||||
time.sleep(9)
|
||||
go(pg, vuri, wait_until="domcontentloaded", timeout=90000); time.sleep(5)
|
||||
t = txt(pg, 220)
|
||||
if "I've verified my email" in t:
|
||||
click_btn(pg, r"verified my email"); time.sleep(8)
|
||||
elif find_code_input(pg):
|
||||
pg.keyboard.type(ucode, delay=90); time.sleep(1)
|
||||
click_btn(pg, r"confirm setup|^confirm$|continue"); time.sleep(7)
|
||||
log(" post-verify:", txt(pg, 140)[:110])
|
||||
|
||||
# redeem
|
||||
org = None
|
||||
m = re.search(r"/o/([0-9a-f-]{36})", pg.url)
|
||||
if m:
|
||||
org = m.group(1)
|
||||
go(pg, "https://www.context.dev/dashboard/redeem-credits", wait_until="domcontentloaded", timeout=60000)
|
||||
time.sleep(6)
|
||||
if "Check your inbox" in txt(pg, 300):
|
||||
log(" redeem blocked: email not verified")
|
||||
else:
|
||||
redeem_trpc(pg, PROMO, org)
|
||||
time.sleep(3)
|
||||
|
||||
r = requests.post("https://www.context.dev/oauth2/token",
|
||||
data={"grant_type": "urn:workos:agent-auth:grant-type:claim", "claim_token": ct}, timeout=60, proxies=PXY)
|
||||
d = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
|
||||
if "access_token" not in d:
|
||||
log(" TOKEN FAIL", r.status_code, json.dumps(d)[:150])
|
||||
return None
|
||||
key = d["access_token"]
|
||||
cr = api_credits(key)
|
||||
entry = {"email": mail, "tag": tag, "key": key, "ts": time.time(),
|
||||
"gift": d.get("signup_gift_credits"), "credits": cr}
|
||||
with open(os.path.join(BASE, os.environ.get("CTX_BANK", "bank.jsonl")), "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
log(" KEY OK len %d gift=%s credits=%s" % (len(key), d.get("signup_gift_credits"), cr))
|
||||
return entry
|
||||
|
||||
|
||||
def main():
|
||||
ok = 0
|
||||
for idx in range(START, START + COUNT):
|
||||
mail, tag = "baradok609+ctx%d@gmail.com" % idx, "ctx%d" % idx
|
||||
log("\n=== %s ===" % mail)
|
||||
if not ensure_chrome():
|
||||
log(" chrome down"); continue
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
br = p.chromium.connect_over_cdp(CDP)
|
||||
ctx = br.contexts[0]
|
||||
pg = ctx.new_page()
|
||||
e = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
if pg.is_closed():
|
||||
pg = ctx.new_page()
|
||||
e = run_one(pg, mail, tag)
|
||||
except Exception as ex:
|
||||
log(" exc:", str(ex)[:120])
|
||||
e = None
|
||||
try:
|
||||
pg = ctx.new_page()
|
||||
except Exception:
|
||||
pass
|
||||
if e:
|
||||
break
|
||||
log(" retry %d/3 in 25s" % (attempt + 1))
|
||||
time.sleep(25)
|
||||
log("RESULT", "OK" if e else "FAIL")
|
||||
if e:
|
||||
ok += 1
|
||||
try:
|
||||
pg.close()
|
||||
except Exception:
|
||||
pass
|
||||
br.close()
|
||||
except Exception as ex:
|
||||
print("EXC", str(ex)[:200], flush=True)
|
||||
time.sleep(int(os.environ.get("CTX_PAUSE", "6")))
|
||||
log("\nTOTAL OK %d / %d" % (ok, COUNT))
|
||||
|
||||
|
||||
main()
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
"""ctx_wave.py <start_idx> <total> — run the farm in batches, rotating the ZTE mobile IP between batches.
|
||||
|
||||
Requires env for ctx_farm2: CTX_CDP, CTX_CDP_PORT, CTX_CHROME_PROF, CTX_CHROME_PROXY, CTX_PROXY, CTX_ID_PROXIES, CTX_BANK.
|
||||
"""
|
||||
import os, subprocess, sys, time
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
os.environ["PYTHONIOENCODING"] = "utf-8"
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
PY = sys.executable
|
||||
START, TOTAL = int(sys.argv[1]), int(sys.argv[2])
|
||||
BATCH = int(os.environ.get("CTX_BATCH", "4"))
|
||||
ROTATE = os.environ.get("CTX_ROTATE", "1") == "1"
|
||||
idx = START
|
||||
done = 0
|
||||
while idx < START + TOTAL:
|
||||
n = min(BATCH, START + TOTAL - idx)
|
||||
print("\n######## WAVE %d..%d ########" % (idx, idx + n - 1), flush=True)
|
||||
env = dict(os.environ)
|
||||
try:
|
||||
subprocess.run([PY, os.path.join(BASE, "ctx_farm2.py"), str(idx), str(n)],
|
||||
cwd=BASE, env=env, timeout=3600)
|
||||
except Exception as e:
|
||||
print("wave err", str(e)[:150], flush=True)
|
||||
idx += n
|
||||
done += n
|
||||
if ROTATE and idx < START + TOTAL:
|
||||
try:
|
||||
sys.path.insert(0, r"regfarm")
|
||||
import newapi_lib as L
|
||||
print("zte_rotate:", L.zte_rotate(max_wait=150), flush=True)
|
||||
except Exception as e:
|
||||
print("rotate err:", type(e).__name__, str(e)[:120], flush=True)
|
||||
time.sleep(20)
|
||||
print("\nWAVE DONE %d accounts requested" % done, flush=True)
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
# почта: файл со строками email:password
|
||||
CTX_MAIL_POOL=./mail_pool.txt
|
||||
# SSH-хост, с которого читается IMAP (локальный IP провайдер рвёт)
|
||||
CTX_VPS=root@203.0.113.10
|
||||
CTX_IMAP_HOST=secureimap.t-online.de
|
||||
# residential-прокси для браузера; пусто = напрямую
|
||||
CTX_CHROME_PROXY=
|
||||
# прокси для /agent/identity (капчи на шаге нет)
|
||||
CTX_ID_PROXY=http://127.0.0.1:8899
|
||||
CTX_CDP_PORT=9311
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import json, os, re, subprocess, sys, time
|
||||
import requests
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
CTOK = sys.argv[1]
|
||||
UCODE = sys.argv[2]
|
||||
MAIL = sys.argv[3] if len(sys.argv) > 3 else ""
|
||||
PORT = os.environ.get("CTX_CDP_PORT", "9351")
|
||||
CDP = "http://127.0.0.1:%s" % PORT
|
||||
PROF = os.environ.get("CTX_CHROME_PROF", BASE + r"\chrome_fin1")
|
||||
PROXY = os.environ.get("CTX_CHROME_PROXY", "")
|
||||
IDPXY = {"http": os.environ.get("CTX_ID_PROXY", "http://127.0.0.1:8899"), "https": os.environ.get("CTX_ID_PROXY", "http://127.0.0.1:8899")}
|
||||
VURI = "https://www.context.dev/claim?claim_attempt_token=" + CTOK
|
||||
|
||||
def log(*a, **kw):
|
||||
kw.setdefault("flush", True); print(*a, **kw)
|
||||
|
||||
def txt(pg, n=300):
|
||||
try: return pg.inner_text("body")[:n]
|
||||
except Exception: return ""
|
||||
|
||||
def click(pg, rx):
|
||||
for kind in ("button", "link"):
|
||||
try:
|
||||
el = pg.get_by_role(kind, name=re.compile(rx, re.I)).first
|
||||
if el.count() and el.is_visible(): el.click(); return True
|
||||
except Exception: pass
|
||||
return False
|
||||
|
||||
if MAIL:
|
||||
try:
|
||||
used = set(json.load(open(os.path.join(BASE, "t_used.json"))))
|
||||
except Exception:
|
||||
used = set()
|
||||
used.add(MAIL); json.dump(sorted(used), open(os.path.join(BASE, "t_used.json"), "w"))
|
||||
|
||||
env2 = dict(os.environ); env2.update({"CTX_CDP_PORT": PORT, "CTX_CHROME_PROF": PROF, "CTX_CHROME_PROXY": PROXY})
|
||||
subprocess.run([sys.executable, os.path.join(BASE, "chrome_up.py")], check=False, env=env2)
|
||||
time.sleep(3)
|
||||
|
||||
with sync_playwright() as p:
|
||||
b = p.chromium.connect_over_cdp(CDP, timeout=90000)
|
||||
ctx = b.contexts[0]
|
||||
pg = ctx.new_page(); pg.set_default_timeout(50000)
|
||||
pg.goto(VURI, timeout=90000, wait_until="domcontentloaded")
|
||||
time.sleep(8)
|
||||
t = txt(pg, 300); log("page:", t[:160].replace("\n", " "))
|
||||
if "verified my email" in t:
|
||||
click(pg, "verified my email"); time.sleep(9)
|
||||
t = txt(pg, 250); log("after ack:", t[:140].replace("\n", " "))
|
||||
ins = pg.locator("input[type=text], input[inputmode=numeric], input[autocomplete=one-time-code]")
|
||||
if ins.count() >= 6:
|
||||
for i in range(6): ins.nth(i).fill(UCODE[i])
|
||||
time.sleep(1)
|
||||
click(pg, "confirm setup|^confirm$|authorize|continue|finish"); time.sleep(10)
|
||||
log("after code:", txt(pg, 220).replace("\n", " "), "|", pg.url[:80])
|
||||
elif ins.count():
|
||||
ins.first.fill(UCODE); time.sleep(1)
|
||||
click(pg, "confirm setup|^confirm$|authorize|continue|finish"); time.sleep(10)
|
||||
log("after code1:", txt(pg, 220).replace("\n", " "), "|", pg.url[:80])
|
||||
pg.screenshot(path=os.path.join(BASE, "fin_one.png"))
|
||||
pg.close()
|
||||
|
||||
j = {}
|
||||
for att in range(5):
|
||||
px = IDPXY if att % 2 == 0 else {"http": os.environ.get("CTX_ID_PROXY2", "http://127.0.0.1:8899"), "https": os.environ.get("CTX_ID_PROXY2", "http://127.0.0.1:8899")}
|
||||
try:
|
||||
r = requests.post("https://www.context.dev/oauth2/token",
|
||||
data={"grant_type": "urn:workos:agent-auth:grant-type:claim", "claim_token": CTOK},
|
||||
timeout=60, proxies=px)
|
||||
log("token:", r.status_code, r.text[:160])
|
||||
if r.text.strip().startswith("{"): j = r.json()
|
||||
if "access_token" in j or j.get("error") not in (None,): break
|
||||
except Exception as e:
|
||||
log("token err", type(e).__name__)
|
||||
time.sleep(6)
|
||||
|
||||
if "access_token" in j:
|
||||
k = j["access_token"]
|
||||
log("KEY len", len(k), "gift", j.get("signup_gift_credits"))
|
||||
u = requests.get("https://api.context.dev/v1/org/logs", headers={"Authorization": "Bearer " + k},
|
||||
timeout=30, proxies=IDPXY)
|
||||
log("logs:", u.status_code, u.text[:300])
|
||||
with open(os.path.join(BASE, "bank.jsonl"), "a") as f:
|
||||
f.write(json.dumps({"email": MAIL, "tag": "t-online", "key": k, "ts": time.time(),
|
||||
"claim_token": CTOK, "gift": j.get("signup_gift_credits"), "dead": False}) + "\n")
|
||||
log("SAVED")
|
||||
else:
|
||||
log("NO KEY")
|
||||
@@ -0,0 +1,54 @@
|
||||
import json, os, random, re, sys, time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import requests
|
||||
|
||||
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36"}
|
||||
SOURCES = [
|
||||
"https://api.proxyscrape.com/v4/free-proxy-list/get?request=display_proxies&protocol=http&proxy_format=ipport&format=text&timeout=5000",
|
||||
"https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt",
|
||||
"https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt",
|
||||
"https://raw.githubusercontent.com/proxifly/free-proxy-list/main/proxies/protocols/http/data.txt",
|
||||
"https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list-raw.txt",
|
||||
]
|
||||
TARGET = "https://www.context.dev/"
|
||||
OUT = "proxies_live.json"
|
||||
|
||||
def grab():
|
||||
out = set()
|
||||
for u in SOURCES:
|
||||
try:
|
||||
r = requests.get(u, timeout=30, headers=UA)
|
||||
for line in r.text.splitlines():
|
||||
line = line.strip()
|
||||
m = re.search(r"(\d{1,3}(?:\.\d{1,3}){3}):(\d{2,5})", line)
|
||||
if m:
|
||||
out.add("%s:%s" % (m.group(1), m.group(2)))
|
||||
print(u.split("/")[2], len(out), flush=True)
|
||||
except Exception as e:
|
||||
print("src err", u.split("/")[2], type(e).__name__, flush=True)
|
||||
return list(out)
|
||||
|
||||
def test(px):
|
||||
p = {"http": "http://" + px, "https": "http://" + px}
|
||||
try:
|
||||
r = requests.get(TARGET, proxies=p, timeout=12, headers=UA, allow_redirects=False)
|
||||
return px, r.status_code
|
||||
except Exception:
|
||||
return px, 0
|
||||
|
||||
pool = grab()
|
||||
print("total proxies", len(pool), flush=True)
|
||||
random.shuffle(pool)
|
||||
pool = pool[:1200]
|
||||
good = []
|
||||
with ThreadPoolExecutor(max_workers=100) as ex:
|
||||
futs = [ex.submit(test, px) for px in pool]
|
||||
for i, f in enumerate(as_completed(futs), 1):
|
||||
px, st = f.result()
|
||||
if st == 200:
|
||||
good.append(px)
|
||||
print("OK", px, flush=True)
|
||||
if i % 200 == 0:
|
||||
print("checked", i, "good", len(good), flush=True)
|
||||
json.dump(good, open(OUT, "w"), indent=1)
|
||||
print("GOOD", len(good), flush=True)
|
||||
@@ -0,0 +1,78 @@
|
||||
import json, os, re, subprocess, sys, time
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
MAIL = sys.argv[1]
|
||||
PW = sys.argv[2]
|
||||
PORT = os.environ.get("CTX_CDP_PORT", "9353")
|
||||
CDP = "http://127.0.0.1:%s" % PORT
|
||||
PROF = os.environ.get("CTX_CHROME_PROF", BASE + r"\chrome_ld1")
|
||||
PROXY = os.environ.get("CTX_CHROME_PROXY", "")
|
||||
|
||||
def log(*a, **kw):
|
||||
kw.setdefault("flush", True); print(*a, **kw)
|
||||
|
||||
def txt(pg, n=350):
|
||||
try: return pg.inner_text("body")[:n]
|
||||
except Exception: return ""
|
||||
|
||||
def click(pg, rx):
|
||||
for kind in ("button", "link"):
|
||||
try:
|
||||
el = pg.get_by_role(kind, name=re.compile(rx, re.I)).first
|
||||
if el.count() and el.is_visible(): el.click(); return True
|
||||
except Exception: pass
|
||||
return False
|
||||
|
||||
env2 = dict(os.environ); env2.update({"CTX_CDP_PORT": PORT, "CTX_CHROME_PROF": PROF, "CTX_CHROME_PROXY": PROXY})
|
||||
subprocess.run([sys.executable, os.path.join(BASE, "chrome_up.py")], check=False, env=env2)
|
||||
time.sleep(3)
|
||||
|
||||
with sync_playwright() as p:
|
||||
b = p.chromium.connect_over_cdp(CDP, timeout=90000)
|
||||
ctx = b.contexts[0]
|
||||
pg = ctx.new_page(); pg.set_default_timeout(50000)
|
||||
pg.goto("https://www.context.dev/login", timeout=90000, wait_until="domcontentloaded")
|
||||
time.sleep(8)
|
||||
log("login page:", txt(pg, 150).replace("\n", " "))
|
||||
em = pg.locator("input[type=email]").first
|
||||
em.click(); em.type(MAIL, delay=30)
|
||||
time.sleep(1)
|
||||
if not click(pg, "^continue$"):
|
||||
pg.keyboard.press("Enter")
|
||||
time.sleep(6)
|
||||
if pg.locator("input[type=password]").count() == 0:
|
||||
try:
|
||||
pg.locator("button[type=submit]").first.click(force=True)
|
||||
except Exception: pass
|
||||
time.sleep(5)
|
||||
log("after email:", txt(pg, 200).replace("\n", " "))
|
||||
pwf = pg.locator("input[type=password]").first
|
||||
for _ in range(15):
|
||||
if pwf.count(): break
|
||||
time.sleep(2)
|
||||
log("pw field:", pwf.count())
|
||||
if pwf.count() == 0:
|
||||
log("STEP1 FAIL")
|
||||
pg.close(); sys.exit(3)
|
||||
if pwf.count():
|
||||
pwf.click(); pwf.type(PW, delay=25)
|
||||
time.sleep(1)
|
||||
click(pg, "^sign in$|^continue$|^submit$|log in")
|
||||
for _ in range(14):
|
||||
time.sleep(4)
|
||||
if "/login" not in pg.url:
|
||||
break
|
||||
time.sleep(3)
|
||||
log("after pw:", txt(pg, 250).replace("\n", " "), "|", pg.url[:90])
|
||||
time.sleep(5)
|
||||
log("final:", txt(pg, 300).replace("\n", " "), "|", pg.url[:90])
|
||||
keys = pg.evaluate("""() => {
|
||||
const m = document.body.innerText.match(/ctxt_secret_[A-Za-z0-9]+/g);
|
||||
return m || null;
|
||||
}""")
|
||||
log("keys on page:", keys)
|
||||
pg.screenshot(path=os.path.join(BASE, "ld_final.png"))
|
||||
json.dump({"url": pg.url, "text": txt(pg, 1500), "keys": keys},
|
||||
open(os.path.join(BASE, "ld_state.json"), "w"), ensure_ascii=False, indent=1)
|
||||
pg.close()
|
||||
@@ -0,0 +1,41 @@
|
||||
import json, os, subprocess, sys, time
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
PY = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe"
|
||||
MAIL, PW = sys.argv[1], sys.argv[2]
|
||||
N = int(sys.argv[3]) if len(sys.argv) > 3 else 10
|
||||
proxies = json.load(open(os.path.join(BASE, "proxies_live.json")))
|
||||
env0 = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"}
|
||||
env0["PYTHONIOENCODING"] = "utf-8"
|
||||
|
||||
for i, px in enumerate(proxies[:N]):
|
||||
port = str(9361 + i * 2)
|
||||
logf = os.path.join(BASE, "ld_try_%d.log" % i)
|
||||
env = dict(env0)
|
||||
env.update({"CTX_CHROME_PROXY": "http://" + px, "CTX_CDP_PORT": port,
|
||||
"CTX_CHROME_PROF": BASE + "\\chrome_ld_%d" % i})
|
||||
print("=== [%d] %s :%s" % (i, px, port), flush=True)
|
||||
try:
|
||||
with open(logf, "w", encoding="utf-8") as f:
|
||||
subprocess.run([PY, os.path.join(BASE, "login_dash3.py"), MAIL, PW], cwd=BASE,
|
||||
env=env, stdout=f, stderr=subprocess.STDOUT, timeout=420, check=False)
|
||||
except subprocess.TimeoutExpired:
|
||||
print(" timeout", flush=True)
|
||||
t = open(logf, encoding="utf-8", errors="replace").read()
|
||||
marks = [l for l in t.splitlines() if any(k in l for k in
|
||||
("pw field", "after pw", "final:", "keys on page", "flagged", "review", "Error"))]
|
||||
print("\n".join(" " + m[:160] for m in marks[-4:]), flush=True)
|
||||
try:
|
||||
st = json.load(open(os.path.join(BASE, "ld_state.json")))
|
||||
except Exception:
|
||||
st = {}
|
||||
url = st.get("url", "")
|
||||
if st.get("keys") or "/o/" in url or "dashboard" in url:
|
||||
print("SUCCESS", px, url[:80], flush=True)
|
||||
json.dump({"proxy": px, "url": url, "keys": st.get("keys")},
|
||||
open(os.path.join(BASE, "win_login.json"), "w"), indent=1)
|
||||
break
|
||||
if "review" in st.get("text", ""):
|
||||
print(" -> account under review", flush=True)
|
||||
break
|
||||
time.sleep(3)
|
||||
@@ -0,0 +1,3 @@
|
||||
# формат: email:password, по одной паре на строку
|
||||
user1@t-online.de:examplepass1
|
||||
user2@t-online.de:examplepass2
|
||||
@@ -0,0 +1,223 @@
|
||||
import json, os, random, re, subprocess, sys, time
|
||||
import requests
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
POOL = os.environ.get("CTX_MAIL_POOL", os.path.join(BASE, "mail_pool.txt"))
|
||||
USED = os.path.join(BASE, "t_used.json")
|
||||
PORT = os.environ.get("CTX_CDP_PORT", "9311")
|
||||
CDP = "http://127.0.0.1:%s" % PORT
|
||||
PROF = os.environ.get("CTX_CHROME_PROF", BASE + r"\chrome_z1")
|
||||
PROXY = os.environ.get("CTX_CHROME_PROXY", "")
|
||||
IDPXY = {"http": os.environ.get("CTX_ID_PROXY", "http://127.0.0.1:8899"), "https": os.environ.get("CTX_ID_PROXY", "http://127.0.0.1:8899")}
|
||||
VPS = os.environ.get("CTX_VPS", "")
|
||||
IMAP_HOST = os.environ.get("CTX_IMAP_HOST", "secureimap.t-online.de")
|
||||
|
||||
VPS_SCRIPT = r'''
|
||||
import imaplib, email, re, sys
|
||||
addr, pw = sys.argv[1], sys.argv[2]
|
||||
host = sys.argv[3] if len(sys.argv) > 3 else "secureimap.t-online.de"
|
||||
m = imaplib.IMAP4_SSL(host, 993)
|
||||
m.login(addr, pw)
|
||||
m.select("INBOX")
|
||||
typ, data = m.search(None, "FROM", "context.dev")
|
||||
ids = data[0].split()
|
||||
for i in reversed(ids[-3:]):
|
||||
typ, d = m.fetch(i, "(RFC822)")
|
||||
msg = email.message_from_bytes(d[0][1])
|
||||
body = ""
|
||||
if msg.is_multipart():
|
||||
for pt in msg.walk():
|
||||
if pt.get_content_type() in ("text/html", "text/plain"):
|
||||
try: body += pt.get_payload(decode=True).decode("utf-8", "replace")
|
||||
except Exception: pass
|
||||
else:
|
||||
body = msg.get_payload(decode=True).decode("utf-8", "replace")
|
||||
ls = re.findall(r"https://www\.context\.dev/verify-email[^\s\"'<>]+", body)
|
||||
if ls:
|
||||
print(ls[0].replace("&", "&")); sys.exit(0)
|
||||
print("NONE")
|
||||
'''
|
||||
|
||||
def log(*a, **kw):
|
||||
kw.setdefault("flush", True)
|
||||
print(*a, **kw)
|
||||
|
||||
def txt(pg, n=300):
|
||||
try: return pg.inner_text("body")[:n]
|
||||
except Exception: return ""
|
||||
|
||||
def click(pg, rx):
|
||||
for kind in ("button", "link"):
|
||||
try:
|
||||
el = pg.get_by_role(kind, name=re.compile(rx, re.I)).first
|
||||
if el.count() and el.is_visible():
|
||||
el.click(); return True
|
||||
except Exception: pass
|
||||
return False
|
||||
|
||||
def consent(pg):
|
||||
if "cookie" in txt(pg, 200).lower():
|
||||
click(pg, "^accept"); time.sleep(2)
|
||||
|
||||
def vps_link(addr, pw, timeout=200):
|
||||
t0 = time.time()
|
||||
last = ""
|
||||
while time.time() - t0 < timeout:
|
||||
try:
|
||||
r = subprocess.run(["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=15", VPS,
|
||||
"python3 - " + addr + " " + pw + " " + IMAP_HOST],
|
||||
input=VPS_SCRIPT.encode(), capture_output=True, timeout=90)
|
||||
out = r.stdout.decode("utf-8", "replace").strip()
|
||||
last = out[:80]
|
||||
if out.startswith("https://"):
|
||||
return out.splitlines()[0]
|
||||
except Exception as e:
|
||||
last = "err " + type(e).__name__
|
||||
log(" mail wait:", last)
|
||||
time.sleep(20)
|
||||
return None
|
||||
|
||||
def identity(mail):
|
||||
for att in range(3):
|
||||
for px in (IDPXY, {"http": os.environ.get("CTX_ID_PROXY2", "http://127.0.0.1:8899"), "https": os.environ.get("CTX_ID_PROXY2", "http://127.0.0.1:8899")}):
|
||||
try:
|
||||
r = requests.post("https://www.context.dev/agent/identity",
|
||||
json={"type": "service_auth", "login_hint": mail,
|
||||
"api_key_name": "hermes-z", "client_name": "Hermes"},
|
||||
timeout=45, proxies=px)
|
||||
if r.status_code == 200:
|
||||
return r.json()
|
||||
log(" identity", r.status_code, r.text[:60])
|
||||
except Exception as e:
|
||||
log(" identity err", type(e).__name__)
|
||||
time.sleep(20)
|
||||
return None
|
||||
|
||||
# pick unused mail
|
||||
used = set(json.load(open(USED))) if os.path.exists(USED) else set()
|
||||
MAIL = MPW = None
|
||||
for line in open(POOL, encoding="utf-8", errors="replace"):
|
||||
line = line.strip()
|
||||
if not line or ":" not in line or line.startswith("#"): continue
|
||||
a, p = line.split(":", 1)
|
||||
if a in used: continue
|
||||
MAIL, MPW = a, p
|
||||
break
|
||||
log("account", MAIL[:4] + "***@" + MAIL.split("@")[-1], "| proxy", PROXY)
|
||||
|
||||
ident = identity(MAIL)
|
||||
if not ident:
|
||||
log("NO IDENTITY"); sys.exit(1)
|
||||
vuri, ucode, ctok = ident["claim"]["verification_uri"], ident["claim"]["user_code"], ident["claim_token"]
|
||||
PW = "Zx9" + "".join(random.choice("abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789") for _ in range(11)) + "!7"
|
||||
rec = {"email": MAIL, "pw": PW, "mailpw": MPW, "claim_token": ctok, "vuri": vuri, "user_code": ucode}
|
||||
af = os.path.join(BASE, "z_acct_%s.json" % re.sub(r"\W", "_", MAIL))
|
||||
json.dump(rec, open(af, "w"), indent=1)
|
||||
log("identity ok | code", ucode)
|
||||
|
||||
env2 = dict(os.environ); env2.update({"CTX_CDP_PORT": PORT, "CTX_CHROME_PROF": PROF, "CTX_CHROME_PROXY": PROXY})
|
||||
subprocess.run([sys.executable, os.path.join(BASE, "chrome_up.py")], check=False, env=env2)
|
||||
time.sleep(3)
|
||||
|
||||
ok = False
|
||||
with sync_playwright() as p:
|
||||
b = p.chromium.connect_over_cdp(CDP, timeout=90000)
|
||||
ctx = b.contexts[0]
|
||||
pg = ctx.new_page(); pg.set_default_timeout(50000)
|
||||
pg.goto(vuri, timeout=90000, wait_until="domcontentloaded")
|
||||
time.sleep(8); consent(pg)
|
||||
t = txt(pg, 240)
|
||||
log("page:", t[:100].replace("\n", " "))
|
||||
if "extra credits" in t or "Finish setup" in t:
|
||||
log(" gift banner present")
|
||||
has_form = pg.locator("#password").count() > 0
|
||||
if has_form:
|
||||
em = pg.locator("input[type=email]").first
|
||||
try: em.evaluate("e=>{e.readOnly=false}")
|
||||
except Exception: pass
|
||||
try: em.fill(MAIL)
|
||||
except Exception: pg.keyboard.type(MAIL, delay=35)
|
||||
nm = pg.locator("#name")
|
||||
if nm.count(): nm.first.fill(random.choice(["Nikita Refor", "Alex Grobman", "Max Koval"]))
|
||||
pg.locator("#password").first.fill(PW)
|
||||
try: pg.locator("input[type=checkbox]").first.click()
|
||||
except Exception: pass
|
||||
time.sleep(2)
|
||||
try: pg.locator("button[type=submit]").first.click(force=True)
|
||||
except Exception: pass
|
||||
for _ in range(25):
|
||||
time.sleep(4)
|
||||
t = txt(pg, 260)
|
||||
if "Confirm agent setup" in t or "Check your inbox" in t: break
|
||||
if "blocked" in t or "Security check" in t or "flagged" in t: break
|
||||
log("submit:", t[:110].replace("\n", " "))
|
||||
if "Confirm agent setup" in txt(pg, 300):
|
||||
ins = pg.locator("input[type=text], input[inputmode=numeric], input[autocomplete=one-time-code]")
|
||||
if ins.count() >= 6:
|
||||
for i in range(6): ins.nth(i).fill(ucode[i])
|
||||
elif ins.count():
|
||||
ins.first.fill(ucode)
|
||||
time.sleep(1)
|
||||
click(pg, "confirm setup|^confirm$|authorize|continue")
|
||||
time.sleep(9)
|
||||
log("after code:", txt(pg, 200).replace("\n", " "), "|", pg.url[:70])
|
||||
if "Check your inbox" in txt(pg, 320):
|
||||
link = vps_link(MAIL, MPW)
|
||||
log("mail:", (link or "NONE")[:80])
|
||||
if link:
|
||||
pg.goto(link, timeout=90000, wait_until="domcontentloaded"); time.sleep(7)
|
||||
log("verify page:", txt(pg, 120).replace("\n", " "))
|
||||
click(pg, "verify email address|verify email"); time.sleep(10)
|
||||
log("after verify:", txt(pg, 140).replace("\n", " "))
|
||||
pg.goto(vuri, timeout=90000, wait_until="domcontentloaded"); time.sleep(8)
|
||||
t2 = txt(pg, 260); log("back:", t2[:110].replace("\n", " "))
|
||||
if "verified my email" in t2:
|
||||
click(pg, "verified my email"); time.sleep(9)
|
||||
t2 = txt(pg, 200); log("after ack:", t2[:110].replace("\n", " "))
|
||||
ins = pg.locator("input[type=text], input[inputmode=numeric], input[autocomplete=one-time-code]")
|
||||
if ins.count() >= 6:
|
||||
for i in range(6): ins.nth(i).fill(ucode[i])
|
||||
time.sleep(1)
|
||||
click(pg, "confirm setup|^confirm$|authorize|continue"); time.sleep(10)
|
||||
log("final page:", txt(pg, 200).replace("\n", " "), "|", pg.url[:80])
|
||||
if "blocked" not in txt(pg, 320):
|
||||
ok = True
|
||||
pg.screenshot(path=os.path.join(BASE, "z_final.png"))
|
||||
try:
|
||||
ks = pg.evaluate("() => (document.body.innerText.match(/ctxt_secret_[A-Za-z0-9]+/g) || null)")
|
||||
log("keys on page:", ks)
|
||||
full = pg.inner_text("body")
|
||||
open(os.path.join(BASE, "z_page_%s.txt" % re.sub(r"\W", "_", MAIL)), "w", encoding="utf-8").write(
|
||||
pg.url + "\n\n" + full)
|
||||
except Exception as e:
|
||||
log("dump err", type(e).__name__)
|
||||
pg.close()
|
||||
|
||||
used.add(MAIL); json.dump(sorted(used), open(USED, "w"))
|
||||
j = {}
|
||||
for att in range(4):
|
||||
px = IDPXY if att % 2 == 0 else {"http": os.environ.get("CTX_ID_PROXY2", "http://127.0.0.1:8899"), "https": os.environ.get("CTX_ID_PROXY2", "http://127.0.0.1:8899")}
|
||||
try:
|
||||
r = requests.post("https://www.context.dev/oauth2/token",
|
||||
data={"grant_type": "urn:workos:agent-auth:grant-type:claim", "claim_token": ctok},
|
||||
timeout=60, proxies=px)
|
||||
log("token:", r.status_code, r.text[:180])
|
||||
if r.text.strip().startswith("{"):
|
||||
j = r.json()
|
||||
if "access_token" in j or "error" in j:
|
||||
break
|
||||
except Exception as e:
|
||||
log("token err", type(e).__name__)
|
||||
time.sleep(5)
|
||||
if "access_token" in j:
|
||||
k = j["access_token"]
|
||||
log("KEY len", len(k), "gift", j.get("signup_gift_credits"))
|
||||
u = requests.get("https://api.context.dev/v1/org/logs", headers={"Authorization": "Bearer " + k},
|
||||
timeout=30, proxies=IDPXY)
|
||||
log("logs:", u.status_code, u.text[:300])
|
||||
json.dump({**rec, "key": k}, open(af, "w"), indent=1)
|
||||
with open(os.path.join(BASE, "bank.jsonl"), "a") as f:
|
||||
f.write(json.dumps({"email": MAIL, "tag": "t-online", "key": k, "ts": time.time(),
|
||||
"gift": j.get("signup_gift_credits"), "credits": None, "dead": False}) + "\n")
|
||||
log("SAVED")
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
playwright>=1.40
|
||||
requests>=2.31
|
||||
httpx>=0.27
|
||||
psutil>=5.9
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import json, os, subprocess, sys, time
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
PY = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe"
|
||||
N = int(sys.argv[1]) if len(sys.argv) > 1 else 10
|
||||
proxies = json.load(open(os.path.join(BASE, "proxies_fast.json")))[:N]
|
||||
env0 = {k: v for k, v in os.environ.items() if k != "PYTHONPATH"}
|
||||
env0["PYTHONIOENCODING"] = "utf-8"
|
||||
|
||||
for i, px in enumerate(proxies):
|
||||
port = str(9331 + i * 2)
|
||||
logf = os.path.join(BASE, "z_try_%d.log" % i)
|
||||
env = dict(env0)
|
||||
env.update({"CTX_CHROME_PROXY": "http://" + px, "CTX_CDP_PORT": port,
|
||||
"CTX_CHROME_PROF": BASE + "\\chrome_zz_%d" % i})
|
||||
print("=== [%d] %s :%s" % (i, px, port), flush=True)
|
||||
try:
|
||||
with open(logf, "w", encoding="utf-8") as f:
|
||||
subprocess.run([PY, os.path.join(BASE, "reg_t3.py")], cwd=BASE, env=env,
|
||||
stdout=f, stderr=subprocess.STDOUT, timeout=700, check=False)
|
||||
except subprocess.TimeoutExpired:
|
||||
print(" timeout", flush=True)
|
||||
t = open(logf, encoding="utf-8", errors="replace").read()
|
||||
marks = [l for l in t.splitlines() if any(k in l for k in
|
||||
("identity ok", "after verify", "back:", "flagged", "blocked", "token:", "KEY len", "SAVED", "mail:"))]
|
||||
print("\n".join(" " + m[:150] for m in marks[-6:]), flush=True)
|
||||
if "SAVED" in t:
|
||||
print("SUCCESS", px, flush=True)
|
||||
json.dump({"proxy": px}, open(os.path.join(BASE, "win3.json"), "w"))
|
||||
break
|
||||
time.sleep(4)
|
||||
Reference in New Issue
Block a user