withruntime autoreg: email+code and Google OAuth channels, key issuance, pool API wrapper
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
wr_accounts.jsonl
|
||||
wr_gfail.json
|
||||
*.log
|
||||
wr_state*.json
|
||||
wrprof*/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.gpw_env
|
||||
@@ -0,0 +1,119 @@
|
||||
# withruntime-autoreg
|
||||
|
||||
Автоматическая регистрация аккаунтов на [withruntime.com](https://withruntime.com) и получение пула API-ключей для бесплатных Firecracker-микровм.
|
||||
|
||||
Один аккаунт даёт **25 vCPU-часов + 100 GiB-часов RAM + 10 GB снапшотов + 5 GB томов** на 30 дней, карта не требуется. Ключ аккаунта — обычный `rtcloud_*`, машины создаются через REST API.
|
||||
|
||||
## Экономика
|
||||
|
||||
| Что | Сколько |
|
||||
|---|---|
|
||||
| vCPU-часы на аккаунт | 25 (`machine-cpu`, `quantity: 25`) |
|
||||
| RAM на аккаунт | 100 GiB-ч (`machine-memory`) |
|
||||
| Срок | первые 30 дней с регистрации, `freeUntil` в `GET /v1/usage` |
|
||||
| Карта | не нужна |
|
||||
| 1 аккаунт = | 100 часов машины 1 GB / 25 часов 1 vCPU |
|
||||
| 30 аккаунтов = | 750 vCPU-ч, 3000 GiB-ч RAM |
|
||||
|
||||
Платные ставки: `$0.025`/активный vCPU-час, `$0.0075`/GiB-час RAM, простой 300 с → пауза, припаркованный диск `$0.08`/GB-мес, egress 100 GiB/мес далее `$0.02`/GB. Бесплатный юнит выдаётся один раз на аккаунт; аккаунт, открытый с датацентрового или VPN-адреса, получает его только после пополнения — поэтому регистрация идёт с домашнего или мобильного IP.
|
||||
|
||||
## Что внутри
|
||||
|
||||
```
|
||||
wr_reg.py базовый CDP-драйвер: поднять/переиспользовать Chrome на порту 9223, отдать playwright context
|
||||
wr_one.py регистрация одного аккаунта по email + код из почты, затем ключ
|
||||
wr_gfarm.py пачка аккаунтов через Google OAuth (основной канал), fail-лист, продолжение с любого индекса
|
||||
wr_key2.py выдать ключ в уже залогиненном профиле + прочитать usage
|
||||
wr_net.py перехват XHR, которым дашборд создаёт ключ (поиск эндпоинта)
|
||||
wr_key.py создание ключа кликами в UI (медленный путь, запасной)
|
||||
wr_api.py работа с пулом: usage / sh / create / exec / list / rm
|
||||
zte_socks.py локальный SOCKS5, весь egress через мобильный интерфейс (для чистого IP)
|
||||
```
|
||||
|
||||
## Канал 1: email + код (`wr_one.py`)
|
||||
|
||||
```bash
|
||||
python wr_one.py 'you+rt01@gmail.com' '<imap-password>'
|
||||
```
|
||||
|
||||
Флоу: `/sign-in` → `Continue with email` → ввод адреса → сервер шлёт 6-значный код → код читается из почты по IMAP (в репозитории чтение вынесено на внешний хост: `ssh()` в `wr_one.py` вызывает скрипт-читалку) → `input#cloud-code` → сессия → ключ.
|
||||
|
||||
Гейты:
|
||||
- **Turnstile** на форме входа. Невидимый, решается только реальным браузером с чистого IP; токен-сервисы его не проходят, а при неудаче форма висит на «Sending…» и запрос на отправку кода вообще не уходит в сеть.
|
||||
- **Лимит писем на IP**: 3-5 писем за окно, дальше тишина на любые адреса, включая новые алиасы.
|
||||
|
||||
## Канал 2: Google OAuth (`wr_gfarm.py`) — рабочий
|
||||
|
||||
```bash
|
||||
# пароли пула должны быть актуальными (сброс через Workspace Admin SDK — вне репы)
|
||||
python wr_gfarm.py 0 6 # первые 6 аккаунтов пула
|
||||
python wr_gfarm.py left 6 # 6 ещё не обработанных
|
||||
```
|
||||
|
||||
Флоу: `accounts.google.com/signin/v2/identifier` → email → `Next` → пароль → при необходимости «I understand» → `withruntime.com/sign-in` → `Continue with Google` → выбор аккаунта → consent → `/account` → ключ.
|
||||
|
||||
Питфолы:
|
||||
- Часть аккаунтов ловит `Verify it's you` с требованием телефона. Это свойство самого аккаунта, а не IP: через другой egress те же адреса падают так же. Такие пишутся в `wr_gfail.json` и больше не трогаются.
|
||||
- После ~20 логинов подряд профиль получает риск-сигнал и страницы начинают отдавать таймаут `inner_text`. Лечится свежим `--user-data-dir` и сменой egress: `WR_PROF=... WR_PROXY=socks5://127.0.0.1:1081`.
|
||||
- Google-пароли воркспейса принудительно протухают — перед волной сбрасывать.
|
||||
|
||||
## Ключ аккаунта
|
||||
|
||||
Ключ создаётся **только из страницы** (запрос идёт с origin дашборда и cookie сессии):
|
||||
|
||||
```js
|
||||
await fetch('/api/account/keys', {
|
||||
method: 'POST', credentials: 'include',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({action: 'create', label: 'farm', access: 'full'})
|
||||
})
|
||||
```
|
||||
Ответ содержит `credential.plaintext` (сам ключ, префикс `rtcloud_`). Через `APIRequestContext` тот же запрос даёт `403 Request origin refused` — origin нет.
|
||||
|
||||
## Использование пула (`wr_api.py`)
|
||||
|
||||
```bash
|
||||
python wr_api.py usage # сводка остатков по всем ключам
|
||||
python wr_api.py sh "uname -a" # создать сандбокс, выполнить, удалить
|
||||
python wr_api.py create farm02 1 1024 3072 # name vcpu memMiB diskMiB
|
||||
python wr_api.py exec <sandbox-id> "cmd" # команда под root
|
||||
python wr_api.py list
|
||||
python wr_api.py rm <sandbox-id>
|
||||
```
|
||||
|
||||
API: `POST /v1/sandboxes` (`name`, `vcpu`, `memoryMiB`, `diskMiB`) → поллинг `GET /v1/sandboxes/{id}` до `running` → `POST /v1/sandboxes/{id}:exec` (`command`, `user: root`). Спецификация: `https://api.withruntime.com/v1/openapi.json`.
|
||||
|
||||
Пруф с живого сандбокса: `uid=0(root)`, `Linux 6.18.44`, `Docker 29.1.3`, `Python 3.12.3`, `exit 0`.
|
||||
|
||||
## Чистый egress (мобильный IP)
|
||||
|
||||
`zte_socks.py` поднимает SOCKS5 на `127.0.0.1:1081` и биндит исходящие на адрес мобильного интерфейса:
|
||||
|
||||
```bash
|
||||
python zte_socks.py 1081
|
||||
curl --socks5-hostname 127.0.0.1:1081 https://api.ipify.org
|
||||
# Chrome
|
||||
WR_PROXY=socks5://127.0.0.1:1081 python wr_gfarm.py left 6
|
||||
```
|
||||
|
||||
## Настройка под свою машину
|
||||
|
||||
В начале файлов заменить пути:
|
||||
|
||||
| Файл | Константы |
|
||||
|---|---|
|
||||
| `wr_reg.py` | `CHROME`, `PROFDIR`, `STATE`, `PORT` |
|
||||
| `wr_api.py` | `REG` (реестр ключей) |
|
||||
| `wr_gfarm.py` | `GPW` (пул аккаунтов: `{"email","password"}` построчно), `OUT` |
|
||||
| `wr_one.py` | `ssh()` — хост-читалка почты |
|
||||
|
||||
Переменные окружения: `WR_PROF` (каталог профиля Chrome), `WR_PROXY` (`socks5://...`).
|
||||
|
||||
Требования: Python 3.11, `playwright` (`pip install playwright`), установленный Google Chrome, `git-bash` для запуска на Windows.
|
||||
|
||||
## Правила и ограничения
|
||||
|
||||
- Регистрация только с домашнего или мобильного IP: с датацентрового бесплатные часы не выдаются.
|
||||
- Обращение к приватным адресам и `169.254.169.254` из сандбокса — мгновенный бан аккаунта. Не делаем.
|
||||
- Чужие аккаунты, платежи, продление — вне рамок. Скрипты только создают аккаунты и читают собственный usage.
|
||||
- Пул ключей хранится вне репозитория (`wr_accounts.jsonl` в `.gitignore`).
|
||||
@@ -0,0 +1 @@
|
||||
playwright>=1.44
|
||||
@@ -0,0 +1,117 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""wr_api.py — обёртка Runtime API: sandbox create/exec/delete, usage, пул ключей.
|
||||
|
||||
Примеры:
|
||||
python wr_api.py usage
|
||||
python wr_api.py sh "uname -a" # одноразовый сандбокс: создать -> exec -> удалить
|
||||
python wr_api.py create farm02 [vcpu] [memMiB] [diskMiB]
|
||||
python wr_api.py exec <id> "cmd"
|
||||
python wr_api.py list
|
||||
python wr_api.py rm <id>
|
||||
"""
|
||||
import json, sys, time, urllib.request, urllib.error
|
||||
|
||||
BASE = "https://api.withruntime.com"
|
||||
REG = r"C:\Users\User\tmp\wr_accounts.jsonl"
|
||||
|
||||
|
||||
def keys():
|
||||
out = []
|
||||
for l in open(REG, encoding="utf-8"):
|
||||
d = json.loads(l)
|
||||
if d.get("key"):
|
||||
out.append((d.get("alias"), d["key"]))
|
||||
return out
|
||||
|
||||
|
||||
def call(key, method, path, data=None, timeout=120):
|
||||
req = urllib.request.Request(BASE + path, method=method)
|
||||
req.add_header("Authorization", "Bearer " + key)
|
||||
body = None
|
||||
if data is not None:
|
||||
body = json.dumps(data).encode()
|
||||
req.add_header("Content-Type", "application/json")
|
||||
try:
|
||||
with urllib.request.urlopen(req, body, timeout=timeout) as r:
|
||||
raw = r.read().decode()
|
||||
return r.status, (json.loads(raw) if raw.strip() else {})
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read().decode()
|
||||
try:
|
||||
return e.code, json.loads(raw)
|
||||
except Exception:
|
||||
return e.code, {"raw": raw[:400]}
|
||||
|
||||
|
||||
def pick_key():
|
||||
for alias, k in keys():
|
||||
s, d = call(k, "GET", "/v1/usage", timeout=30)
|
||||
if s == 200:
|
||||
left = {a["pool"]: a["left"] for a in d.get("allowances", [])}
|
||||
if left.get("machine-cpu", 0) > 0.5:
|
||||
return alias, k, left
|
||||
return None, None, None
|
||||
|
||||
|
||||
def wait_running(key, sid, timeout=180):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
s, d = call(key, "GET", "/v1/sandboxes/%s" % sid, timeout=40)
|
||||
st = (d or {}).get("state") or (d or {}).get("status")
|
||||
if st in ("running", "ready"):
|
||||
return st
|
||||
if st in ("failed", "error"):
|
||||
return st
|
||||
time.sleep(4)
|
||||
return "timeout"
|
||||
|
||||
|
||||
def main():
|
||||
cmd = sys.argv[1] if len(sys.argv) > 1 else "usage"
|
||||
if cmd == "usage":
|
||||
for alias, k in keys():
|
||||
s, d = call(k, "GET", "/v1/usage", timeout=30)
|
||||
if s != 200:
|
||||
print(alias[:34].ljust(34), "ERR", s, str(d)[:80])
|
||||
continue
|
||||
left = {a["pool"]: round(a["left"], 2) for a in d.get("allowances", [])}
|
||||
print(alias[:34].ljust(34), json.dumps(left))
|
||||
return
|
||||
alias, k, left = pick_key()
|
||||
if not k:
|
||||
print("NO KEY with quota left")
|
||||
return
|
||||
print("key:", alias)
|
||||
if cmd == "sh":
|
||||
command = sys.argv[2]
|
||||
s, d = call(k, "POST", "/v1/sandboxes", {"name": "tmp%d" % int(time.time()) % 100000,
|
||||
"vcpu": 1, "memoryMiB": 1024, "diskMiB": 3072})
|
||||
if s not in (200, 201):
|
||||
print("create fail", s, d); return
|
||||
sid = d.get("id") or d.get("sandbox", {}).get("id")
|
||||
print("sandbox", sid, wait_running(k, sid))
|
||||
s, r = call(k, "POST", "/v1/sandboxes/%s:exec" % sid, {"command": command, "user": "root"}, timeout=180)
|
||||
print("exec", s, json.dumps(r)[:1500])
|
||||
call(k, "DELETE", "/v1/sandboxes/%s" % sid, timeout=60)
|
||||
print("deleted")
|
||||
elif cmd == "create":
|
||||
name = sys.argv[2] if len(sys.argv) > 2 else "sbx"
|
||||
vcpu = int(sys.argv[3]) if len(sys.argv) > 3 else 1
|
||||
mem = int(sys.argv[4]) if len(sys.argv) > 4 else 1024
|
||||
disk = int(sys.argv[5]) if len(sys.argv) > 5 else 3072
|
||||
s, d = call(k, "POST", "/v1/sandboxes", {"name": name, "vcpu": vcpu, "memoryMiB": mem, "diskMiB": disk})
|
||||
print(s, json.dumps(d)[:600])
|
||||
elif cmd == "exec":
|
||||
sid, command = sys.argv[2], sys.argv[3]
|
||||
s, r = call(k, "POST", "/v1/sandboxes/%s:exec" % sid, {"command": command, "user": "root"}, timeout=300)
|
||||
print(s, json.dumps(r)[:2000])
|
||||
elif cmd == "list":
|
||||
s, d = call(k, "GET", "/v1/sandboxes")
|
||||
print(s, json.dumps(d)[:1500])
|
||||
elif cmd == "rm":
|
||||
s, d = call(k, "DELETE", "/v1/sandboxes/%s" % sys.argv[2], timeout=60)
|
||||
print(s, json.dumps(d)[:300])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""wr_gfarm.py <start> <count> — авторег Runtime через Google OAuth (пул reforrm.me).
|
||||
Пароли должны быть свежими (pwreset.py). Пишет wr_accounts.jsonl.
|
||||
"""
|
||||
import json, re, sys, time, urllib.request
|
||||
|
||||
import os
|
||||
PROF = os.environ.get("WR_PROF") or r"C:\Users\User\tmp\wrprof2"
|
||||
PROXY = os.environ.get("WR_PROXY") or ""
|
||||
GPW = r"C:\Users\User\tmp\hilink\gpw.jsonl"
|
||||
OUT = r"C:\Users\User\tmp\wr_accounts.jsonl"
|
||||
BASE = "https://withruntime.com"
|
||||
|
||||
|
||||
def log(*a):
|
||||
print(*a, flush=True)
|
||||
|
||||
|
||||
def usage(key):
|
||||
try:
|
||||
req = urllib.request.Request("https://api.withruntime.com/v1/usage")
|
||||
req.add_header("Authorization", "Bearer " + key)
|
||||
d = json.loads(urllib.request.urlopen(req, timeout=40).read())
|
||||
return {a["pool"]: {"q": a["quantity"], "left": a["left"]} for a in (d.get("allowances") or [])}
|
||||
except Exception as e:
|
||||
return {"err": str(e)[:100]}
|
||||
|
||||
|
||||
def _next(pg):
|
||||
b = pg.get_by_role("button", name=re.compile("Next|Далее"))
|
||||
if b.count():
|
||||
try:
|
||||
b.first.click(no_wait_after=True, timeout=8000)
|
||||
return True
|
||||
except Exception:
|
||||
try:
|
||||
b.first.evaluate("e=>e.click()")
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
pg.keyboard.press("Enter")
|
||||
return False
|
||||
|
||||
|
||||
def google_login(pg, email, pw):
|
||||
pg.goto("https://accounts.google.com/signin/v2/identifier?hl=en&flowName=GlifWebSignIn", wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
body = pg.inner_text("body")
|
||||
if "Choose an account" in body or "Выберите аккаунт" in body:
|
||||
try:
|
||||
pg.get_by_text(email, exact=False).first.click()
|
||||
time.sleep(4)
|
||||
except Exception:
|
||||
pass
|
||||
if pg.locator("input#identifierId:visible, input[type=email]:visible").count():
|
||||
el = pg.locator("input#identifierId:visible, input[type=email]:visible").first
|
||||
el.click(); el.type(email, delay=30); time.sleep(0.4)
|
||||
_next(pg)
|
||||
time.sleep(5)
|
||||
for i in range(10):
|
||||
if pg.locator("input[name=Passwd]:visible, input[type=password]:visible").count():
|
||||
break
|
||||
txt = pg.inner_text("body")
|
||||
if any(k in txt for k in ("Couldn't find", "Не удалось найти", "rejected")):
|
||||
log(" g: account problem:", re.sub(r"\s+", " ", txt)[:160])
|
||||
return False
|
||||
time.sleep(2)
|
||||
if not pg.locator("input[name=Passwd]:visible, input[type=password]:visible").count():
|
||||
log(" g: no pw field:", re.sub(r"\s+", " ", pg.inner_text("body"))[:160])
|
||||
return False
|
||||
pel = pg.locator("input[name=Passwd]:visible, input[type=password]:visible").first
|
||||
pel.click(); pel.type(pw, delay=45); time.sleep(0.4)
|
||||
_next(pg)
|
||||
time.sleep(7)
|
||||
txt = pg.inner_text("body")
|
||||
if any(k in txt for k in ("2-Step", "verify it", "Verify it", "tap Yes", "Enter a code", "Подтвердите", "Неверный пароль", "Wrong password")):
|
||||
log(" g: challenge/wrong pw:", re.sub(r"\s+", " ", txt)[:180])
|
||||
return False
|
||||
for lbl in ("I understand", "Понятно", "Accept", "Принять", "Continue", "Продолжить"):
|
||||
try:
|
||||
b = pg.get_by_role("button", name=lbl)
|
||||
if b.count() and b.first.is_visible():
|
||||
b.first.click(); time.sleep(3); log(" g: clicked", lbl)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def oauth_runtime(pg, email):
|
||||
pg.goto(BASE + "/sign-in", wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
try:
|
||||
pg.get_by_role("button", name="Continue with Google").click(no_wait_after=True, timeout=10000)
|
||||
except Exception:
|
||||
try:
|
||||
pg.get_by_role("button", name="Continue with Google").evaluate("e=>e.click()")
|
||||
except Exception as e:
|
||||
log(" oauth btn err", str(e)[:80])
|
||||
return False
|
||||
time.sleep(5)
|
||||
for step in range(10):
|
||||
url = pg.url
|
||||
try:
|
||||
body = pg.inner_text("body")
|
||||
except Exception:
|
||||
body = ""
|
||||
if url.startswith(BASE) and "sign-in" not in url:
|
||||
return True
|
||||
if "Choose an account" in body or "Выберите аккаунт" in body:
|
||||
try:
|
||||
pg.get_by_text(email, exact=False).first.click(); log(" chooser")
|
||||
except Exception:
|
||||
pass
|
||||
elif pg.get_by_role("button", name=re.compile("Continue|Продолжить|Allow|Разрешить")).count():
|
||||
try:
|
||||
pg.get_by_role("button", name=re.compile("Continue|Продолжить|Allow|Разрешить")).first.click(); log(" consent")
|
||||
except Exception:
|
||||
pass
|
||||
elif pg.locator("input[name=Passwd]:visible, input[type=password]:visible").count():
|
||||
try:
|
||||
pel = pg.locator("input[name=Passwd]:visible, input[type=password]:visible").first
|
||||
pel.click(); pel.type(sys._wr_pw, delay=45); time.sleep(0.4); _next(pg)
|
||||
log(" pw refilled")
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(5)
|
||||
log(" oauth stuck at", pg.url[:80])
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
arg1 = sys.argv[1] if len(sys.argv) > 1 else "0"
|
||||
start = int(arg1) if arg1.isdigit() else 0
|
||||
count = int(sys.argv[2]) if len(sys.argv) > 2 else 1
|
||||
rows = [json.loads(l) for l in open(GPW, encoding="utf-8") if l.strip()]
|
||||
rows = [r for r in rows if (r.get("email") or "").lower().endswith("@reforrm.me")]
|
||||
done = set()
|
||||
try:
|
||||
for l in open(OUT, encoding="utf-8"):
|
||||
d = json.loads(l)
|
||||
if d.get("alias", "").startswith("google:"):
|
||||
done.add(d["alias"].split(":", 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
FAILF = r"C:\Users\User\tmp\wr_gfail.json"
|
||||
fails = []
|
||||
try:
|
||||
fails = json.load(open(FAILF, encoding="utf-8"))
|
||||
except Exception:
|
||||
fails = []
|
||||
bad = {f[0] for f in fails}
|
||||
|
||||
def mark_fail(email, reason):
|
||||
fails.append([email, reason, int(time.time())])
|
||||
json.dump(fails, open(FAILF, "w", encoding="utf-8"), ensure_ascii=False)
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "left":
|
||||
cnt = int(sys.argv[2]) if len(sys.argv) > 2 else 6
|
||||
rows = [r for r in rows if (r.get("email") or "") not in done and (r.get("email") or "") not in bad]
|
||||
start, count = 0, cnt
|
||||
log("left mode: %d candidates, take %d" % (len(rows), count))
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
with sync_playwright() as p:
|
||||
args = ["--no-first-run", "--no-default-browser-check", "--disable-blink-features=AutomationControlled"]
|
||||
if PROXY:
|
||||
args.append("--proxy-server=" + PROXY)
|
||||
args.append("--proxy-bypass-list=<-loopback>")
|
||||
ctx = p.chromium.launch_persistent_context(
|
||||
PROF, channel="chrome", headless=False, args=args,
|
||||
viewport={"width": 1280, "height": 900})
|
||||
pg = ctx.pages[0] if ctx.pages else ctx.new_page()
|
||||
pg.set_default_timeout(30000)
|
||||
for r in rows[start:start + count]:
|
||||
email, pw = r["email"], r.get("password") or r.get("pw")
|
||||
if not pw:
|
||||
log("skip (no pw)", email)
|
||||
continue
|
||||
if email in done:
|
||||
log("skip (done)", email)
|
||||
continue
|
||||
if email in bad:
|
||||
log("skip (gfail)", email)
|
||||
continue
|
||||
log("==", email)
|
||||
sys._wr_pw = pw
|
||||
try:
|
||||
ctx.clear_cookies()
|
||||
if not google_login(pg, email, pw):
|
||||
log(" RESULT google_fail")
|
||||
mark_fail(email, "google_login")
|
||||
continue
|
||||
if not oauth_runtime(pg, email):
|
||||
log(" RESULT oauth_fail")
|
||||
continue
|
||||
log(" landed", pg.url[:70])
|
||||
js = """async (label) => {
|
||||
const r = await fetch('/api/account/keys', {method:'POST', headers:{'Content-Type':'application/json'},
|
||||
credentials:'include', body: JSON.stringify({action:'create', label:label, access:'full'})});
|
||||
return {s: r.status, t: await r.text()};
|
||||
}"""
|
||||
res = pg.evaluate(js, "farm")
|
||||
key = None
|
||||
try:
|
||||
d = json.loads(res["t"])
|
||||
cred = d.get("credential") or {}
|
||||
key = cred.get("plaintext") or cred.get("key") or d.get("key")
|
||||
except Exception:
|
||||
pass
|
||||
if not key:
|
||||
log(" RESULT key_fail", str(res)[:200])
|
||||
continue
|
||||
us = usage(key)
|
||||
log(" USAGE", json.dumps(us)[:180])
|
||||
with open(OUT, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps({"alias": "google:" + email, "key": key, "ts": int(time.time()), "usage": us}) + "\n")
|
||||
log(" SAVED", key[:22] + "...")
|
||||
except Exception as e:
|
||||
log(" EXC", str(e)[:180])
|
||||
time.sleep(6)
|
||||
try:
|
||||
ctx.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""wr_key.py <name> — создать API-ключ на /account/keys и вывести его."""
|
||||
import json, re, sys, time
|
||||
sys.path.insert(0, r"C:/Users/User/tmp")
|
||||
import wr_reg
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
|
||||
def main():
|
||||
name = sys.argv[1] if len(sys.argv) > 1 else "farm"
|
||||
with sync_playwright() as p:
|
||||
br, ctx, pg = wr_reg.connect(p)
|
||||
pg.goto("https://withruntime.com/account/keys", wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
pg.get_by_role("button", name="New key").first.click()
|
||||
time.sleep(2)
|
||||
# диалог
|
||||
dlg = pg.locator("[role=dialog]")
|
||||
print("dialog:", dlg.count())
|
||||
inputs = pg.eval_on_selector_all("input:visible", "els=>els.map(e=>({id:e.id,name:e.name,ph:e.placeholder,type:e.type}))")
|
||||
print("inputs:", inputs)
|
||||
if inputs:
|
||||
sel = "input:visible" if not inputs[0].get("id") else "input#%s" % inputs[0]["id"]
|
||||
pg.locator(sel).first.click()
|
||||
pg.locator(sel).first.type(name, delay=40)
|
||||
# кнопки диалога
|
||||
btns = [b.inner_text().strip() for b in pg.locator("[role=dialog] button, dialog button").all()]
|
||||
print("dlg buttons:", btns)
|
||||
for lbl in ("Create", "Create key", "Create API key", "Add"):
|
||||
b = pg.get_by_role("button", name=re.compile(lbl, re.I))
|
||||
if b.count() and b.first.is_visible():
|
||||
b.first.click()
|
||||
print("clicked", lbl)
|
||||
break
|
||||
time.sleep(4)
|
||||
txt = pg.inner_text("body")
|
||||
print("TEXT:", re.sub(r"\s+", " ", txt)[:800])
|
||||
m = re.findall(r"\b(rt_[A-Za-z0-9_\-]{10,}|sk-[A-Za-z0-9_\-]{10,})\b", txt)
|
||||
print("KEYS:", m)
|
||||
try:
|
||||
ctx.storage_state(path=wr_reg.STATE)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""wr_key2.py [label] — в профиле wrprof2 (Google-сессия) создать ключ и проверить usage."""
|
||||
import json, sys, time, urllib.request
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
PROF = r"C:\Users\User\tmp\wrprof2"
|
||||
STATE = r"C:\Users\User\tmp\wr_state2.json"
|
||||
BASE = "https://withruntime.com"
|
||||
label = sys.argv[1] if len(sys.argv) > 1 else "farm"
|
||||
|
||||
|
||||
def usage(key):
|
||||
try:
|
||||
req = urllib.request.Request("https://api.withruntime.com/v1/usage")
|
||||
req.add_header("Authorization", "Bearer " + key)
|
||||
d = json.loads(urllib.request.urlopen(req, timeout=40).read())
|
||||
return {a["pool"]: {"q": a["quantity"], "left": a["left"]} for a in (d.get("allowances") or [])}
|
||||
except Exception as e:
|
||||
return {"err": str(e)[:100]}
|
||||
|
||||
|
||||
with sync_playwright() as p:
|
||||
ctx = p.chromium.launch_persistent_context(
|
||||
PROF, channel="chrome", headless=False,
|
||||
args=["--no-first-run", "--no-default-browser-check", "--disable-blink-features=AutomationControlled"],
|
||||
viewport={"width": 1280, "height": 900})
|
||||
pg = ctx.pages[0] if ctx.pages else ctx.new_page()
|
||||
pg.goto(BASE + "/account/keys", wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
print("URL", pg.url)
|
||||
js = """async (label) => {
|
||||
const r = await fetch('/api/account/keys', {method:'POST', headers:{'Content-Type':'application/json'},
|
||||
credentials:'include', body: JSON.stringify({action:'create', label:label, access:'full'})});
|
||||
return {s: r.status, t: await r.text()};
|
||||
}"""
|
||||
res = pg.evaluate(js, label)
|
||||
print("status", res.get("s"))
|
||||
key = None
|
||||
try:
|
||||
d = json.loads(res["t"])
|
||||
cred = d.get("credential") or {}
|
||||
key = cred.get("plaintext") or cred.get("key") or d.get("key")
|
||||
if not key:
|
||||
print("RESP", json.dumps(d)[:400])
|
||||
except Exception:
|
||||
print("RAW", str(res.get("t"))[:300])
|
||||
if key:
|
||||
print("KEY", key[:26] + "...")
|
||||
us = usage(key)
|
||||
print("USAGE", json.dumps(us))
|
||||
rec = {"alias": "google:flk8ka4g4op6@reforrm.me", "key": key, "ts": int(time.time()), "usage": us}
|
||||
with open(r"C:\Users\User\tmp\wr_accounts.jsonl", "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec) + "\n")
|
||||
print("SAVED")
|
||||
ctx.close()
|
||||
@@ -0,0 +1,54 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""wr_net.py <name> — headless: создать ключ через UI и записать все XHR (endpoint discovery)."""
|
||||
import json, re, sys, time
|
||||
|
||||
ST = r"C:\Users\User\tmp\wr_state.json"
|
||||
name = sys.argv[1] if len(sys.argv) > 1 else "farm"
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
calls = []
|
||||
|
||||
with sync_playwright() as p:
|
||||
b = p.chromium.launch(headless=True, channel="chrome")
|
||||
ctx = b.new_context(storage_state=ST, viewport={"width": 1400, "height": 900})
|
||||
pg = ctx.new_page()
|
||||
|
||||
def on_resp(r):
|
||||
if "/api/" in r.url or "withruntime" in r.url and r.request.resource_type in ("xhr", "fetch"):
|
||||
try:
|
||||
body = r.text()[:600]
|
||||
except Exception:
|
||||
body = "<no body>"
|
||||
calls.append({"m": r.request.method, "url": r.url, "s": r.status,
|
||||
"post": (r.request.post_data or "")[:300], "resp": body})
|
||||
|
||||
pg.on("response", on_resp)
|
||||
pg.goto("https://withruntime.com/account/keys", wait_until="domcontentloaded")
|
||||
time.sleep(4)
|
||||
print("URL", pg.url)
|
||||
txt = pg.inner_text("body")
|
||||
print("SIGNED:", "No keys yet" in txt or "Agents & API keys" in txt, "|", re.sub(r"\s+", " ", txt)[:200])
|
||||
try:
|
||||
pg.get_by_role("button", name="New key").first.click()
|
||||
time.sleep(2)
|
||||
pg.locator("input#key-name").click()
|
||||
pg.locator("input#key-name").type(name, delay=40)
|
||||
time.sleep(0.5)
|
||||
for lbl in ("Create key", "Create", "Add key"):
|
||||
btn = pg.get_by_role("button", name=re.compile(lbl, re.I))
|
||||
if btn.count():
|
||||
btn.first.click()
|
||||
print("clicked", lbl)
|
||||
break
|
||||
time.sleep(5)
|
||||
t2 = pg.inner_text("body")
|
||||
print("AFTER:", re.sub(r"\s+", " ", t2)[:900])
|
||||
print("KEYS FOUND:", re.findall(r"\b(rk_[A-Za-z0-9_\-]{8,}|rt_[A-Za-z0-9_\-]{8,}|sk-[A-Za-z0-9_\-]{8,}|wr_[A-Za-z0-9_\-]{8,})\b", t2))
|
||||
ctx.storage_state(path=ST)
|
||||
except Exception as e:
|
||||
print("ACT ERR", str(e)[:200])
|
||||
print("=== CALLS ===")
|
||||
for c in calls:
|
||||
print(c["m"], c["s"], c["url"][:120], "|", c["post"][:120], "|", c["resp"][:200].replace("\n", " "))
|
||||
b.close()
|
||||
@@ -0,0 +1,156 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""wr_one.py <email> [mailpass] — рега/вход Runtime одним аккаунтом + API-ключ.
|
||||
Код читается: gmail -> VPS wr_code2.py ; t-online -> VPS tcode2.py.
|
||||
Результат дописывается в C:/Users/User/tmp/wr_accounts.jsonl
|
||||
"""
|
||||
import json, os, re, subprocess, sys, time
|
||||
|
||||
sys.path.insert(0, r"C:/Users/User/tmp")
|
||||
import wr_reg
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = "https://withruntime.com"
|
||||
OUT = r"C:\Users\User\tmp\wr_accounts.jsonl"
|
||||
VPS = "root@144.31.34.147"
|
||||
|
||||
|
||||
def log(*a):
|
||||
print(*a, flush=True)
|
||||
|
||||
|
||||
def ssh(cmd, timeout=180):
|
||||
r = subprocess.run(["ssh", "-o", "ConnectTimeout=15", "-o", "StrictHostKeyChecking=no", VPS, cmd],
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
return (r.stdout or "") + (("\nERR:" + r.stderr[-200:]) if r.stderr.strip() else "")
|
||||
|
||||
|
||||
def get_code(email, mailpass, min_ts, timeout=120):
|
||||
if email.lower().endswith("@gmail.com"):
|
||||
out = ssh("python3 /root/wr_code2.py '%s' %d %d" % (email, min_ts, timeout), timeout + 60)
|
||||
else:
|
||||
# tcode2.py <addr> <pw> code <min_uid> <timeout>; min_uid берём по времени -> используем UID 0 и фильтр по свежести
|
||||
out = ssh("python3 /root/ton_code.py '%s' '%s' withruntime %d %d" % (email, mailpass, max(0, min_ts - 60), timeout), timeout + 90)
|
||||
log(" code_raw:", out.strip()[:160])
|
||||
m = re.search(r"CODE=([0-9]{6})|\b([0-9]{6})\b", out)
|
||||
if m:
|
||||
return m.group(1) or m.group(2)
|
||||
return None
|
||||
|
||||
|
||||
def sign_in(pg, ctx, email):
|
||||
pg.goto(BASE + "/sign-in", wait_until="domcontentloaded")
|
||||
time.sleep(2.5)
|
||||
if "sign-in" not in pg.url:
|
||||
log(" already signed in:", pg.url)
|
||||
return True
|
||||
try:
|
||||
pg.get_by_role("button", name="Continue with email").click(no_wait_after=True, timeout=8000)
|
||||
except Exception:
|
||||
try:
|
||||
pg.get_by_role("button", name="Continue with email").evaluate("e=>e.click()")
|
||||
except Exception as e:
|
||||
log(" no email btn", str(e)[:80])
|
||||
time.sleep(2)
|
||||
el = pg.locator("input#cloud-email")
|
||||
el.click()
|
||||
el.type(email, delay=30)
|
||||
time.sleep(1.5)
|
||||
for i in range(40):
|
||||
b = pg.get_by_role("button", name=re.compile("Continue with email|Sending", re.I))
|
||||
if b.count():
|
||||
if not b.first.get_attribute("disabled") and "Sending" not in b.first.inner_text():
|
||||
break
|
||||
time.sleep(1)
|
||||
min_ts = int(time.time()) - 5
|
||||
try:
|
||||
pg.get_by_role("button", name="Continue with email").click(no_wait_after=True, timeout=10000)
|
||||
except Exception:
|
||||
pg.get_by_role("button", name="Continue with email").evaluate("e=>e.click()")
|
||||
log(" code requested")
|
||||
return "wait_code"
|
||||
|
||||
|
||||
def submit_code(pg, code):
|
||||
for i in range(15):
|
||||
if pg.locator("input#cloud-code").count():
|
||||
break
|
||||
time.sleep(1)
|
||||
if not pg.locator("input#cloud-code").count():
|
||||
log(" no code field:", re.sub(r"\s+", " ", pg.inner_text("body"))[:200])
|
||||
return False
|
||||
ce = pg.locator("input#cloud-code")
|
||||
ce.click()
|
||||
ce.type(code, delay=80)
|
||||
time.sleep(0.6)
|
||||
try:
|
||||
pg.get_by_role("button", name=re.compile("Continue|Sign in|Verify", re.I)).first.click(no_wait_after=True, timeout=8000)
|
||||
except Exception:
|
||||
pg.keyboard.press("Enter")
|
||||
for i in range(20):
|
||||
time.sleep(2)
|
||||
if "sign-in" not in pg.url:
|
||||
break
|
||||
body = pg.inner_text("body")
|
||||
if "sign-in" in pg.url or "Check your email" in body:
|
||||
log(" FAIL body:", re.sub(r"\s+", " ", body)[:220])
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def make_key(pg, label="farm"):
|
||||
js = """async (label) => {
|
||||
const r = await fetch('/api/account/keys', {method:'POST', headers:{'Content-Type':'application/json'},
|
||||
credentials:'include', body: JSON.stringify({action:'create', label:label, access:'full'})});
|
||||
return {s: r.status, t: await r.text()};
|
||||
}"""
|
||||
try:
|
||||
res = pg.evaluate(js, label)
|
||||
except Exception as e:
|
||||
return None, "evaluate: " + str(e)[:150]
|
||||
if res.get("s") != 200:
|
||||
return None, str(res)
|
||||
try:
|
||||
d = json.loads(res["t"])
|
||||
except Exception:
|
||||
return None, res["t"][:300]
|
||||
cred = d.get("credential") or {}
|
||||
key = cred.get("plaintext") or cred.get("key") or cred.get("secret") or d.get("key")
|
||||
return (key, None) if key else (None, json.dumps(d)[:400])
|
||||
|
||||
|
||||
def main():
|
||||
email = sys.argv[1]
|
||||
mailpass = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
min_ts = int(sys.argv[3]) if len(sys.argv) > 3 else int(time.time()) - 5
|
||||
with sync_playwright() as p:
|
||||
br, ctx, pg = wr_reg.connect(p)
|
||||
ctx.clear_cookies()
|
||||
st = sign_in(pg, ctx, email)
|
||||
if st is not True:
|
||||
code = get_code(email, mailpass, min_ts, 130)
|
||||
if not code:
|
||||
log("RESULT NO_CODE")
|
||||
return
|
||||
log(" code:", code)
|
||||
if not submit_code(pg, code):
|
||||
log("RESULT CODE_REJECTED")
|
||||
return
|
||||
log(" signed | url", pg.url[:70])
|
||||
try:
|
||||
c = ctx.request.get(BASE + "/api/account/console", timeout=30000).json()
|
||||
log(" trial:", json.dumps(c.get("trial"))[:200])
|
||||
except Exception as e:
|
||||
c = {}
|
||||
log(" console err", str(e)[:80])
|
||||
key, err = make_key(pg)
|
||||
if not key:
|
||||
log("RESULT KEY_FAIL", str(err)[:200])
|
||||
return
|
||||
rec = {"alias": email, "key": key, "ts": int(time.time()), "trial": (c or {}).get("trial")}
|
||||
with open(OUT, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec) + "\n")
|
||||
log("RESULT OK", key[:20] + "...", "| trial:", json.dumps((c or {}).get("trial"))[:120])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,319 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""wr_reg.py — авторег withruntime.com через реальный Chrome (CDP).
|
||||
usage:
|
||||
wr_reg.py send <alias> — открыть sign-in, ввести email, отправить код
|
||||
wr_reg.py verify <code> — ввести код, дождаться сессии
|
||||
wr_reg.py key — создать API-ключ, вывести его
|
||||
wr_reg.py usage — GET /v1/usage сохранённым ключом
|
||||
wr_reg.py whoami — состояние страницы
|
||||
"""
|
||||
import json, os, re, subprocess, sys, time
|
||||
|
||||
CHROME = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
|
||||
PROFDIR = r"C:\Users\User\tmp\wrprof"
|
||||
PORT = 9223
|
||||
STATE = r"C:\Users\User\tmp\wr_state.json"
|
||||
KEYS = r"C:\Users\User\tmp\wr_keys.jsonl"
|
||||
BASE = "https://withruntime.com"
|
||||
PY = r"C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe"
|
||||
ENV = dict(os.environ)
|
||||
|
||||
|
||||
def log(*a):
|
||||
print(*a, flush=True)
|
||||
|
||||
|
||||
def ensure_chrome():
|
||||
import urllib.request
|
||||
try:
|
||||
urllib.request.urlopen("http://127.0.0.1:%d/json/version" % PORT, timeout=3).read()
|
||||
log("chrome: already up")
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
os.makedirs(PROFDIR, exist_ok=True)
|
||||
args = [CHROME, "--remote-debugging-port=%d" % PORT, "--user-data-dir=" + PROFDIR,
|
||||
"--no-first-run", "--no-default-browser-check", "--disable-features=Translate",
|
||||
"--window-size=1280,900", "about:blank"]
|
||||
DETACHED = 0x00000008 | 0x00000200
|
||||
subprocess.Popen(args, creationflags=DETACHED, close_fds=True)
|
||||
for _ in range(40):
|
||||
time.sleep(0.5)
|
||||
try:
|
||||
urllib.request.urlopen("http://127.0.0.1:%d/json/version" % PORT, timeout=2).read()
|
||||
log("chrome: launched")
|
||||
return
|
||||
except Exception:
|
||||
continue
|
||||
raise SystemExit("chrome launch failed")
|
||||
|
||||
|
||||
def page_new(p):
|
||||
ctx = p.contexts[0] if p.contexts else p.new_context()
|
||||
pages = [x for x in ctx.pages if x.url not in ("", "about:blank")]
|
||||
if pages:
|
||||
return ctx, pages[-1]
|
||||
for pg in ctx.pages:
|
||||
if pg.url == "about:blank":
|
||||
return ctx, pg
|
||||
return ctx, ctx.new_page()
|
||||
|
||||
|
||||
def kill_prof_chrome():
|
||||
try:
|
||||
import psutil
|
||||
except Exception:
|
||||
return
|
||||
for pr in psutil.process_iter(["pid", "name", "cmdline"]):
|
||||
try:
|
||||
if pr.info["name"] and "chrome" in pr.info["name"].lower():
|
||||
cl = " ".join(pr.info["cmdline"] or [])
|
||||
if "wrprof" in cl and str(pr.info["pid"]) != str(os.getpid()):
|
||||
pr.kill()
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def connect(pw):
|
||||
last = None
|
||||
for attempt in range(4):
|
||||
try:
|
||||
ensure_chrome()
|
||||
br = pw.chromium.connect_over_cdp("http://127.0.0.1:%d" % PORT, timeout=15000)
|
||||
ctx, pg = page_new(br)
|
||||
pg.set_default_timeout(30000)
|
||||
return br, ctx, pg
|
||||
except Exception as e:
|
||||
last = e
|
||||
log("connect retry", attempt, str(e)[:120])
|
||||
kill_prof_chrome()
|
||||
time.sleep(3)
|
||||
raise SystemExit("cdp connect failed: %s" % last)
|
||||
|
||||
|
||||
def main():
|
||||
cmd = sys.argv[1]
|
||||
from playwright.sync_api import sync_playwright
|
||||
with sync_playwright() as pw:
|
||||
br, ctx, pg = connect(pw)
|
||||
|
||||
if cmd == "whoami":
|
||||
log("URL:", pg.url)
|
||||
log("TEXT:", pg.inner_text("body")[:800])
|
||||
return
|
||||
|
||||
if cmd == "send":
|
||||
alias = sys.argv[2]
|
||||
pg.goto(BASE + "/sign-in", wait_until="domcontentloaded")
|
||||
time.sleep(2)
|
||||
pg.reload(wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
cw = pg.get_by_role("button", name="Continue with email")
|
||||
try:
|
||||
cw.click(no_wait_after=True, timeout=8000)
|
||||
except Exception as e:
|
||||
log("cw click fallback:", str(e)[:80])
|
||||
cw.evaluate("e=>e.click()")
|
||||
time.sleep(2)
|
||||
form = pg.locator("form:has(input#cloud-email)")
|
||||
form.locator("input#cloud-email").fill(alias)
|
||||
time.sleep(0.5)
|
||||
btn = form.locator("button[type=submit]")
|
||||
log("btn text before:", btn.inner_text())
|
||||
for i in range(40):
|
||||
if btn.get_attribute("disabled") is None:
|
||||
break
|
||||
time.sleep(1)
|
||||
log("tsr:", pg.eval_on_selector("input[name=cf-turnstile-response]", "e=>e.value.length") if pg.query_selector("input[name=cf-turnstile-response]") else "no-input")
|
||||
log("btn text:", btn.inner_text(), "disabled:", btn.get_attribute("disabled"))
|
||||
btn.click()
|
||||
time.sleep(5)
|
||||
log("URL:", pg.url)
|
||||
log("TEXT:", pg.inner_text("body")[:600])
|
||||
return
|
||||
|
||||
if cmd == "auto":
|
||||
alias = sys.argv[2]
|
||||
pg.goto(BASE + "/sign-in", wait_until="domcontentloaded")
|
||||
time.sleep(2)
|
||||
pg.reload(wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
cw = pg.get_by_role("button", name="Continue with email")
|
||||
try:
|
||||
cw.click(no_wait_after=True, timeout=8000)
|
||||
except Exception as e:
|
||||
log("cw click fallback:", str(e)[:80])
|
||||
cw.evaluate("e=>e.click()")
|
||||
time.sleep(2)
|
||||
form = pg.locator("form:has(input#cloud-email)")
|
||||
form.locator("input#cloud-email").fill(alias)
|
||||
btn = form.locator("button[type=submit]")
|
||||
for i in range(110):
|
||||
try:
|
||||
tx = btn.inner_text()
|
||||
dis = btn.get_attribute("disabled")
|
||||
except Exception:
|
||||
tx, dis = "", None
|
||||
if "Sending" not in tx and dis is None:
|
||||
break
|
||||
time.sleep(1)
|
||||
log("sendbtn:", tx, "disabled:", dis)
|
||||
min_ts = int(time.time()) - 5
|
||||
try:
|
||||
btn.click(no_wait_after=True, timeout=10000)
|
||||
log("clicked send")
|
||||
except Exception as e:
|
||||
log("click err:", str(e)[:120])
|
||||
btn.evaluate("e=>e.click()")
|
||||
log("clicked send via js")
|
||||
ok = False
|
||||
for i in range(20):
|
||||
time.sleep(2)
|
||||
if "Check your email" in pg.inner_text("body"):
|
||||
ok = True
|
||||
break
|
||||
log("code_requested:", ok)
|
||||
if not ok:
|
||||
log("TEXT:", pg.inner_text("body")[:400])
|
||||
return
|
||||
code = None
|
||||
for i in range(6):
|
||||
r = subprocess.run(["ssh", "-o", "ConnectTimeout=15", "root@144.31.34.147",
|
||||
"cd /root && timeout 60 python3 wr_code2.py '%s' %d 55" % (alias, min_ts)],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
m = re.search(r"CODE=(\w{6})", r.stdout or "")
|
||||
if m:
|
||||
code = m.group(1)
|
||||
break
|
||||
log("code poll", i, (r.stdout or "").strip()[-80:])
|
||||
time.sleep(5)
|
||||
log("code:", code)
|
||||
if not code:
|
||||
return
|
||||
codeel = pg.locator("input#cloud-code")
|
||||
codeel.click()
|
||||
codeel.fill(code)
|
||||
time.sleep(0.6)
|
||||
log("FIELDS:", pg.eval_on_selector_all("input", "els=>els.filter(e=>e.type!='hidden').map(e=>e.id+'='+e.value).join(' | ')"))
|
||||
codeel.press("Enter")
|
||||
time.sleep(9)
|
||||
log("URL:", pg.url)
|
||||
log("TEXT:", pg.inner_text("body")[:700])
|
||||
try:
|
||||
ctx.storage_state(path=STATE)
|
||||
except Exception as e:
|
||||
log("state err", e)
|
||||
return
|
||||
|
||||
if cmd == "finish":
|
||||
alias, code = sys.argv[2], sys.argv[3]
|
||||
pg.fill("input#cloud-email", alias)
|
||||
time.sleep(0.4)
|
||||
pg.fill("input#cloud-code", code)
|
||||
time.sleep(0.6)
|
||||
log("FIELDS:", pg.eval_on_selector_all("input", "els=>els.filter(e=>e.type!='hidden').map(e=>e.id+'='+e.value).join(' | ')"))
|
||||
pg.locator("input#cloud-code").press("Enter")
|
||||
time.sleep(9)
|
||||
log("URL:", pg.url)
|
||||
log("TEXT:", pg.inner_text("body")[:900])
|
||||
try:
|
||||
ctx.storage_state(path=STATE)
|
||||
log("state saved")
|
||||
except Exception as e:
|
||||
log("state err", e)
|
||||
return
|
||||
|
||||
if cmd == "type":
|
||||
code = sys.argv[2]
|
||||
log("URL:", pg.url)
|
||||
info = pg.eval_on_selector_all("input", "els=>els.map(e=>({id:e.id,type:e.type,ml:e.maxLength,name:e.name,ph:e.placeholder,vis:!!e.offsetParent}))")
|
||||
log("INPUTS:", json.dumps(info))
|
||||
tgt = None
|
||||
for e in info:
|
||||
if e["vis"] and e["type"] != "email" and e["type"] != "hidden":
|
||||
tgt = e
|
||||
break
|
||||
if tgt is None:
|
||||
log("NO_CODE_INPUT"); return
|
||||
sel = ("#%s" % tgt["id"]) if tgt["id"] else "input[type=%s]:visible" % tgt["type"]
|
||||
el = pg.locator(sel).first
|
||||
el.click()
|
||||
el.type(code, delay=140)
|
||||
time.sleep(1)
|
||||
log("FILLED:", pg.eval_on_selector_all("input", "els=>els.map(e=>e.id+':'+e.value).join(' | ')"))
|
||||
clicked = False
|
||||
for b in pg.locator("button[type=submit]").all():
|
||||
try:
|
||||
tx = b.inner_text().strip()
|
||||
if b.get_attribute("disabled") is None and tx.lower().startswith(("continue", "sign", "verif")):
|
||||
b.click(); clicked = True; log("clicked:", tx); break
|
||||
except Exception:
|
||||
pass
|
||||
if not clicked:
|
||||
try:
|
||||
pg.keyboard.press("Enter"); log("pressed Enter")
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(9)
|
||||
log("URL:", pg.url)
|
||||
log("TEXT:", pg.inner_text("body")[:800])
|
||||
try:
|
||||
ctx.storage_state(path=STATE)
|
||||
log("state saved")
|
||||
except Exception as e:
|
||||
log("state err", e)
|
||||
return
|
||||
|
||||
if cmd == "verify":
|
||||
code = sys.argv[2]
|
||||
log("URL:", pg.url)
|
||||
log("TEXT0:", pg.inner_text("body")[:300])
|
||||
boxes = pg.locator("input:visible")
|
||||
n = boxes.count()
|
||||
log("visible inputs:", n)
|
||||
filled = False
|
||||
for i in range(n):
|
||||
el = boxes.nth(i)
|
||||
t = (el.get_attribute("type") or "").lower()
|
||||
ml = el.get_attribute("maxlength")
|
||||
if t in ("tel", "text", "number") and (ml in ("1", "6", None)):
|
||||
try:
|
||||
el.click()
|
||||
el.type(code, delay=120)
|
||||
filled = True
|
||||
log("typed into", i, t, ml)
|
||||
break
|
||||
except Exception as e:
|
||||
log("type err", i, e)
|
||||
if not filled:
|
||||
pg.keyboard.type(code, delay=120)
|
||||
time.sleep(6)
|
||||
log("URL:", pg.url)
|
||||
log("TEXT:", pg.inner_text("body")[:600])
|
||||
ctx.storage_state(path=STATE)
|
||||
log("state saved")
|
||||
return
|
||||
|
||||
if cmd == "key":
|
||||
pg.goto(BASE + "/account/keys", wait_until="domcontentloaded")
|
||||
time.sleep(4)
|
||||
log("URL:", pg.url)
|
||||
txt = pg.inner_text("body")
|
||||
log("TEXT:", txt[:800])
|
||||
btns = pg.locator("button")
|
||||
labels = [btns.nth(i).inner_text().strip() for i in range(btns.count())]
|
||||
log("BUTTONS:", labels[:30])
|
||||
return
|
||||
|
||||
if cmd == "usage":
|
||||
key = json.load(open(KEYS))[-1]["key"] if os.path.exists(KEYS) else None
|
||||
r = subprocess.run(['curl', '-s', '-m', '25', '-H', 'Authorization: Bearer %s' % key,
|
||||
'https://api.withruntime.com/v1/usage'], capture_output=True, text=True)
|
||||
log("HTTP_BODY:", r.stdout[:1500])
|
||||
return
|
||||
|
||||
raise SystemExit("unknown cmd")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,90 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""zte_socks.py [port] — SOCKS5-прокси, весь egress через мобильный IP (bind 192.168.0.2).
|
||||
Chrome: --proxy-server=socks5://127.0.0.1:1081
|
||||
"""
|
||||
import socket, struct, sys, threading
|
||||
|
||||
BIND_IP = "192.168.0.2"
|
||||
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 1081
|
||||
BUFS = 65536
|
||||
|
||||
|
||||
def pipe(a, b):
|
||||
try:
|
||||
while True:
|
||||
r, _, _ = __import__("select").select([a, b], [], [], 300)
|
||||
if not r:
|
||||
break
|
||||
for s in r:
|
||||
data = s.recv(BUFS)
|
||||
if not data:
|
||||
return
|
||||
(b if s is a else a).sendall(data)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
for s in (a, b):
|
||||
try:
|
||||
s.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def recv_exact(c, n):
|
||||
buf = b""
|
||||
while len(buf) < n:
|
||||
chunk = c.recv(n - len(buf))
|
||||
if not chunk:
|
||||
raise IOError("eof")
|
||||
buf += chunk
|
||||
return buf
|
||||
|
||||
|
||||
def handle(c):
|
||||
try:
|
||||
ver, n = recv_exact(c, 2)
|
||||
recv_exact(c, n) # methods
|
||||
c.sendall(b"\x05\x00") # no auth
|
||||
ver, cmd, rsv, atyp = recv_exact(c, 4)
|
||||
if atyp == 1:
|
||||
host = socket.inet_ntoa(recv_exact(c, 4))
|
||||
elif atyp == 3:
|
||||
ln = recv_exact(c, 1)[0]
|
||||
host = recv_exact(c, ln).decode()
|
||||
elif atyp == 4:
|
||||
host = socket.inet_ntop(socket.AF_INET6, recv_exact(c, 16))
|
||||
else:
|
||||
c.close(); return
|
||||
port = struct.unpack("!H", recv_exact(c, 2))[0]
|
||||
if cmd != 1:
|
||||
c.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00"); c.close(); return
|
||||
try:
|
||||
up = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
up.settimeout(25)
|
||||
up.bind((BIND_IP, 0))
|
||||
up.connect((host, port))
|
||||
up.settimeout(None)
|
||||
except Exception:
|
||||
c.sendall(b"\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00"); c.close(); return
|
||||
c.sendall(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00")
|
||||
threading.Thread(target=pipe, args=(c, up), daemon=True).start()
|
||||
except Exception:
|
||||
try:
|
||||
c.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
srv.bind(("127.0.0.1", PORT))
|
||||
srv.listen(128)
|
||||
print("socks5 on 127.0.0.1:%d -> bind %s" % (PORT, BIND_IP), flush=True)
|
||||
while True:
|
||||
c, _ = srv.accept()
|
||||
threading.Thread(target=handle, args=(c,), daemon=True).start()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user