From 57f005839c453f2dc2a11298c4a928399d30650a Mon Sep 17 00:00:00 2001 From: reform Date: Fri, 23 Oct 2026 20:04:08 +0300 Subject: [PATCH] recovered snapshot from suspended aaronjaworski710 (history unavailable) --- .gitignore | 9 + FINDINGS.md | 106 +++++ README.md | 37 ++ USAGE.md | 66 +++ autoreg/cb_reg.py | 162 +++++++ autoreg/cb_reg2.py | 170 +++++++ autoreg/fast_reg.py | 140 ++++++ autoreg/gh_autoreg.py | 655 ++++++++++++++++++++++++++ autoreg/gh_db.py | 244 ++++++++++ autoreg/gh_mail.py | 139 ++++++ autoreg/gh_pat.py | 217 +++++++++ autoreg/gh_pipeline.py | 113 +++++ autoreg/gh_postreg.py | 777 +++++++++++++++++++++++++++++++ autoreg/gh_runner.py | 131 ++++++ autoreg/gh_verify_accounts.py | 102 ++++ autoreg/gh_watchdog.py | 154 ++++++ autoreg/gl_gmail_reg.py | 141 ++++++ autoreg/gl_home_reg.py | 154 ++++++ autoreg/png2ascii.py | 116 +++++ autoreg/scan_forge.py | 18 + autoreg/tt_chrome_code_signup.py | 123 +++++ autoreg/tt_chrome_reg.py | 94 ++++ autoreg/tt_google_sso.py | 103 ++++ autoreg/tt_signin_code.py | 135 ++++++ autoreg/tt_wos_reg2.py | 412 ++++++++++++++++ client/README.md | 196 ++++++++ client/device_login_run.py | 16 + client/dyn_client.json | 1 + client/e2e_test.py | 124 +++++ client/probe_identity.py | 19 + client/probe_identity_refresh.py | 39 ++ client/probe_orpc.py | 42 ++ client/probe_refresh.py | 45 ++ client/probe_start.py | 27 ++ client/probe_token.py | 39 ++ client/type2api.py | 160 +++++++ client/type_client.py | 490 +++++++++++++++++++ requirements.txt | 6 + server/dashboard.html | 114 +++++ server/gateway.py | 239 ++++++++++ server/manager.py | 362 ++++++++++++++ tools.json | 81 ++++ 42 files changed, 6518 insertions(+) create mode 100644 .gitignore create mode 100644 FINDINGS.md create mode 100644 README.md create mode 100644 USAGE.md create mode 100644 autoreg/cb_reg.py create mode 100644 autoreg/cb_reg2.py create mode 100644 autoreg/fast_reg.py create mode 100644 autoreg/gh_autoreg.py create mode 100644 autoreg/gh_db.py create mode 100644 autoreg/gh_mail.py create mode 100644 autoreg/gh_pat.py create mode 100644 autoreg/gh_pipeline.py create mode 100644 autoreg/gh_postreg.py create mode 100644 autoreg/gh_runner.py create mode 100644 autoreg/gh_verify_accounts.py create mode 100644 autoreg/gh_watchdog.py create mode 100644 autoreg/gl_gmail_reg.py create mode 100644 autoreg/gl_home_reg.py create mode 100644 autoreg/png2ascii.py create mode 100644 autoreg/scan_forge.py create mode 100644 autoreg/tt_chrome_code_signup.py create mode 100644 autoreg/tt_chrome_reg.py create mode 100644 autoreg/tt_google_sso.py create mode 100644 autoreg/tt_signin_code.py create mode 100644 autoreg/tt_wos_reg2.py create mode 100644 client/README.md create mode 100644 client/device_login_run.py create mode 100644 client/dyn_client.json create mode 100644 client/e2e_test.py create mode 100644 client/probe_identity.py create mode 100644 client/probe_identity_refresh.py create mode 100644 client/probe_orpc.py create mode 100644 client/probe_refresh.py create mode 100644 client/probe_start.py create mode 100644 client/probe_token.py create mode 100644 client/type2api.py create mode 100644 client/type_client.py create mode 100644 requirements.txt create mode 100644 server/dashboard.html create mode 100644 server/gateway.py create mode 100644 server/manager.py create mode 100644 tools.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..090d326 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +*.log +*.db +*.jsonl +*.png +*.json +__pycache__/ + +server/pool.json +server/pool.json.tmp diff --git a/FINDINGS.md b/FINDINGS.md new file mode 100644 index 0000000..1083802 --- /dev/null +++ b/FINDINGS.md @@ -0,0 +1,106 @@ +# Session log 2026-09-30 (evening) — full attack surface matrix + +| Path | Status | Proof | +|---|---|---| +| mail.tm + agent-signup API (browserless) | **WORKS** | `client/acct.json` — account tt42i0vo@uberip.com, org reform-org, live refresh 200 | +| identity refresh (rotating rt) | **WORKS** | 200, assertion+rt rotated, saved | +| jwt-bearer exchange (no resource) | **WORKS** | 200 → access_token 818 chars, aud=client_id | +| jwt-bearer exchange (resource=api.type.com) | **BLOCKED** | 400 invalid_target — registration.scopes.post_claim=[] server-side | +| oRPC /api/orpc/* with any agent token | **BLOCKED** | 401 Invalid token — api requires aud=https://api.type.com (WorkOS user token) | +| Web signup UI + virtual passkey (CDP WebAuthn) | **BLOCKED** | 'Access blocked, please contact support' — anti-fraud (IP/среда), одинакого для uberip и gmail | +| Login existing user | **DEAD END** | passkey-only UI; email-code/password недоступны; passkey нельзя зарегистрировать | +| OAuth device flow (dynamic client) | **WORKS (pipeline)** | device_authorization 201, poll → authorization_pending — требует залогиненного юзера на /device | +| WorkOS direct authenticate (device grant) | **BLOCKED** | 400 invalid_client — dynamic client неизвестен api.workos.com | + +## Root cause + +Type выключил выдачу `api.read` scope для новых agent-регистраций: +`scopes.post_claim=[]` при `type=service_auth` для любого client_id/UA/заголовков. +Web UI принимает только WorkOS user token (localStorage `authToken` / +`workos:access-token`), получаемый через Google OAuth или passkey. +Passkey-создание через virtual authenticator (CDP WebAuthn) блокируется anti-fraud +с не-резидентного IP ('Access blocked, please contact support'). + +## Ключевые endpoints (проверено) + +- `POST https://auth.type.com/oauth2/register` — dynamic client (JSON, grant_types: device_code) → 201 +- `POST https://auth.type.com/oauth2/device_authorization` — client_id dyn → 200 (user_code, 900s) +- `POST https://auth.type.com/oauth2/token` grant_type=urn:ietf:params:oauth:grant-type:device_code — poll: authorization_pending → expired_token +- `POST https://auth.type.com/agent/identity` type=refresh → assertion + rotated rt +- `POST https://auth.type.com/oauth2/token` jwt-bearer без resource → 200 access_token (aud=client) +- WorkOS: `api.workos.com/user_management/authorize/device` + `/authenticate` — только для type_workos_client_id (в WorkOS registry) + +## Остающиеся векторы + +1. residential/mobile IP + живой Chrome (не headless) → Google OAuth путь (`/oauth` после gmail) → user token → oRPC +2. Найти org с включённым Authentication > Agents (api.read post_claim) — agent flow даст полный API токен +3. device-login из type_client.py с живым юзером (Google в реальном браузере, один клик Confirm) + +# Session log 2026-10-01 — глубокий реверс CLI-бинаря + device-claim flow + +## Новый реверс type-cli (linux-x64 Bun binary, strings dump) + +Полный auth-стек из `cli_strings.txt` (src/auth/agent-auth.ts + src/commands/auth.ts): + +1. **`type-cli auth login`** = WorkOS OAuth device flow: + - `POST https://api.workos.com/user_management/authorize/device` (client_id=`client_01K5GFDDKQWV8MM9FSRZS3YNNN`, БЕЗ client_secret — public) + - юзер подтверждает на `https://auth.type.com/device?user_code=XXXX` + - `POST https://api.workos.com/user_management/authenticate` grant=`urn:ietf:params:oauth:grant-type:device_code` (client_id+device_code) + - → tokens {access_token, refresh_token} (WorkOS user token — THE token, который принимает api.type.com) + - смена орги: `refreshAccessToken` с `organization_id` +2. **`type-cli signup`** = agent registration flow: + - `POST {serverUrl}/api/agent-signup/authkit` {claimAttemptToken, email, organizationName} + Bearer accessToken (WorkOS) + - → {claim: {token, attempt:{verification_uri}}, organization} + - `POST {issuer}/agent/identity/claim/complete` {claim_token, user_code} → identity {assertion, refresh_token} +3. **identity refresh**: `POST {issuer}/agent/identity` {refresh_token, type:"refresh"} — rt ОДНОРАЗОВЫЙ (rotation), оба наших потрачены +4. **oRPC-клиент**: `POST {serverUrl}/api/orpc` headers: `authorization: Bearer`, `user-agent: TypeCLI/{ver}`, `x-type-cli-version`, `x-type-trace-id` +5. **credential store**: `~/.type/credentials/{profile}.json` — kind=tokens, live у нас: default.json (ttqy41m2f8j@uberip.com, org reform-lab) + +## Живые пробы (сегодня) + +| Проба | Результат | +|---|---| +| device flow (client_01K5GFDDKQWV8MM9FSRZS3YNNN) на api.workos.com | **200** user_code=MQKW-GFBR, poll → authorization_pending (нужен юзер) | +| Google OAuth путь через auth.type.com/api/login | **redirect 307** → accounts.google.com → WorkOS Google SSO callback (живой) | +| Google login milansuvse380@gmail.com (gh-пул) | **Wrong password** — пароль сменён/мёртв | +| Google login lunamiaonlinenubaid@gmail.com | пароль принят → **reCAPTCHA Enterprise** challenge (sitekey 6LeyfJsrAAAAABWwSCCGzNb9d1fiBnrAd_hJuNyO, accounts.google.com) | +| YesCaptcha RecaptchaV2Enterprise solve | **SOLVED** (token 2638 chars, 5с, баланс 4639) — но Google вживую токен не принимает без JS-челленджа (инжект в v3 signin-flow невозможен, токен подаётся через их TL= протокол) | +| magic_auth send через api.workos.com напрямую | **401** — WorkOS API требует секрет/спецпуть; прошлый рег шёл через auth.type.com Next.js server actions | +| Existing user login (email→password) | passkey-only экран, пароль не задан, email-code недоступен | + +## Вывод + +Путь к **живому API-токену** = WorkOS device flow → юзер подтверждает в браузере (Google/Slack/passkey). +Google-block: рекапча на login с новых IP. Обход: residential IP + прогретый Google-акк, ИЛИ Slack-путь. +Agent-flow (assertion) математически закрыт: aud=client_id ≠ требуемого aud=api.type.com, resource-запрос → invalid_target. + +**Что работает и готово к автоскейлу:** +- mail.tm регистрация + agent-signup (аккаунты создаются) +- identity refresh + jwt-bearer exchange (токены живут, 300с) +- gateway :8311 + manager :8312 + dashboard (коммит 3d0a5e8e6) +- Pool management + POST /api/import-token (когда появится WorkOS-токен — шлюз подхватит) + + +## 2026-10-07: FINAL RADAR VERDICT (все варианты исчерпаны) + +Матрица попыток signup (все -> "Access blocked"): +| Browser | Email | IP | Результат | +|---|---|---|---| +| patchright Chromium | mail.tm | home | blocked | +| Camoufox | Voidash eu.cc | home | blocked (password step) | +| Camoufox | Voidash | DC proxy x N | blocked | +| Camoufox | Voidash | residential socks5 | browser не резолвит | +| REAL Chrome 154 (CDP :9223) | Voidash govno.eu.cc | home | blocked (password + email-code) | +| REAL Chrome | existing acct tt42i0vo@uberip.com signin | home | blocked | + +Вывод: WorkOS Radar флагнул ДОМЕН-IP (178.x home) на уровне репутации — +блок срабатывает даже для человеческого браузера на этом IP. +- Email-code signup protocol: HTTP 410 (отключён сервером) +- Google SSO: chooser пуст (нет Google-акков в профиле Chrome) +- Pool tokens: истекли, refresh_token already used +- reforrm.me MX = Namecheap eforward (письма теряются, catch-all нет) +- Workspace Gmail delegation: access_denied (SA не авторизован для gmail.readonly) + +Единственные рабочие пути: +1. Ручной signup ОДИН РАЗ с чистого IP (мобильный интернет телефона / VPN / резидентный прокси) -> токен в pool.json -> шлюз живёт на refresh. +2. Paid residential/mobile proxy с чистой репутацией (BrightData/IPRoyal ~$2-5/GB). diff --git a/README.md b/README.md new file mode 100644 index 0000000..2b3eeda --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# type-toolkit + +Full reverse-engineering + automation stack for **type.com** (TypeCLI): + +1. **`client/`** — protocol reverse: browserless signup, token exchange, identity refresh, device-login, and an **OpenAI-compatible API gateway** (`type2api.py`, port 8311). +2. **`autoreg/`** — GitHub/GitLab/Codeberg auto-registration framework (Camoufox-based), proxy rotation, PAT harvesting, mass account checking. + +## client/ — type.com protocol + +``` +python client/type_client.py signup --email # 7-HTTP-request browserless registration +python client/type_client.py device-login --email # one human click -> user token +python client/type2api.py # OpenAI-compatible gateway :8311 +``` + +Key findings (live-probed): +- RFC 8414 discovery -> `auth.type.com` (issuer) + `api.type.com` (server) +- service_auth signup: `/api/agent-signup/start` -> email code -> verify -> claim/complete -> JWT bearer exchange +- **exchange trap**: assertion `aud`=issuer; sending `resource` returns 400 invalid_target — omit it +- refresh_token arrives as `{value, expires_at}` — send `.value` +- oRPC layer: `POST {server}/api/orpc/` with `Authorization`/`TypeCLI` UA headers +- anti-farm: 429 on `/agent/identity` (IP-based, 3600s), AuthKit blocks disposable domains, Google blocks CDP browsers + +## autoreg/ — account farming framework + +``` +autoreg/gh_autoreg.py [ZTE|HK1024|HOME] [mailtm|gmail] # single GitHub account +autoreg/gh_pat.py # PAT harvesting (login -> /settings/tokens) +autoreg/fast_reg.py # farm loop with IP rotation +autoreg/cb_reg2.py # Codeberg reg (image-captcha via operator file) +autoreg/mass_check.py # bulk profile shadowban check +autoreg/png2ascii.py # pure-python PNG captcha decoder (no PIL) +``` + +Shadowban research (2026-09-30): accounts born via Camoufox autoreg are **instantly shadow-hidden** on GitHub (profile 404 for anonymous) regardless of email domain or IP; the flag triggers on the registration pattern itself. GitLab requires phone verification (step 2/2) + blocks gmail aliases. Codeberg uses a solvable image captcha. + +All credentials sanitized to placeholders — bring your own. diff --git a/USAGE.md b/USAGE.md new file mode 100644 index 0000000..1358f0f --- /dev/null +++ b/USAGE.md @@ -0,0 +1,66 @@ +# USAGE — agent guide + +Все компоненты stdlib-only (Python 3.11+), работают на Windows/Linux без зависимостей. + +## Быстрый старт + +```bash +# 1) Control-plane (авторег + пул + дашборд) — порт 8312 +python server/manager.py +# GET / dashboard +# GET /api/status {gateway, pool, log tail} +# GET /api/accounts пул (redacted, без токенов) +# POST /api/autoreg {"org": "reform-org"} -> регистрация 1 аккаунта (60-180s) +# POST /api/refresh refresh всех аккаунтов (identity refresh + jwt-bearer exchange) + +# 2) OpenAI-compatible gateway поверх пула — порт 8311 +python server/gateway.py +# GET /v1/models +# GET /health +# POST /v1/chat/completions + +# 3) Клиент протокола type.com +python client/type_client.py signup --email # browserless регистрация (7 HTTP-запросов) +python client/type_client.py device-login --email # 1 клик человека -> user token +python client/type2api.py # альтернативный gateway :8311 +``` + +## Авторег-фарм (GitHub/GitLab/Codeberg) + +```bash +python autoreg/gh_autoreg.py [ZTE|HK1024|HOME] [mailtm|gmail] # 1 GitHub-аккаунт (Camoufox) +python autoreg/gh_pat.py # PAT harvesting: login -> /settings/tokens +python autoreg/fast_reg.py # фарм-цикл с IP-ротацией (ZTE 4G) +python autoreg/cb_reg2.py # Codeberg (image captcha через operator-файл) +python autoreg/mass_check.py # bulk shadowban-проверка профилей +python autoreg/png2ascii.py # pure-python PNG-декодер капчи (без PIL) +python autoreg/gl_home_reg.py # GitLab (phone verify step 2/2) +``` + +## Флоу type.com signup (browserless, live-verified) + +1. `auth.type.com` RFC 8414 discovery -> issuer + `api.type.com` server +2. `POST /api/agent-signup/start` (service_auth) -> email code (mail.tm) +3. `POST /api/agent-signup/verify` -> `agent/identity/claim/complete` +4. `POST oauth2/token` grant_type=jwt-bearer -> access_token + +**Ловушки:** assertion `aud` = issuer; параметр `resource` -> 400 invalid_target (не слать); +refresh_token приходит как `{value, expires_at}` — слать `.value`; oRPC: +`POST {server}/api/orpc/` с заголовками `Authorization` + `TypeCLI/1.0.0` UA. + +## Анти-фарм лимиты + +- 429 на `/agent/identity` — IP-based, окно 3600s (нужна ротация IP: ZTE 4G / резидентные прокси) +- AuthKit блочит disposable email-домены +- Google OAuth блочит CDP-браузеры (используется Camoufox) +- GitHub: аккаунты с Camoufox-авторега мгновенно shadow-hidden (профиль 404 для анонимов) — паттерн регистрации палится, домен/IP ни при чём + +## Пул и секреты + +- `server/pool.json`, `client/acct.json`, `client/api_token.json` — локальные, gitignored (JWT/refresh токены) +- Свои креды: mail.tm аккаунт + прокси-пул (ZTE modem 192.168.0.1, IP ротация через DISCONNECT_NETWORK/CONNECT_NETWORK) + +## Известный статус upstream (2026-09-30) + +`api.type.com` отвечает 401 Invalid token на agent-токены (aud=client, server-side policy) — +gateway проксирует upstream-статус как есть. device-login (user token) работает. diff --git a/autoreg/cb_reg.py b/autoreg/cb_reg.py new file mode 100644 index 0000000..1a40570 --- /dev/null +++ b/autoreg/cb_reg.py @@ -0,0 +1,162 @@ +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +# Codeberg (Gitea) reg: HOME + mail.tm + API token via Basic Auth +import json +import random +import re +import string +import sys +import time +import urllib.request + +sys.path.insert(0, str(_REPO)) +from camoufox.sync_api import Camoufox +from gh_mail import MailTM + +SIGNUP_URL = "https://codeberg.org/user/sign_up" +API = "https://codeberg.org/api/v1" +OUT = str(_w("tmp/bpproxy_run")) + + +def log(m): + print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True) + + +mail = MailTM() +mb = mail.create() +if not mb: + log("FATAL: mailbox") + sys.exit(2) +addr, token = mb["address"], mb["token"] +log(f"mailbox: {addr}") + +username = "rev" + "".join(random.choices(string.ascii_lowercase, k=4)) + "".join(random.choices(string.digits, k=3)) +password = "Cb#" + "".join(random.choices(string.ascii_letters + string.digits, k=14)) + "!9" +log(f"account: {username}") + +result = {"status": "unknown", "username": username, "password": password, "email": addr} + +with Camoufox(headless=True, humanize=True) as browser: + page = browser.new_page() + page.goto(SIGNUP_URL, timeout=90000, wait_until="domcontentloaded") + time.sleep(3) + + # Gitea signup form: user_name, email, password, retype + fields = page.evaluate("(() => Array.from(document.querySelectorAll('input')).map(i => i.name + '|' + i.type + '|' + (i.id||'')).slice(0,12))()") + log(f"form fields: {fields}") + + def fill(sel, val): + try: + page.fill(sel, val, timeout=8000) + time.sleep(0.6) + return True + except Exception: + return False + + ok1 = fill("input[name=user_name]", username) + ok2 = fill("input[name=email]", addr) + ok3 = fill("input[name=password]", password) + ok4 = fill("input[name=retype]", password) + log(f"filled: name={ok1} email={ok2} pass={ok3} retype={ok4}") + + try: + page.click("button[type=submit], #submit", timeout=8000) + except Exception: + page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('button.green') || document.querySelector('button'); if (b) b.click(); })()") + time.sleep(8) + + st = page.evaluate("(() => ({url: location.href, body: document.body.innerText.slice(0,600)}))()") + log(f"after submit: {st['url'][:90]}") + log("BODY: " + st["body"][:400].replace("\n", " | ")) + + # verification code flow? + needs_code = bool(re.search(r"verification code|confirm|activate", st["body"], re.I)) or "activate" in st["url"] + code_el = page.evaluate("(() => !!document.querySelector('input[name*=code i], input[id*=code i], input[inputmode=numeric]'))()") + if needs_code or code_el: + log("email-code flow detected") + code = mail.wait_code(token, sender_hint="codeberg", timeout_sec=300) + log(f"code: {code}") + if code: + page.evaluate("""(code) => { + const cands = ['input[name*=code i]','input[id*=code i]','input[autocomplete=one-time-code]','input[inputmode=numeric]']; + let el = null; + for (const c of cands) { el = document.querySelector(c); if (el) break; } + if (!el) return; + el.focus(); el.value = code; + el.dispatchEvent(new Event('input', {bubbles:true})); + }""", code) + time.sleep(1.2) + page.evaluate("(() => { const b = document.querySelector('button[type=submit]'); if (b) b.click(); })()") + time.sleep(8) + st = page.evaluate("(() => ({url: location.href, body: document.body.innerText.slice(0,500)}))()") + log(f"after code: {st['url'][:90]}") + log("BODY: " + st["body"][:350].replace("\n", " | ")) + + result["final_url"] = st["url"][:200] + result["body"] = st["body"][:300] + page.screenshot(path=OUT + r"\cb_state.png") + +# --- API token via Basic Auth (works only if account activated) --- +import base64 + +def api(method, path, data=None, auth=True): + h = {"Content-Type": "application/json"} + if auth: + cred = base64.b64encode(f"{username}:{password}".encode()).decode() + h["Authorization"] = "Basic " + cred + req = urllib.request.Request( + API + path, + data=json.dumps(data).encode() if data else None, + headers=h, + method=method, + ) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.load(r) + except urllib.error.HTTPError as e: + try: + return e.code, json.load(e) + except Exception: + return e.code, {} + except Exception as e: + return 0, {"err": str(e)[:80]} + +stc, me = api("GET", "/user") +log(f"API /user: {stc} -> {str(me)[:120]}") +if stc == 200: + stt, tok = api("POST", f"/users/{username}/tokens", {"name": "push", "scopes": ["write:repository", "read:user"]}) + log(f"API token: {stt} -> {str(tok)[:120]}") + result["status"] = "OK" + result["pat"] = tok.get("sha1") + print(json.dumps(result)) +else: + result["status"] = "pending_activation" + print(json.dumps(result)) diff --git a/autoreg/cb_reg2.py b/autoreg/cb_reg2.py new file mode 100644 index 0000000..eb1422b --- /dev/null +++ b/autoreg/cb_reg2.py @@ -0,0 +1,170 @@ +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +# Codeberg reg v2: image-captcha solved by operator (poll answer file) +import json +import random +import string +import sys +import time +import base64 +import os +import re +import urllib.request +import urllib.error + +sys.path.insert(0, str(_REPO)) +from camoufox.sync_api import Camoufox +from gh_mail import MailTM + +OUT = str(_w("tmp/bpproxy_run")) +CAP = OUT + r"\cb_captcha.png" +ANS = OUT + r"\cb_answer.txt" +SIGNUP_URL = "https://codeberg.org/user/sign_up" +API = "https://codeberg.org/api/v1" + + +def log(m): + print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True) + + +for f in (ANS,): + if os.path.exists(f): + os.remove(f) + +mail = MailTM() +mb = mail.create() +addr, token = mb["address"], mb["token"] +log(f"mailbox: {addr}") + +username = "dev" + "".join(random.choices(string.ascii_lowercase, k=5)) + "".join(random.choices(string.digits, k=3)) +password = "Cb#" + "".join(random.choices(string.ascii_letters + string.digits, k=14)) + "!9" +log(f"account: {username}") + +result = {"username": username, "password": password, "email": addr} + +with Camoufox(headless=True, humanize=True) as browser: + page = browser.new_page() + page.goto(SIGNUP_URL, timeout=90000, wait_until="domcontentloaded") + time.sleep(3) + + page.fill("input[name=user_name]", username) + page.fill("input[name=email]", addr) + page.fill("input[name=password]", password) + page.fill("input[name=retype]", password) + time.sleep(1) + + # screenshot the captcha image + try: + img = page.locator("img.captcha, img#captcha-img, img[src*=captcha]").first + img.wait_for(state="visible", timeout=10000) + img.screenshot(path=CAP) + log("captcha screenshot saved -> cb_captcha.png") + except Exception: + page.screenshot(path=CAP) + log("captcha element not found; full page saved") + + # wait for operator answer + log("waiting operator answer (cb_answer.txt)...") + answer = None + for _ in range(90): + if os.path.exists(ANS): + answer = open(ANS).read().strip() + if answer: + break + time.sleep(4) + log(f"captcha answer: {answer!r}") + if not answer: + log("FATAL: no operator answer") + sys.exit(3) + + page.fill("input[name=img-captcha-response]", answer) + time.sleep(0.8) + try: + page.click("button[type=submit]", timeout=8000) + except Exception: + page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('button'); if (b) b.click(); })()") + time.sleep(8) + + st = page.evaluate("() => ({url: location.href, body: document.body.innerText.slice(0,500)})()") + log(f"after submit: {st['url'][:90]}") + log("BODY: " + st["body"][:350].replace("\n", " | ")) + page.screenshot(path=OUT + r"\cb_state2.png") + result["after_submit"] = st["body"][:200] + + # email code? + code_el = page.evaluate("() => !!document.querySelector('input[name*=code i], input[id*=code i]')") + if code_el or "verification" in st["body"].lower(): + log("email-code flow") + code = mail.wait_code(token, sender_hint="codeberg", timeout_sec=300) + log(f"code: {code}") + if code: + page.evaluate("""(code) => { + const cands = ['input[name*=code i]','input[id*=code i]','input[autocomplete=one-time-code]']; + let el = null; + for (const c of cands) { el = document.querySelector(c); if (el) break; } + if (!el) return; + el.focus(); el.value = code; + el.dispatchEvent(new Event('input', {bubbles:true})); + }""", code) + time.sleep(1) + page.evaluate("(() => { const b = document.querySelector('button[type=submit]'); if (b) b.click(); })()") + time.sleep(8) + st = page.evaluate("() => ({url: location.href, body: document.body.innerText.slice(0,400)})()") + log("AFTER CODE: " + st["body"][:300].replace("\n", " | ")) + result["after_code"] = st["body"][:200] + +# API token via Basic Auth +def api(method, path, data=None): + cred = base64.b64encode(f"{username}:{password}".encode()).decode() + req = urllib.request.Request( + API + path, + data=json.dumps(data).encode() if data else None, + headers={"Content-Type": "application/json", "Authorization": "Basic " + cred}, + method=method, + ) + try: + with urllib.request.urlopen(req, timeout=30) as r: + return r.status, json.load(r) + except urllib.error.HTTPError as e: + try: + return e.code, json.load(e) + except Exception: + return e.code, {} + +stc, me = api("GET", "/user") +log(f"API /user: {stc} -> {str(me)[:140]}") +result["api_user"] = stc +if stc == 200: + stt, tok = api("POST", f"/users/{username}/tokens", {"name": "push1", "scopes": ["write:repository", "read:user"]}) + log(f"token: {stt} -> {str(tok)[:100]}") + if stt == 201: + result["pat"] = tok.get("sha1") +print(json.dumps(result)) diff --git a/autoreg/fast_reg.py b/autoreg/fast_reg.py new file mode 100644 index 0000000..594c37b --- /dev/null +++ b/autoreg/fast_reg.py @@ -0,0 +1,140 @@ +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +# FAST registration worker: tight loop, rotate IP every 3 accounts, no long pauses +import subprocess, time, sqlite3, sys + +PY = _PY +OUT = str(_w("tmp/bpproxy_run")) +DB = OUT + r"\accounts.db" +LOG = open(OUT + r"\fast_reg.log", "a", encoding="utf-8") + +TARGET = int(sys.argv[1]) if len(sys.argv) > 1 else 1000 +PER_IP = 3 + + +def log(m): + print(m, flush=True) + LOG.write(m + "\n") + LOG.flush() + + +def ok_count(): + db = sqlite3.connect(DB) + n = db.execute("SELECT COUNT(*) FROM accounts WHERE status='OK_VERIFIED'").fetchone()[0] + db.close() + return n + + +def run(cmd, timeout): + try: + r = subprocess.run([PY, "-u"] + cmd, cwd=OUT, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout or "") + (r.stderr or "") + except subprocess.TimeoutExpired: + return 99, "timeout" + + +idx = 400 +made_on_ip = PER_IP # rotate immediately on start +consecutive_ft = 0 + + +def relay_alive(): + import socket as sk + try: + s = sk.create_connection(("127.0.0.1", 8899), timeout=3) + s.close() + return True + except OSError: + return False + + +def heal_relay(): + import subprocess as sp + try: + sp.Popen([PY, "zte_relay.py"], cwd=str(_d("tmp")), + creationflags=0x00000008) # DETACHED_PROCESS, no wait + log("relay healed (restarted)") + except Exception as e: + log(f"relay heal failed: {e}") + + +while True: + if not relay_alive(): + log("relay dead (proactive probe) — healing") + heal_relay() + time.sleep(5) + ok = ok_count() + if ok >= TARGET: + log(f"TARGET {TARGET} reached (ok={ok})") + break + # rotate every PER_IP accounts + if made_on_ip >= PER_IP: + # wait for warm worker to finish its browser session (modem disconnect kills it) + import os, glob + for _ in range(60): + flags = glob.glob(OUT + r"\warm_busy_*.flag") + if not flags: + break + # stale flag cleanup (crashed warm worker) + for f in flags: + try: + if time.time() - os.path.getmtime(f) > 1200: + os.remove(f) + log("removed stale warm flag") + except OSError: + pass + time.sleep(3) + + try: + subprocess.run([PY, "-u", "zte_ui_rotate2.py"], cwd=OUT, capture_output=True, timeout=300) + log("rotated IP") + except Exception: + log("rotate failed — continuing on current IP") + made_on_ip = 0 + idx += 1 + t0 = time.time() + rc, out = run(["gh_autoreg.py", str(idx).zfill(3), "ZTE", "gmail"], 700) + dt = time.time() - t0 + if "OK_VERIFIED" in out: + made_on_ip += 1 + consecutive_ft = 0 + log(f"reg #{idx}: OK ({dt:.0f}s) ok_total={ok + 1}") + time.sleep(20) + else: + reason = "timeout" if rc == 99 else ("FORM_TIMEOUT" if "FORM_TIMEOUT" in out else "fail") + log(f"reg #{idx}: {reason} ({dt:.0f}s)") + if reason == "FORM_TIMEOUT": + consecutive_ft += 1 + if consecutive_ft >= 3: + heal_relay() + consecutive_ft = 0 + time.sleep(8) + made_on_ip += 2 # fails burn the IP budget 2x faster -> rotate sooner \ No newline at end of file diff --git a/autoreg/gh_autoreg.py b/autoreg/gh_autoreg.py new file mode 100644 index 0000000..cb1e856 --- /dev/null +++ b/autoreg/gh_autoreg.py @@ -0,0 +1,655 @@ +# -*- coding: utf-8 -*- +"""GitHub account autoregister 2026 (v3). +2026 form = single page: #email, #password, #login + country + one submit. +Flow: mailbox -> /signup (wait DataDome; drag slider if shown) -> reject cookies -> +fill all fields -> submit (form button[type=submit] only) -> mail code -> verify -> save. +Usage: python gh_autoreg.py IDX [proxy_label|HOME] [mailtm|gmail] +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import time, json, re, random, string, sys, os +from camoufox.sync_api import Camoufox + +sys.path.insert(0, str(_REPO)) +from gh_mail import MailTM, GmailIMAP + +OUT = str(_w("tmp/bpproxy_run")) +ACCOUNTS = OUT + r"\github_accounts.jsonl" +LOG = OUT + r"\gh_autoreg.log" + +IDX = (sys.argv[1] if len(sys.argv) > 1 else str(random.randint(1, 999))).zfill(3) +PROXY_LABEL = sys.argv[2] if len(sys.argv) > 2 else "HOME" +MAIL_MODE = sys.argv[3] if len(sys.argv) > 3 else "mailtm" + +P_USER = "bpproxy-user" +P_PASS = "BPPROXY_PASS" +P_HOST = "bpproxy-host:1000" +DEBUG_SHOTS = os.path.isdir(str(_w("tmp/bpproxy_run/shots"))) +CAPTCHA_WAIT = 160 + +gmail = GmailIMAP() + +# ---- TG push: instant creds delivery ---- +TG_BOT = {"bot_token": "TG_BOT_TOKEN"} +TG_BACKUP = {"chat_id": "TG_CHAT_ID", "thread": "350384", + "token_alt": "7189316701"} +TG_CHATID_FILE = OUT + r"\gh_bot_chatid.txt" + + +def tg_request(token, method, params, timeout=25): + try: + req = __import__("urllib").request.Request( + "https://api.telegram.org/bot%s/%s" % (token, method), + data=__import__("urllib").parse.urlencode(params).encode()) + with __import__("urllib").request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + except Exception: + return {"ok": False} + + +def tg_chat_id(): + try: + with open(TG_CHATID_FILE) as f: + v = f.read().strip() + if v: + return v + except Exception: + pass + try: + upd = tg_request(TG_BOT["bot_token"], "getUpdates", + {"limit": 5, "timeout": 1}) + for u in upd.get("result", []): + ch = u.get("message", {}).get("chat", {}).get("id") + if ch: + open(TG_CHATID_FILE, "w").write(str(ch)) + return str(ch) + except Exception: + pass + return None + + +def tg_push_creds(email, username, password): + msg = ("GitHub OK!\nemail: %s\nusername: %s\npassword: %s" % + (email, username, password)) + cid = tg_chat_id() + if cid: + r = tg_request(TG_BOT["bot_token"], "sendMessage", + {"chat_id": cid, "text": msg}) + if r.get("ok"): + log("TG pushed to Hermetik chat " + cid) + return True + try: + tok = re.search(r"[0-9]{10}:[A-Za-z0-9_-]{30,}", + open((_pos.environ.get("HERMES_CONFIG","")), + encoding="utf-8").read()).group(1) + except Exception: + tok = None + if tok: + r = tg_request(tok, "sendMessage", + {"chat_id": TG_BACKUP["chat_id"], + "message_thread_id": TG_BACKUP["thread"], + "text": msg}) + if r.get("ok"): + log("TG pushed to backup chat") + else: + log("TG push failed: no token") + # last-resort fallback: Telethon R3fIex -> reformboss DM + try: + import subprocess + rc = subprocess.run( + [_PY, OUT + "\tg_push_r3f.py", msg], + capture_output=True, text=True, timeout=60) + if rc.returncode == 0: + log("TG pushed via R3fIex DM") + else: + log("R3fIex push rc=%d %s" % (rc.returncode, rc.stdout[-120:])) + except Exception as e: + log("R3fIex push EXC: " + str(e)[:120]) + +def log(m): + line = f"[{time.strftime('%H:%M:%S')}] [{IDX}] {m}" + print(line, flush=True) + with open(LOG, "a", encoding="utf-8") as f: + f.write(line + "\n") + +def save(rec): + rec = {"idx": IDX, "ts": time.strftime("%Y-%m-%d %H:%M:%S"), **rec} + with open(ACCOUNTS, "a", encoding="utf-8") as f: + f.write(json.dumps(rec, ensure_ascii=False) + "\n") + log("SAVED: " + json.dumps(rec, ensure_ascii=False)[:240]) + try: + import gh_db + db_rec = {k: v for k, v in rec.items() if k in gh_db.VALID_COLS} + if "ts" in rec and "created_ts" not in db_rec: + db_rec["created_ts"] = rec["ts"] + if "body" in rec or set(rec) - set(gh_db.VALID_COLS): + extra = {k: v for k, v in rec.items() if k not in gh_db.VALID_COLS} + if extra: + db_rec["notes"] = json.dumps(extra, ensure_ascii=False)[:2000] + gh_db.upsert_account(db_rec) + log("DB saved") + except Exception as e: + log("DB save EXC: " + str(e)[:150]) + if rec.get("status") == "OK_VERIFIED": + try: + tg_push_creds(rec.get("email", ""), rec.get("username", ""), + rec.get("password", "")) + except Exception as e: + log("tg_push EXC: " + str(e)[:150]) + +def proxy_cfg(): + if PROXY_LABEL == "SOCKSH": + return {"server": "socks5://127.0.0.1:2090"} + if PROXY_LABEL == "ZTE": + return {"server": "http://127.0.0.1:8899"} + if PROXY_LABEL == "HK1024": + # 1024proxy HK mobile sticky: rotate over verified-clean sids + import random as _r + try: + pool = [88291] + [int(x) for x in open(str(_w("tmp/bpproxy_run/clean_sids.txt"))).read().split() if x.strip()] + except Exception: + pool = [88291] + sid = _r.choice(pool) + return {"server": "http://hk.1024proxy.io:3000", + "username": f"PROXY_USER-region-HK-sid-{sid}-t-30", + "password": "PROXY_PASS"} + if PROXY_LABEL == "ZTE": + return {"server": "http://127.0.0.1:8899"} + return {"server": f"http://{P_HOST}", "username": P_USER, + "password": f"{P_PASS}_session-{PROXY_LABEL}_lifetime-30"} + +def gen_pass(): + return "Gh#" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "@9x" + +def gen_username(): + adj = ["neon", "crimson", "violet", "silver", "arctic", "lunar", "cobalt", "amber", "steel", "ember"] + noun = ["dev", "lab", "forge", "stack", "grid", "byte", "flux", "chip", "logic", "node"] + return (random.choice(adj) + random.choice(noun) + "".join(random.choices(string.digits, k=3)))[:28].lower() + +def ev(page, js): + try: + return page.evaluate(js) + except Exception: + return None + +def try_drag_slider(page): + for fr in page.frames: + try: + u = fr.url or "" + except Exception: + continue + if "captcha" not in u: + continue + try: + info = fr.evaluate("""(() => { + const out = []; + document.querySelectorAll('button,input,div[id],div[class]').forEach(e => { + if (out.length > 40) return; + const r = e.getBoundingClientRect(); + const blob = ((e.id||'')+' '+((e.className||'')).toString()).toLowerCase(); + if (r.width>8 && r.height>8 && /slider|drag|handle|captcha|button/i.test(blob)) + out.push({tag:e.tagName, id:e.id||'', cls:(e.className||'').toString().slice(0,50), + x:Math.round(r.x), y:Math.round(r.y), w:Math.round(r.width), h:Math.round(r.height)}); + }); + return out; + })()""") + except Exception: + continue + target = None + for e in info: + blob = (e["id"] + " " + e["cls"]).lower() + if ("slider" in blob or "drag" in blob or "handle" in blob) and e["w"] < 100: + target = e + break + if not target: + continue + try: + fb = page.evaluate("""(() => { + const f = Array.from(document.querySelectorAll('iframe')).find(f => f.src.includes('captcha')); + if (!f) return null; const r = f.getBoundingClientRect(); + return {x:r.x, y:r.y, w:r.width, h:r.height}; + })()""") + if not fb: + return False + iw = fr.evaluate("document.documentElement.clientWidth") or fb["w"] or 1 + scale = fb["w"] / max(iw, 1) + ax = fb["x"] + (target["x"] + target["w"] / 2) * scale + ay = fb["y"] + (target["y"] + target["h"] / 2) * scale + endx = fb["x"] + fb["w"] - 30 + except Exception: + continue + rng = random.Random() + log(f"SLIDER drag {round(ax)}->{round(endx)}") + page.mouse.move(ax, ay) + time.sleep(0.35 + rng.random() * 0.3) + page.mouse.down() + time.sleep(0.3) + steps = rng.randint(26, 36) + for i in range(steps): + f_ = (i + 1) / steps + page.mouse.move(ax + (endx - ax) * f_, ay + rng.uniform(-3, 3)) + time.sleep(rng.uniform(0.012, 0.036)) + page.mouse.move(endx, ay + rng.uniform(-2, 2)) + time.sleep(0.2) + page.mouse.up() + log("SLIDER dragged") + return True + return False + + +# ---- DataDome trust-cookie carry-over (ported from regkit) ---- +_TRUST_FILE = OUT + r"\.datadome-trust.json" +_TRUST_NAMES = {"datadome", "datadome_proxied", "device_id", "_device_id"} +_cur_exit_ip = None + + +def _exit_ip(): + global _cur_exit_ip + if _cur_exit_ip: + return _cur_exit_ip + import requests + try: + server = (proxy_cfg() or {}).get("server", "http://127.0.0.1:8899") + px = {"http": server, "https": server} + _cur_exit_ip = requests.get("https://api.ipify.org", proxies=px, timeout=10).text.strip() + except Exception: + _cur_exit_ip = "" + return _cur_exit_ip + + +def dd_save_trust(context): + import json as _j + try: + keep = [c for c in context.cookies() + if c.get("name") in _TRUST_NAMES and c.get("domain", "").endswith("github.com")] + if not keep: + return + open(_TRUST_FILE, "w").write(_j.dumps({"cookies": keep, "exit_ip": _exit_ip()})) + log(f"dd trust saved ({len(keep)} cookies, ip={_cur_exit_ip})") + except Exception as e: + log(f"trust save err {str(e)[:60]}") + + +def dd_restore_trust(context): + import json as _j, os + try: + if not os.path.exists(_TRUST_FILE): + return + data = _j.loads(open(_TRUST_FILE).read()) + bound_ip = data.get("exit_ip") or "" + cur = _exit_ip() + if bound_ip and cur and bound_ip != cur: + log(f"trust skip (bound {bound_ip} != cur {cur})") + return + if not cur: + return + clean = [] + for c in data.get("cookies") or []: + cc = {k: c[k] for k in ("name", "value", "domain", "path", + "expires", "httpOnly", "secure", "sameSite") if k in c} + cc.setdefault("domain", ".github.com") + cc.setdefault("path", "/") + cc.setdefault("secure", True) + cc.setdefault("httpOnly", False) + clean.append(cc) + context.add_cookies(clean) + log(f"dd trust restored ({len(clean)})") + except Exception as e: + log(f"trust restore err {str(e)[:60]}") + + +def is_hard_block(page): + t = (body_text(page) or "").lower() + return "access is temporarily restricted" in t or "too many requests" in t + + +def open_signup(page): + deadline = time.time() + CAPTCHA_WAIT + last_drag = 0 + first_pass = True + while time.time() < deadline: + try: + if first_pass: + # referral entry (regkit): arrive like a search-result visitor + try: + page.goto("https://github.com/?utm_source=google", timeout=60000, + wait_until="domcontentloaded") + ev(page, """(() => { const a = Array.from(document.querySelectorAll('a')) + .find(x => (x.innerText||'').trim() === 'Sign up'); if (a) { a.click(); return true; } return false; })()""") + time.sleep(3) + except Exception: + page.goto("https://github.com/signup", timeout=60000, wait_until="domcontentloaded") + first_pass = False + else: + page.goto("https://github.com/signup", timeout=60000, wait_until="domcontentloaded") + except Exception as e: + log(f"nav err {str(e)[:60]}") + time.sleep(5) + continue + t0 = time.time() + last_reload = time.time() + while time.time() < deadline: + if is_hard_block(page): + log("HARD BLOCK detected — aborting early") + return False + st = ev(page, "(() => ({email: !!(document.querySelector('input#email') && document.querySelector('input#email').offsetParent), captcha: !!document.querySelector('iframe[src*=captcha]')}))()") + if st["email"]: + log(f"FORM VISIBLE after ~{int(time.time()-t0)}s") + return True + if st["captcha"] and time.time() - last_drag > 8: + if try_drag_slider(page): + last_drag = time.time() + time.sleep(6) + if time.time() - last_reload > 25: + log("stale challenge, reloading") + try: + page.goto("https://github.com/signup", timeout=60000, wait_until="domcontentloaded") + except Exception: + pass + last_reload = time.time() + time.sleep(4) + return False + +def dismiss_cookies(page): + ev(page, """(() => { + let b = document.querySelector('button[data-testid=cookie-banner-accept], #ghcc button, .cookie-banner button, button[data-accept-cookie], button[data-consent-accept]'); + if (!b) b = Array.from(document.querySelectorAll('button')).find(x => /^(Accept|Reject|Accept all|Allow all|Agree)( all| cookies)?$/i.test((x.innerText||'').trim())); + if (b) { b.click(); } + setTimeout(() => { const c = document.querySelector('ghcc-consent'); if (c) c.remove(); }, 500); + return b ? 'dismissed' : 'none'; + })()""") + +def setf(page, sel, val): + s = json.dumps(sel) + v = json.dumps(val) + return ev(page, f"""(() => {{ + const el = document.querySelector({s}); + if (!el) return 'NO_EL'; + el.focus(); el.value = {v}; + el.dispatchEvent(new Event('input', {{bubbles:true}})); + el.dispatchEvent(new Event('change', {{bubbles:true}})); + el.dispatchEvent(new Event('blur', {{bubbles:true}})); + return el.value === {v} ? 'OK' : 'MISMATCH:' + el.value; + }})()""") + + +def human_sleep(base=1.0, spread=0.6): + """Human-ish pause: base +- spread, occasionally a longer 'distraction'.""" + t = random.uniform(base - spread, base + spread) + if random.random() < 0.08: # rare distraction pause + t += random.uniform(2.0, 5.0) + time.sleep(max(0.2, t)) + + +def human_type(page, sel, text, click_first=True, allow_typo=False): + """Type like a person: click into field, variable per-char delays. + allow_typo=True adds rare typo+backspace-fix (use only for usernames/bios, + NEVER for email/password — a half-fixed typo corrupts creds).""" + loc = page.locator(sel) + if click_first: + box = loc.bounding_box() + if box: + page.mouse.move(box["x"] + box["width"] * random.uniform(0.3, 0.7), + box["y"] + box["height"] * random.uniform(0.3, 0.7), + steps=random.randint(8, 18)) + human_sleep(0.4, 0.3) + loc.click() + human_sleep(0.3, 0.2) + # rare typo: swap two adjacent chars, then fix with backspaces + typo_idx = None + if allow_typo and len(text) > 4 and random.random() < 0.18: + typo_idx = random.randint(1, len(text) - 2) + broken = text[:typo_idx] + text[typo_idx + 1] + text[typo_idx] + text[typo_idx + 2:] + else: + broken = text + typed = "" + for ch_i, ch in enumerate(broken): + page.keyboard.type(ch, delay=0) + typed += ch + # per-char variable delay + d = random.uniform(0.05, 0.16) + if ch in "@.#-_!": # shifted keys take longer + d += random.uniform(0.05, 0.12) + if random.random() < 0.04: # micro-think + d += random.uniform(0.3, 0.9) + time.sleep(d) + if typo_idx is not None: + time.sleep(random.uniform(0.3, 0.8)) # notice the typo + page.keyboard.press("Backspace") + time.sleep(random.uniform(0.08, 0.2)) + page.keyboard.press("Backspace") + time.sleep(random.uniform(0.15, 0.4)) + for ch in (text[typo_idx], text[typo_idx + 1]): + page.keyboard.type(ch, delay=0) + time.sleep(random.uniform(0.06, 0.15)) + return typed + + +def human_scroll(page, direction="down", n=None): + """Scroll like a reader: several wheel steps with pauses, sometimes up a bit.""" + n = n or random.randint(2, 5) + dy = random.randint(180, 420) * (1 if direction == "down" else -1) + for _ in range(n): + page.mouse.wheel(0, dy + random.randint(-60, 60)) + time.sleep(random.uniform(0.2, 0.7)) + if random.random() < 0.25: # scroll back up to check something + page.mouse.wheel(0, -random.randint(100, 300)) + time.sleep(random.uniform(0.3, 0.8)) + + +def human_move_mouse(page, target_box=None): + """Idle-ish mouse drift to a random spot or near a target box.""" + if target_box: + x = target_box["x"] + random.uniform(0.1, 0.9) * target_box["width"] + y = target_box["y"] + random.uniform(0.1, 0.9) * target_box["height"] + else: + x = random.uniform(120, 900) + y = random.uniform(120, 700) + page.mouse.move(x, y, steps=random.randint(10, 25)) + time.sleep(random.uniform(0.1, 0.4)) + +def submit_form(page): + """Click the primary Create account button; SSO buttons excluded.""" + return ev(page, """(() => { + const bs = Array.from(document.querySelectorAll('button')); + let b = bs.find(x => { + const t = (x.innerText||'').trim(); + return !x.disabled && x.offsetParent && /^Create account/i.test(t) && !/google|apple|continue with/i.test(t); + }); + if (b) { b.click(); return 'create_account'; } + const f = document.querySelector('form[action*=signup]'); + if (f) { + const s = f.querySelector('button[type=submit]'); + if (s && !/google|apple|continue with/i.test((s.innerText||''))) { s.click(); return 'signup_form_submit'; } + } + return 'NONE'; + })()""") + +def body_text(page): + try: + return ev(page, "document.body.innerText.slice(0,500)").replace("\n", " | ") + except Exception: + return "?" + +def main(): + email = None + mailtm_box = None + if MAIL_MODE == "mailtm": + try: + mailtm_box = MailTM().create() + email = mailtm_box["address"] + log(f"mailbox: {email}") + except Exception as e: + log(f"mailtm failed ({str(e)[:100]}) -> gmail fallback") + mailtm_box = None + if not email: + email = gmail.make_address() + log(f"mailbox(gmail): {email}") + username = gen_username() + password = gen_pass() + cfg = None if PROXY_LABEL == "HOME" else proxy_cfg() + attempt_label = PROXY_LABEL + for browser_try in range(3): + if browser_try > 0 and PROXY_LABEL not in ("HOME", "SOCKSH", "HK1024", "ZTE"): + attempt_label = (("ghrt" + IDX + "x" * browser_try))[:15] + cfg = {"server": f"http://{P_HOST}", "username": P_USER, + "password": f"{P_PASS}_session-{attempt_label}_lifetime-30"} + log(f"browser retry #{browser_try} new sticky label={attempt_label}") + elif browser_try > 0: + cfg = None if PROXY_LABEL == "HOME" else proxy_cfg() + log(f"browser retry #{browser_try} fresh {PROXY_LABEL} session") + try: + with Camoufox(proxy=cfg, headless=True, humanize=True, geoip=True) as browser: + page = browser.new_page() + dd_restore_trust(page.context) + if not open_signup(page): + save({"status": "FORM_TIMEOUT", "email": email, "username": username, "password": password}) + return 2 + time.sleep(random.uniform(2.5, 4.5)) # look at the page first + dismiss_cookies(page) + human_move_mouse(page) # idle drift + human_sleep(1.5, 0.8) + + # type like a human: email -> pause -> password -> pause -> username + human_type(page, "#email", email) + human_sleep(1.4, 0.7) + human_move_mouse(page) + human_type(page, "#password", password) + human_sleep(1.1, 0.5) + human_type(page, "#login", username, allow_typo=True) + # 'review' the form: small scroll + re-read + human_sleep(1.8, 0.9) + human_move_mouse(page) + human_sleep(0.9, 0.5) + if DEBUG_SHOTS: + page.screenshot(path=OUT + f"\\gh_a{IDX}_1filled.png") + + sub = submit_form(page) + log("submit: " + sub) + time.sleep(12) + st = ev(page, "(() => ({url: location.href, body: document.body.innerText.slice(0,500)}))()") or {} + st.setdefault("body", "") + st.setdefault("url", "") + st["body"] = (st["body"] or "").replace("\n", " | ") + log("after submit: url=" + st["url"][:120]) + log("BODY: " + st["body"][:400]) + if DEBUG_SHOTS: + page.screenshot(path=OUT + f"\\gh_a{IDX}_4submit.png") + + if "accounts.google.com" in st["url"] or "apple" in st["url"]: + save({"status": "SSO_REDIRECT", "email": email, "username": username, "password": password, "url": st["url"]}) + return 7 + if "captcha" in st["url"].lower() or "arkose" in st["body"].lower() or "challenge" in st["url"].lower(): + save({"status": "CHALLENGE_ON_SUBMIT", "email": email, "username": username, "password": password, "url": st["url"]}) + return 5 + + code_screen = False + for _ in range(12): + time.sleep(4) + s2 = ev(page, "(() => ({url: location.href, inputsN: document.querySelectorAll('input').length}))()") or {} + log(f"wait code: url={str(s2.get('url',''))[:90]} inputs={s2.get('inputsN')}") + if "account_verifications" in str(s2.get("url", "")).lower(): + code_screen = True + break + if not code_screen: + save({"status": "NO_CODE_SCREEN", "email": email, "username": username, "password": password, + "url": (page.url or "")[:160]}) + return 4 + code = None + if mailtm_box: + code, _ = MailTM().wait_code(mailtm_box["token"], timeout_sec=260) + if not code: + code = gmail.wait_code(email, timeout_sec=260) + if not code: + save({"status": "NO_MAIL", "email": email, "username": username, "password": password}) + return 6 + log(f"code={code}") + + c = json.dumps(code) + filled = ev(page, f"""(() => {{ + const ins = Array.from(document.querySelectorAll('input[inputmode=numeric], input[autocomplete=one-time-code], input[name*=code i], input[id*=code i]')); + if (!ins.length) return 'NO_INPUT'; + if (ins.length === 1) {{ + const i = ins[0]; i.focus(); i.value = {c}; + i.dispatchEvent(new Event('input',{{bubbles:true}})); + i.dispatchEvent(new Event('change',{{bubbles:true}})); + return 'SINGLE'; + }} + ins.forEach((i, n) => {{ i.focus(); i.value = String({c})[n] || ''; i.dispatchEvent(new Event('input',{{bubbles:true}})); }}); + return 'SPLIT:' + ins.length; + }})()""") + log("code fill: " + str(filled)) + time.sleep(2) + log("verify click: " + str(ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => !x.disabled && x.offsetParent && /^Continue$/i.test((x.innerText||'').trim())); + if (b) { b.click(); return 'continue'; } + return 'NONE'; + })()"""))) + time.sleep(12) + + final = ev(page, "(() => ({url: location.href, body: document.body.innerText.slice(0,400)}))()") or {} + final["body"] = (final.get("body") or "").replace("\n", " | ") + log("FINAL url=" + str(final.get("url", ""))[:130]) + log("FINAL BODY: " + str(final.get("body", ""))[:350]) + if DEBUG_SHOTS: + page.screenshot(path=OUT + f"\\gh_a{IDX}_6final.png") + for _ in range(6): + t = (body_text(page) or "").lower() + if "welcome" in t or "where teams" in t or "plan" in t or "cancel" in t or "skip" in t: + ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button, a')).find(x => + /^(Skip|Cancel|Continue|Next|Maybe later|Do this later)$/i.test((x.innerText||'').trim()) && !x.disabled); + if (b) { b.click(); return true; } return false; + })()""") + time.sleep(4) + else: + break + dd_save_trust(page.context) + cookies = page.context.cookies() + verdict = "OK_VERIFIED" + save({"status": verdict, "email": email, "username": username, "password": password, + "mail_password": (mailtm_box or {}).get("password", ""), + "mail_token": (mailtm_box or {}).get("token", ""), + "final_url": (page.url or "")[:160], "cookie_count": len(cookies), + "final_body": final.get("body", "")[:180]}) + return 0 + except Exception as e: + log(f"EXC(try {browser_try}) " + type(e).__name__ + ": " + str(e)[:220]) + if browser_try == 2: + save({"status": "EXC", "email": email, "username": username, "password": password, + "err": f"{type(e).__name__}: {str(e)[:160]}"}) + return 1 + time.sleep(20) + save({"status": "BROWSER_DEAD", "email": email, "username": username, "password": password}) + return 1 + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/autoreg/gh_db.py b/autoreg/gh_db.py new file mode 100644 index 0000000..4004a72 --- /dev/null +++ b/autoreg/gh_db.py @@ -0,0 +1,244 @@ +# -*- coding: utf-8 -*- +"""SQLite store for GitHub/GitLab accounts. +Central DB: accounts.db (SQLite, WAL mode). +All autoreg / postreg / verify flows write here. +JSONL files stay as append-only raw feed, DB is the source of truth. +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import json, os, sqlite3, time, threading + +DB_PATH = str(_w("tmp/bpproxy_run/accounts.db")) +_LOCK = threading.Lock() + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS accounts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + provider TEXT NOT NULL DEFAULT 'github', + idx TEXT, + email TEXT, + username TEXT, + password TEXT, + status TEXT DEFAULT 'NEW', + mail_password TEXT, + mail_token TEXT, + final_url TEXT, + err TEXT, + -- postreg fields + new_username TEXT, + avatar TEXT, -- local avatar file + avatar_url TEXT, -- github user avatar url + bio TEXT, + repo_name TEXT, + repo_type TEXT, -- 'fork' | 'own' | None + totp_secret TEXT, + totp_ok INTEGER DEFAULT 0, + backup_codes TEXT, -- JSON array + twofa_enabled INTEGER DEFAULT 0, + cookies_json TEXT, + notes TEXT, + created_ts TEXT, + updated_ts TEXT +); +CREATE UNIQUE INDEX IF NOT EXISTS ux_provider_username ON accounts(provider, username); +CREATE INDEX IF NOT EXISTS ix_provider_status ON accounts(provider, status); +""" + +VALID_COLS = {"provider", "idx", "email", "username", "password", "status", + "mail_password", "mail_token", "final_url", "err", + "new_username", "avatar", "avatar_url", "bio", "repo_name", + "repo_type", "totp_secret", "totp_ok", "backup_codes", + "twofa_enabled", "cookies_json", "notes", "created_ts", "updated_ts"} + + +def connect(): + os.makedirs(os.path.dirname(DB_PATH), exist_ok=True) + con = sqlite3.connect(DB_PATH, timeout=30) + con.row_factory = sqlite3.Row + con.execute("PRAGMA journal_mode=WAL;") + con.execute("PRAGMA busy_timeout=15000;") + return con + + +def init(): + with _LOCK: + con = connect() + con.executescript(SCHEMA) + con.commit() + con.close() + + +def upsert_account(rec, con=None): + """rec: dict matching accounts columns (subset ok). + Match key: (provider, username) if username present else (provider, email). + Returns account id. + """ + own = con is None + if own: + con = connect() + try: + rec = dict(rec) + rec.setdefault("provider", "github") + rec.setdefault("updated_ts", time.strftime("%Y-%m-%d %H:%M:%S")) + for k, v in list(rec.items()): + if isinstance(v, (list, dict)): + rec[k] = json.dumps(v, ensure_ascii=False) + username = rec.get("username") or "" + email = rec.get("email") or "" + row = None + if username: + row = con.execute( + "SELECT id FROM accounts WHERE provider=? AND username=?", + (rec["provider"], username)).fetchone() + if row is None and email: + row = con.execute( + "SELECT id FROM accounts WHERE provider=? AND email=?", + (rec["provider"], email)).fetchone() + cols = [c for c in rec.keys() if c not in ("id", "created_ts")] + if row: + aid = row["id"] + sets = ", ".join(f"{c}=?" for c in cols) + vals = [rec[c] for c in cols] + [aid] + if cols: + con.execute(f"UPDATE accounts SET {sets} WHERE id=?", vals) + else: + cur_cols = ["provider", "created_ts"] + cols + cur_vals = [rec["provider"], rec["updated_ts"]] + [rec[c] for c in cols] + ph = ", ".join("?" for _ in cur_vals) + cur = con.execute( + f"INSERT INTO accounts ({', '.join(cur_cols)}) VALUES ({ph})", cur_vals) + aid = cur.lastrowid + con.commit() + return aid + finally: + if own: + con.close() + + +def import_jsonl(path, provider): + """Import legacy jsonl feed into DB. Skips records already present + (same username+status) to keep idempotent.""" + if not os.path.exists(path): + return 0 + imported = 0 + con = connect() + try: + con.executescript(SCHEMA) + with open(path, encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + r = json.loads(line) + except Exception: + continue + u = r.get("username") or "" + if not u and not r.get("email"): + continue + # map legacy fields to schema columns, dump the rest into notes + r.setdefault("provider", provider) + if "ts" in r and not r.get("created_ts"): + r["created_ts"] = r.pop("ts") + else: + r.pop("ts", None) + extra = {k: v for k, v in r.items() + if k not in VALID_COLS} + for k in extra: + r.pop(k) + if extra: + r["notes"] = json.dumps(extra, ensure_ascii=False)[:2000] + # keep latest record per username: import in order, upsert overwrites + upsert_account(r, con=con) + imported += 1 + con.commit() + finally: + con.close() + return imported + + +def import_all(): + n1 = import_jsonl(str(_w("tmp/bpproxy_run/github_accounts.jsonl")), "github") + n2 = import_jsonl(str(_w("tmp/bpproxy_run/gitlab_accounts.jsonl")), "gitlab") + return n1, n2 + + +def set_status(provider, username, status, con=None): + return upsert_account({"provider": provider, "username": username, + "status": status}, con=con) + + +def stats(provider=None): + con = connect() + try: + q = "SELECT status, COUNT(*) n FROM accounts" + args = [] + if provider: + q += " WHERE provider=?" + args.append(provider) + q += " GROUP BY status ORDER BY n DESC" + return [(r["status"], r["n"]) for r in con.execute(q, args)] + finally: + con.close() + + +def fetch(provider="github", status="OK_VERIFIED", limit=0, need_postreg=False): + con = connect() + try: + q = "SELECT * FROM accounts WHERE provider=? AND status=?" + args = [provider, status] + if need_postreg: + q += " AND twofa_enabled=0" + q += " ORDER BY id" + if limit: + q += " LIMIT ?" + args.append(limit) + return [dict(r) for r in con.execute(q, args)] + finally: + con.close() + + +def get_by_username(username, provider="github"): + con = connect() + try: + r = con.execute("SELECT * FROM accounts WHERE provider=? AND username=?", + (provider, username)).fetchone() + return dict(r) if r else None + finally: + con.close() + + +if __name__ == "__main__": + init() + n1, n2 = import_all() + print(f"imported github={n1} gitlab={n2} -> {DB_PATH}") + for prov in ("github", "gitlab"): + print(prov, stats(prov)) diff --git a/autoreg/gh_mail.py b/autoreg/gh_mail.py new file mode 100644 index 0000000..8856c75 --- /dev/null +++ b/autoreg/gh_mail.py @@ -0,0 +1,139 @@ +# -*- coding: utf-8 -*- +"""Mailboxes for the GitHub autoreg pipeline. +Primary: mail.tm REST API (disposable inbox, uberip.com etc). +Fallback: Gmail IMAP with +alias addressing (FARM_ALIAS@gmail.com). +All code ASCII. Prints are UTF-8 safe via caller's PYTHONIOENCODING. +""" +import time, re, random, string, json +import requests + +TM_BASE = "https://api.mail.tm" +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" + + +class MailTM: + def __init__(self): + d = requests.get(f"{TM_BASE}/domains", headers={"User-Agent": UA}, timeout=20).json() + self.domains = [x["domain"] for x in d["hydra:member"]] + if not self.domains: + raise RuntimeError("mail.tm no domains") + + def create(self, local=None, password=None): + local = local or "gh" + "".join(random.choices(string.ascii_lowercase + string.digits, k=12)) + password = password or "Gh#" + "".join(random.choices(string.ascii_letters + string.digits, k=13)) + "!7z" + domain = self.domains[0] + address = f"{local}@{domain}" + r = requests.post(f"{TM_BASE}/accounts", + headers={"User-Agent": UA, "Content-Type": "application/json"}, + json={"address": address, "password": password}, timeout=20) + if r.status_code not in (201, 200): + raise RuntimeError(f"mail.tm create {r.status_code}: {r.text[:160]}") + tok = self._token(address, password) + return {"address": address, "password": password, "token": tok} + + def _token(self, address, password): + r = requests.post(f"{TM_BASE}/token", + headers={"User-Agent": UA, "Content-Type": "application/json"}, + json={"address": address, "password": password}, timeout=20) + r.raise_for_status() + return r.json()["token"] + + def wait_code(self, token, sender_hint="github", timeout_sec=300, pattern=r"\b(\d{6,8})\b", seen_ids=None): + """Poll inbox for a code in the newest message matching sender_hint. + Returns (code, message_id) or (None, None) on timeout.""" + seen_ids = seen_ids or set() + hdr = {"User-Agent": UA, "Authorization": f"Bearer {token}"} + deadline = time.time() + timeout_sec + while time.time() < deadline: + try: + r = requests.get(f"{TM_BASE}/messages", headers=hdr, timeout=20) + if r.status_code == 200: + for m in r.json()["hydra:member"]: + mid = m["id"] + if mid in seen_ids: + continue + seen_ids.add(mid) + sender = (m.get("from") or {}).get("address", "") + subject = m.get("subject", "") + if not (sender_hint.lower() in sender.lower() or sender_hint.lower() in subject.lower()): + continue + d = requests.get(f"{TM_BASE}/messages/{mid}", headers=hdr, timeout=20).json() + text = " ".join([d.get("text", "") or "", d.get("html", "") or ""]) + mm = re.search(pattern, text, re.I) + if mm: + return mm.group(1), mid + except Exception: + pass + time.sleep(5) + return None, None + + +class GmailIMAP: + """Gmail +alias mailbox via IMAP. All aliases land in one inbox.""" + + def __init__(self, user="FARM_GMAIL@gmail.com", app_pass="GMAIL_APP_PASS", alias_prefix="ghsig"): + import imaplib + self.user = user + self.pass_ = app_pass + self.prefix = alias_prefix + + def make_address(self, idx=None): + idx = idx or random.randint(10000, 99999) + u, d = self.user.split("@") + return f"{u}+{self.prefix}{idx}@{d}" + + def wait_code(self, address, timeout_sec=300): + import imaplib + import email as email_lib + deadline = time.time() + timeout_sec + while time.time() < deadline: + try: + m = imaplib.IMAP4_SSL("imap.gmail.com", 993) + m.login(self.user, self.pass_) + m.select("INBOX") + st, data = m.search(None, f'TO "{address}"') + ids = [] + if st == "OK" and data[0]: + ids = data[0].split()[-5:] + else: + st, data = m.search(None, 'FROM "noreply@github.com"') + if st == "OK" and data[0]: + ids = data[0].split()[-5:] + found = None + for mid in reversed(ids): + st, md = m.fetch(mid, "(RFC822)") + if st != "OK": + continue + msg = email_lib.message_from_bytes(md[0][1]) + body = "" + if msg.is_multipart(): + for part in msg.walk(): + if part.get_content_type() in ("text/plain", "text/html"): + try: + body += part.get_payload(decode=True).decode("utf-8", "ignore") + except Exception: + pass + else: + try: + body = msg.get_payload(decode=True).decode("utf-8", "ignore") + except Exception: + body = "" + mm = re.search(r"(\b\d{8}\b|\b\d{6}\b)", body) + if mm and ("github" in str(msg.get("From", "")).lower() or address in str(msg.get("To", "")) or address in str(msg.get("Delivered-To", ""))): + found = mm.group(1) + break + m.logout() + if found: + return found + except Exception: + pass + time.sleep(6) + return None + + +if __name__ == "__main__": + tm = MailTM() + box = tm.create() + print(json.dumps({"address": box["address"], "token_len": len(box["token"])}, ensure_ascii=False)) + g = GmailIMAP() + print("gmail alias sample:", g.make_address()) \ No newline at end of file diff --git a/autoreg/gh_pat.py b/autoreg/gh_pat.py new file mode 100644 index 0000000..4982648 --- /dev/null +++ b/autoreg/gh_pat.py @@ -0,0 +1,217 @@ +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +# PAT harvester for warmed accounts: login w/ TOTP -> device-code via gmail -> PAT -> DB +import time, sys, re, json, sqlite3 +sys.path.insert(0, str(_REPO)) +from camoufox.sync_api import Camoufox +import pyotp +import imaplib +import email as el + +DB = str(_w("tmp/bpproxy_run/accounts.db")) +from gh_mail import GmailIMAP # real creds live in gh_mail - never copy them here +_GMAIL = GmailIMAP() +# The workstation IP drives the fleet control plane; a fraud flag on it costs +# the whole fleet. Every login goes through the VPS SOCKS tunnel instead. +proxy = {"server": "socks5://127.0.0.1:2090"} + + +def fetch_device_code(addr, timeout=240, since=None): + since = since or 0 + t0 = time.time() + while time.time() - t0 < timeout: + try: + m = imaplib.IMAP4_SSL("imap.gmail.com", 993) + m.login(_GMAIL.user, _GMAIL.pass_) + m.select("INBOX") + st, data = m.search(None, '(FROM "noreply@github.com")') + ids = data[0].split()[-4:] + for mid in reversed(ids): + st, md = m.fetch(mid, "(BODY.PEEK[HEADER.FIELDS (SUBJECT TO DATE)])") + msg = el.message_from_bytes(md[0][1]) + if addr.lower() not in str(msg.get("To", "")).lower(): + continue + import email.utils as eutils + try: + dt = eutils.parsedate_to_datetime(str(msg.get("Date", ""))) + if since and dt.timestamp() < since - 60: + continue # stale code from earlier session + except Exception: + pass + st2, md2 = m.fetch(mid, "(BODY.PEEK[])") + body = md2[0][1].decode("utf-8", "ignore") + mm = re.search(r'\b(\d{6,8})\b', str(msg.get("Subject", "")) + body[:800]) + if mm: + m.logout() + return mm.group(1) + m.logout() + except Exception: + pass + time.sleep(8) + return None + + +def pat_for(username, password, totp_secret, email): + login_start = time.time() + with Camoufox(headless=True, humanize=True, proxy=proxy) as browser: + page = browser.new_page() + page.goto("https://github.com/login", wait_until="domcontentloaded", timeout=60000) + time.sleep(3) + page.fill("#login_field", username, timeout=15000) + page.fill("#password", password, timeout=15000) + page.click("input[name='commit'], button[type=submit]", timeout=10000) + time.sleep(8) + url = page.url + # device verification? + if "verified-device" in url: + code = fetch_device_code(email, since=login_start) + print(f"[p] {username} device code: {code}") + if not code: + return None + try: + loc = page.locator("input#otp, input[name='otp'], input[inputmode='numeric']").first + loc.wait_for(state="visible", timeout=15000) + loc.click() + loc.press_sequentially(str(code), delay=90) + time.sleep(2) + page.click("button:has-text('Verify')", timeout=10000) + except Exception as e: + print(f"[p] {username} verify click: {str(e)[:50]}") + # wait for the page to advance (slow 3G) + for _ in range(12): + time.sleep(5) + if "verified-device" not in page.url: + break + url = page.url + if "verified-device" in url: + try: + b = " ".join(page.inner_text("body").split())[:200] + print(f"[p] {username} device stuck, body: {b}") + inputs = page.evaluate("() => Array.from(document.querySelectorAll('input')).map(i => i.type + '#' + (i.id || i.name || '?')).join(' | ')") + print(f"[p] inputs: {inputs[:200]}") + except Exception: + pass + # 2FA TOTP? + if "two-factor" in url: + if not totp_secret: + print(f"[p] {username} two-factor without totp_secret - skip") + return None + totp = pyotp.TOTP(totp_secret).now() + try: + page.fill("input[name='otp'], input#app_totp", totp, timeout=10000) + page.click("button:has-text('Verify'), input[name='commit']", timeout=25000) + time.sleep(8) + except Exception as e: + print(f"[p] {username} totp click slow: {str(e)[:50]}") + time.sleep(10) + if "two-factor" in page.url: + return None + # navigation completed despite click timeout + print(f"[p] {username} logged in: {page.url[:50]}") + # PAT + page.goto("https://github.com/settings/tokens/new", wait_until="domcontentloaded", timeout=60000) + time.sleep(3) + try: + page.fill("input#oauth_access_description", f"ci-{username}-{int(time.time())%100000}", timeout=10000) + page.evaluate("""() => { document.querySelectorAll('input[type="checkbox"]').forEach(cb => { if (!cb.checked) cb.click(); }); }""") + time.sleep(1) + for sel in ("label:has-text('No expiration')", "input[value='no_expiration']"): + try: + if page.locator(sel).count() > 0: + page.locator(sel).first.click() + break + except Exception: + pass + time.sleep(1) + for bt in ("Generate token", "Generate"): + try: + b = page.locator(f"button:has-text('{bt}')").first + if b.count() > 0: + b.click(timeout=8000) + time.sleep(4) + break + except Exception: + pass + pat = page.evaluate("() => { const m = document.body.innerText.match(/gh[pousr]_[a-zA-Z0-9]{36,}/); return m ? m[0] : null; }") + if not pat: + # diagnostics: why no token + try: + u = page.url + b = " ".join(page.inner_text("body").split())[:150] + print(f"[p] {username} no-token url={u[:60]} body={b[:120]}") + except Exception: + pass + return pat + except Exception as e: + print(f"[p] {username} PAT err: {str(e)[:80]}") + return None + + +def main(): + limit = int(sys.argv[1]) if len(sys.argv) > 1 else 5 + only = sys.argv[2] if len(sys.argv) > 2 else None + db = sqlite3.connect(DB) + # warmed accounts (2FA on, no PAT yet) — PAT stored in notes col? add col + try: + db.execute("ALTER TABLE accounts ADD COLUMN pat TEXT") + db.commit() + except Exception: + pass + q = """SELECT username, password, totp_secret, email FROM accounts + WHERE twofa_enabled=1 AND (pat IS NULL OR pat='') AND COALESCE(pat_fail,0) < 3""" + if only: + q += " AND username=?" + rows = db.execute(q, (only,)).fetchall() + else: + rows = db.execute(q + " ORDER BY (pat_fail IS NULL) DESC, username LIMIT ?", (limit,)).fetchall() + print(f"[p] target accounts: {len(rows)}") + ok = 0 + for username, password, totp_secret, email in rows: + print(f"[p] === {username} ===") + pat = pat_for(username, password, totp_secret, email) + if pat: + db.execute("UPDATE accounts SET pat=?, pat_fail=0 WHERE username=?", (pat, username)) + db.commit() + print(f"[p] {username} PAT: {pat[:18]}...") + ok += 1 + else: + print(f"[p] {username} PAT: FAILED") + try: + db.execute("UPDATE accounts SET pat_fail=COALESCE(pat_fail,0)+1 WHERE username=?", (username,)) + db.commit() + except Exception: + pass + time.sleep(60) + print(f"[p] DONE ok={ok}/{len(rows)}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/autoreg/gh_pipeline.py b/autoreg/gh_pipeline.py new file mode 100644 index 0000000..58c6484 --- /dev/null +++ b/autoreg/gh_pipeline.py @@ -0,0 +1,113 @@ +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +# 24/7 pipeline supervisor: register -> warmup -> PAT, loop until target +import subprocess, time, json, sqlite3, sys, os + +PY = _PY +OUT = str(_w("tmp/bpproxy_run")) +DB = OUT + r"\accounts.db" +LOG = open(OUT + r"\pipeline.log", "a", encoding="utf-8") + +TARGET = int(sys.argv[1]) if len(sys.argv) > 1 else 1000 + + +def log(m): + line = f"[{time.strftime('%H:%M:%S')}] PIPE: {m}" + print(line, flush=True) + LOG.write(line + "\n") + LOG.flush() + + +def counts(): + db = sqlite3.connect(DB) + ok = db.execute("SELECT COUNT(*) FROM accounts WHERE status='OK_VERIFIED'").fetchone()[0] + warmed = db.execute("SELECT COUNT(*) FROM accounts WHERE twofa_enabled=1").fetchone()[0] + pats = db.execute("SELECT COUNT(*) FROM accounts WHERE pat IS NOT NULL AND pat != ''").fetchone()[0] + db.close() + return ok, warmed, pats + + +def run(cmd, timeout): + try: + r = subprocess.run([PY, "-u"] + cmd, cwd=OUT, capture_output=True, text=True, timeout=timeout) + out = (r.stdout or "") + (r.stderr or "") + return r.returncode, out + except subprocess.TimeoutExpired: + return 99, "timeout" + + +idx = 200 # supervisor's own registration index space +cycle = 0 +while True: + cycle += 1 + ok, warmed, pats = counts() + log(f"cycle {cycle}: ok={ok} warmed={warmed} pat={pats} target={TARGET}") + if ok >= TARGET: + log("TARGET REACHED") + break + + # 1) registration if below target + if ok < TARGET: + idx += 1 + # ZTE: fresh mobile IP before each attempt (UI toggle rotation) + try: + subprocess.run([PY, "-u", "zte_ui_rotate2.py"], cwd=OUT, + capture_output=True, timeout=300) + except Exception: + pass + rc, out = run(["gh_autoreg.py", str(idx).zfill(3), "ZTE", "gmail"], 900) + status = "ok" if "OK_VERIFIED" in out else ("timeout" if rc == 99 else "fail") + log(f"reg #{idx}: {status}") + time.sleep(30) # let modem/browser settle before warmup + time.sleep(__import__("random").uniform(90, 200)) + + # 2) warmup: pick one warmed-less account (retry once) + rc, out = run(["gh_postreg.py", "1"], 900) + if ("skip" not in out and "finished: ok=0" in out) or rc in (99, None): + time.sleep(45) + rc, out = run(["gh_postreg.py", "1"], 900) + if "finished: ok=1" in out or "ok=1/" in out: + log("warmup: +1") + elif "no accounts to process" in out: + log("warmup: queue empty") + else: + log("warmup: skip/fail") + time.sleep(20) + + # 3) PAT for one warmed account without PAT + rc, out = run(["gh_pat.py", "1"], 900) + if "DONE ok=1" in out: + log("pat: +1") + elif "target accounts: 0" in out: + log("pat: queue empty") + else: + log("pat: skip/fail") + time.sleep(20) \ No newline at end of file diff --git a/autoreg/gh_postreg.py b/autoreg/gh_postreg.py new file mode 100644 index 0000000..d4a8903 --- /dev/null +++ b/autoreg/gh_postreg.py @@ -0,0 +1,777 @@ +# -*- coding: utf-8 -*- +"""GitHub post-registration profiler + 2FA hardening. + +For each OK_VERIFIED account from accounts.db: + 1. login (email + password) through Camoufox + 2. generate + upload avatar (Pillow, identicon-style gradient) + 3. set bio + name (profile "oformlenie") + 4. change username (fresh, non-patterned) + 5. create own repo OR fork a real one (README with content) + 6. enable TOTP 2FA, download backup codes + 7. save everything back to accounts.db, push creds to TG + +Usage: + python gh_postreg.py [limit] [username_filter] + python gh_postreg.py 1 # one oldest account + python gh_postreg.py 0 cobaltdev128 # exactly this account +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import time, json, re, sys, os, random, string, base64, io + +sys.path.insert(0, str(_REPO)) +import gh_db +from gh_db import upsert_account + +from camoufox.sync_api import Camoufox +import pyotp +from PIL import Image, ImageDraw +from gh_autoreg import human_sleep, human_type, human_scroll, human_move_mouse + +OUT = str(_w("tmp/bpproxy_run")) +AVATARS = OUT + r"\avatars" +LOG = OUT + r"\gh_postreg.log" + +P_USER = "bpproxy-user" +P_PASS = "BPPROXY_PASS" +P_HOST = "bpproxy-host:1000" + +FORK_TARGETS = [ + ("awesome-chatgpt-prompts", "f/awesome-chatgpt-prompts"), + ("public-api", "public-api"), +] +REPO_TOPICS = ["automation", "tools", "python", "scripts", "web", "api", "dev", "utils"] + +# bios pool (short, human, no AI-isms) +BIOS = [ + "tinkering with python & web automation", + "building small tools that do boring stuff", + "dev tools, scripts, occasional scraping", + "python / js. mostly experiments here", + "code, coffee, side projects", + "making repos so my scripts have a home", + "software tinkering. random useful stuff", +] +NAMES_POOL = [ + ("Alex", "Moreau"), ("Sam", "Ridley"), ("Kai", "Novak"), ("Robin", "Hale"), + ("Jesse", "Linden"), ("Morgan", "Reyes"), ("Ash", "Brennan"), ("Drew", "Karlsen"), + ("Casey", "Volker"), ("Noel", "Ferrer"), +] + +REPO_README = """# {repo} + +{tagline} + +## What's inside + +- {item1} +- {item2} +- {item3} + +## Notes + +{note} + +Made with too much coffee. License: MIT. +""" + + +def log(m): + line = f"[{time.strftime('%H:%M:%S')}] {m}" + print(line, flush=True) + with open(LOG, "a", encoding="utf-8") as f: + f.write(line + "\n") + + +def proxy_cfg(label): + if label == "HOME": + return None + if label == "ZTE": + return {"server": "http://127.0.0.1:8899"} + if label == "HK1024": + import random as _r + try: + pool = [88291] + [int(x) for x in open(str(_w("tmp/bpproxy_run/clean_sids.txt"))).read().split() if x.strip()] + except Exception: + pool = [88291] + sid = _r.choice(pool) + return {"server": "http://hk.1024proxy.io:3000", + "username": f"PROXY_USER-region-HK-sid-{sid}-t-30", + "password": "PROXY_PASS"} + return {"server": f"http://{P_HOST}", "username": P_USER, + "password": f"{P_PASS}_session-{label}_lifetime-30"} + + +def gen_new_username(): + """less bot-looking than adj+noun+3digits: word+digits, sometimes underscore.""" + words = ["harbor", "quill", "fjord", "wren", "onyx", "cedar", "maple", "rune", + "solace", "vector", "kestrel", "lumen", "cobble", "thistle", "brisk", + "hollow", "gravel", "saffron", "tidal", "ember"] + w = random.choice(words) + style = random.randint(0, 3) + if style == 0: + return w + str(random.randint(2, 99)) + if style == 1: + return w + "_" + random.choice(["dev", "ops", "hq", "labs", "x"]) + str(random.randint(1, 99)) + if style == 2: + return random.choice(words) + random.choice(words) + str(random.randint(1, 999)) + return w + str(random.randint(1000, 99999)) + + +def make_avatar(seed): + """Deterministic gradient identicon 512x512, saved to avatars/.png""" + os.makedirs(AVATARS, exist_ok=True) + path = os.path.join(AVATARS, seed + ".png") + if os.path.exists(path): + return path + rnd = random.Random(seed) + h = rnd.randint(0, 359) + base = (h, rnd.randint(55, 75), rnd.randint(45, 65)) + h2 = (h + rnd.randint(30, 120)) % 360 + img = Image.new("RGB", (512, 512)) + dr = ImageDraw.Draw(img, "RGBA") + + def hx(hh, ss, vv): + import colorsys + r, g, b = colorsys.hsv_to_rgb(hh / 360, ss / 100, vv / 100) + return (int(r * 255), int(g * 255), int(b * 255)) + + for y in range(512): + t = y / 511 + # gradient blend h->h2 + hh = (h + (h2 - h) * t) % 360 + ss = base[1] + (30 - 60 * t) + vv = base[2] + (25 - 10 * t) + dr.line([(0, y), (512, y)], fill=hx(hh, max(15, min(90, ss)), max(35, min(80, vv)))) + # random geometric overlay blocks + for _ in range(rnd.randint(6, 12)): + x0, y0 = rnd.randint(-60, 460), rnd.randint(-60, 460) + s = rnd.randint(40, 200) + alpha = rnd.randint(30, 90) + col = hx((h + rnd.randint(0, 90)) % 360, rnd.randint(40, 80), rnd.randint(50, 90)) + (alpha,) + if rnd.random() < 0.5: + dr.rounded_rectangle([x0, y0, x0 + s, y0 + s], radius=s // 6, fill=col) + else: + dr.ellipse([x0, y0, x0 + s, y0 + s], fill=col) + img.save(path, "PNG") + return path + + +def ev(page, js): + try: + return page.evaluate(js) + except Exception: + return None + + +def body_text(page): + try: + return (page.evaluate("document.body.innerText") or "")[:2000] + except Exception: + return "" + + +def login(page, email, password, username): + page.goto("https://github.com/login", timeout=90000, + wait_until="domcontentloaded") + human_sleep(3.0, 1.5) # read the page + human_move_mouse(page) + human_scroll(page, "down", n=random.randint(1, 2)) + human_scroll(page, "up", n=1) + human_sleep(1.2, 0.6) + # type email like a person (no instant fill) + human_type(page, "#login_field", email) + human_sleep(1.3, 0.7) + human_type(page, "#password", password) + human_sleep(1.5, 0.8) + page.screenshot(path=OUT + "\\pr_login_filled.png") + # human pause before submit + human_move_mouse(page) + human_sleep(0.9, 0.5) + page.click("input[name=commit], button[type=submit]") + human_sleep(10, 3) + url = page.url + log("login url: " + url[:120]) + body = body_text(page) + if "two-factor" in url or "2fa" in url: + return "2FA_ALREADY", None + if "Incorrect username or password" in body: + return "BAD_CREDS", None + # device verification screen (email code) — BEFORE generic /session check, + # because its url contains /sessions/verified-device + if "verified-device" in url or ("verify" in body.lower() and "code" in body.lower() + and "resend" in body.lower()): + return "DEVICE_VERIFY", url + if "/session" in url: + return "LOGIN_FAIL", None + return "OK", url + + +def wait_device_code(page, account, timeout_sec=280): + """If GitHub wants email device verification code, fetch it from mail.""" + from gh_mail import MailTM, GmailIMAP + email = account["email"] + code = None + if account.get("mail_token"): + code, _ = MailTM().wait_code(account["mail_token"], timeout_sec=timeout_sec, + pattern=r"\b(\d{6,8})\b") + if not code and "+ghsig" in (email or ""): + code = GmailIMAP().wait_code(email, timeout_sec=timeout_sec) + if not code: + return False + log(f"device code={code}") + # type code like a human (found in live flow: #app_totp / numeric inputs) + human_sleep(1.5, 0.8) # "check the phone/email" pause + sel = "input[name=otp], input[name=app_otp], input[autocomplete=one-time-code]" + try: + loc = page.locator(sel).first + loc.wait_for(state="visible", timeout=8000) + loc.click() + loc.press_sequentially(str(code), delay=random.uniform(90, 160)) + except Exception as e: + log("devver typewriter fallback: " + str(e)[:60]) + ev(page, f"""(() => {{ + const ins = Array.from(document.querySelectorAll('input[inputmode=numeric], input[autocomplete=one-time-code], input[name*=code i], input[id*=code i]')); + if (!ins.length) return 'NO_INPUT'; + if (ins.length === 1) {{ + const i = ins[0]; i.focus(); i.value = {json.dumps(str(code))}; + i.dispatchEvent(new Event('input',{{bubbles:true}})); + i.dispatchEvent(new Event('change',{{bubbles:true}})); + return 'SINGLE'; + }} + ins.forEach((i, n) => {{ i.focus(); i.value = String({json.dumps(str(code))})[n] || ''; i.dispatchEvent(new Event('input',{{bubbles:true}})); }}); + return 'SPLIT:' + ins.length; + }})()""") + human_sleep(2.0, 0.8) + ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => !x.disabled && x.offsetParent && /verify/i.test((x.innerText||'').trim())); + if (b) { b.click(); return true; } + return false; + })()""") + time.sleep(10) + return "/login" not in page.url + + +def upload_avatar(page, path): + page.goto("https://github.com/settings/profile", timeout=90000, + wait_until="domcontentloaded") + human_sleep(3.0, 1.2) + try: + inp = page.query_selector("#avatar_upload, input[type=file][accept*=image], input.js-profile-file-edit") + if not inp: + # 2026 UI: avatar edit under button + human_move_mouse(page) + human_sleep(0.8, 0.4) + ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button, summary')).find(x => /avatar|photo|picture/i.test((x.innerText||'') + (x.getAttribute('aria-label')||''))); + if (b) { b.click(); return true; } return false; + })()""") + human_sleep(2.0, 0.8) + inp = page.query_selector("input[type=file]") + if not inp: + return "NO_FILE_INPUT" + inp.set_input_files(path) + human_sleep(3.0, 1.0) # photo 'processing' + # crop/scale dialog may appear -> confirm + ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => !x.disabled && /^(set new profile photo|save|apply|use photo|confirm)$/i.test((x.innerText||'').trim())); + if (b) { b.click(); return 'SET'; } return 'NOBTN'; + })()""") + human_sleep(4.0, 1.5) + save_profile_settings(page) + return "OK" + except Exception as e: + return "AVATAR_EXC:" + str(e)[:80] + + +def save_profile_settings(page): + ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => !x.disabled && /^update profile$/i.test((x.innerText||'').trim())); + if (b) { b.click(); return true; } + const b2 = document.querySelector("button[data-testid='update-profile-button'], .js-profile-editable-save button"); + if (b2) { b2.click(); return true; } + return false; + })()""") + time.sleep(5) + + +def set_profile(page, first, last, bio): + try: + if "settings/profile" not in page.url: + page.goto("https://github.com/settings/profile", timeout=90000, + wait_until="domcontentloaded") + except Exception: + pass # avatar step already navigated; double-nav race is harmless + human_sleep(3.0, 1.2) + human_scroll(page, "down", n=random.randint(1, 3)) # look around settings + human_sleep(1.0, 0.5) + # name — type like a person + name_sel = "#user_display_name, #user_profile_name, input[name='user[profile_name]']" + try: + el = page.query_selector(name_sel.replace(", ", ", ")) + if el: + human_type(page, name_sel.split(",")[0].strip(), f"{first} {last}") + except Exception as e: + log("name fill exc: " + str(e)[:60]) + human_sleep(1.2, 0.6) + # bio + bio_sel = "#user_profile_bio, textarea[name='user[profile_bio]']" + try: + human_type(page, bio_sel.split(",")[0].strip(), bio, click_first=True) + except Exception as e: + log("bio fill exc: " + str(e)[:60]) + human_sleep(1.5, 0.7) + page.screenshot(path=OUT + "\\pr_profile_filled.png") + save_profile_settings(page) + human_sleep(2.5, 1.0) + + +def change_username(page, new_username): + page.goto("https://github.com/settings/admin", timeout=90000) + time.sleep(4) + body = body_text(page) + if "change username" not in body.lower() and "Change your username" not in body: + log("no change-username block visible; trying UI anyway") + ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button, summary, a')).find(x => /change username/i.test((x.innerText||'').trim())); + if (b) { b.click(); return true; } return false; + })()""") + time.sleep(2.5) + # danger-zone modal with input + filled = ev(page, """(() => { + const inp = Array.from(document.querySelectorAll('input[aria-describedby], input[name*=login i], input[placeholder*=current i]')) + .find(i => i.offsetParent); + if (!inp) return 'NO_INP'; + inp.focus(); + return 'FOUND:' + (inp.name || inp.id || 'x'); + })()""") + log("rename input: " + str(filled)) + # type new name into the dialog field + try: + el = page.query_selector("input[name*='login' i], dialog input, modal input") + if el: + el.fill(new_username) + except Exception: + pass + time.sleep(1) + r = ev(page, """(() => { + const dlg = document.querySelector('dialog[open], .Overlay, [role=dialog]'); + const scope = dlg || document; + const b = Array.from(scope.querySelectorAll('button')).find(x => /update username|change username|rename/i.test((x.innerText||'').trim()) && !x.disabled); + if (b) { b.click(); return 'CLICKED'; } + return 'NOBTN'; + })()""") + log("rename click: " + str(r)) + time.sleep(8) + # confirm page: "I understand, update my username" + r2 = ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => /i understand, update/i.test((x.innerText||'').trim()) && !x.disabled); + if (b) { b.click(); return 'CONFIRM'; } + return 'NOCONFIRM'; + })()""") + log("rename confirm: " + str(r2)) + time.sleep(10) + url = page.url + ok = "admin" in url or page.query_selector("input[name*=login i]") is None + # verify on profile + page.goto(f"https://github.com/{new_username}", timeout=90000) + time.sleep(4) + notfound = "404" in body_text(page)[:200] or "This is not the web page" in body_text(page) + if notfound: + return False + return True + + +def create_repo(page, repo_name, account): + """2026 UI: #repository-name-input, Public toggle-button, Create repository submit.""" + page.goto("https://github.com/new", timeout=90000, + wait_until="domcontentloaded") + human_sleep(4.0, 1.5) # read the form + human_scroll(page, "down", n=random.randint(1, 3)) + human_scroll(page, "up", n=1) + human_sleep(1.2, 0.6) + # name (new 2026 input) — typed char by char + try: + page.wait_for_selector("#repository-name-input", timeout=30000) + loc = page.locator("#repository-name-input") + loc.click() + loc.press_sequentially(repo_name, delay=random.uniform(80, 150)) + human_sleep(2.0, 0.8) + except Exception as e: + log("repo name fill exc: " + str(e)[:80]) + return False + # description + try: + loc = page.locator("input[name='Description']") + loc.click() + loc.press_sequentially(random.choice([ + "small tools collection", "automation scripts", "helper utilities", + "misc dev experiments", "tiny python utilities"])[:80], + delay=random.uniform(30, 90)) + human_sleep(1.2, 0.6) + except Exception: + pass + # Public (button in 2026 UI) + ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => /^public$/i.test((x.innerText||'').trim()) && x.offsetParent !== null); + if (b) { b.click(); return 'public'; } + const r = document.querySelector('input#repository_visibility_public, input[name=repository_visibility][value=public]'); + if (r) { r.click(); return 'radio'; } + return 'none'; + })()""") + human_sleep(1.3, 0.6) + # "Add a README" (checkbox or button in new UI) + ev(page, """(() => { + const c = document.querySelector('#repository_auto_init, input[name=auto_init]'); + if (c) { c.click(); return 'old'; } + const b = Array.from(document.querySelectorAll('button, label, summary')).find(x => /readme/i.test((x.innerText||'').trim()) && x.offsetParent !== null); + if (b) { b.click(); return 'btn'; } + return 'none'; + })()""") + human_sleep(1.5, 0.7) + page.screenshot(path=OUT + "\\pr_repo_form.png") + # submit "Create repository" + r = ev(page, """(() => { + const b = Array.from(document.querySelectorAll('button[type=submit], button')).find(x => /create repository/i.test((x.innerText||'').trim()) && x.offsetParent !== null); + if (b && !b.disabled) { b.click(); return 'CLICK'; } + return 'DISABLED'; + })()""") + log("repo create click: " + str(r)) + time.sleep(14) + # verify creation: page may sit at /new while redirect completes — re-check url + repo page + ok_url = repo_name in page.url and "/new" not in page.url + if not ok_url: + try: + page.goto(f"https://github.com/{account['username']}/{repo_name}", + timeout=60000, wait_until="domcontentloaded") + time.sleep(3) + ok_url = "Page not found" not in (body_text(page) or "") + except Exception: + ok_url = False + if ok_url: + # edit README with real content + try: + page.goto(f"https://github.com/{account['username']}/{repo_name}/edit/main/README.md", + timeout=90000) + time.sleep(3) + tagline = random.choice([ + "assorted scripts and tools", "random dev utilities", + "small tools, nothing fancy", "stuff that automates stuff"]) + content = REPO_README.format( + repo=repo_name, tagline=tagline, + item1=random.choice(["CLI helpers", "scrapers", "file utilities", "API wrappers"]), + item2=random.choice(["backup scripts", "cron jobs", "one-off experiments", "glue code"]), + item3=random.choice(["notes & docs", "tiny libs", "docker snippets", "config templates"]), + note=random.choice([ + "Mostly for personal use, shared in case it helps.", + "Written late at night, works on my machine.", + "Refactor when time allows.", + "See commits for the mess in progress."])) + ed = page.query_selector("textarea, div.CodeMirror, [role=textbox]") + if ed: + try: + ed.fill("") + ed.fill(content) + except Exception: + ev(page, """(() => { + const t = document.querySelector('textarea'); + if (t) { t.value = %s; t.dispatchEvent(new Event('input',{bubbles:true})); } + })()""" % json.dumps(content)) + page.screenshot(path=OUT + "\\pr_readme_edit.png") + ev(page, """(() => { + const b = document.querySelector("button[type=submit], .Button--primary"); + if (b && !b.disabled) { b.click(); return 'COMMIT'; } + return 'NO'; + })()""") + time.sleep(8) + except Exception as e: + log("readme edit exc: " + str(e)[:80]) + return True + return False + + +def fork_repo(page): + target = random.choice(["microsoft/WSL", "torvalds/linux", "psf/requests", + "tiangolo/fastapi", "sindresorhus/awesome"]) + log(f"fork target: {target}") + page.goto(f"https://github.com/{target}/fork", timeout=90000, + wait_until="domcontentloaded") + human_sleep(4.0, 1.5) # look at the fork page + human_scroll(page, "down", n=random.randint(1, 2)) + r = ev(page, """(() => { + const b = document.querySelector('.Button--primary, button[type=submit]'); + const b2 = Array.from(document.querySelectorAll('button')).find(x => /^create fork$/i.test((x.innerText||'').trim())); + const bb = b2 || b; + if (bb && !bb.disabled) { bb.click(); return 'CLICK'; } + return 'FAIL:' + (bb ? bb.disabled : 'nobtn'); + })()""") + log("fork click: " + str(r)) + human_sleep(15, 4) + body = body_text(page) + return "forked" in body.lower() or "already exists" in body.lower() or "your fork" in body.lower() + + +def enable_2fa_totp(page, uname): + """Enable TOTP 2FA via wizard (verified live flow 2026-09). + Returns (totp_secret, backup_codes_list) or (None, None).""" + page.goto("https://github.com/settings/two_factor_authentication/setup/intro", + timeout=90000, wait_until="domcontentloaded") + human_sleep(5.0, 1.5) # read the wizard + human_scroll(page, "down", n=random.randint(1, 2)) + body = body_text(page) + if "two-factor authentication" in body and "setup" not in page.url: + log("2fa: already enabled?") + return "ALREADY", None + # 1. open "setup key" dialog + page.evaluate("""(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => /setup key/i.test((x.innerText||'').trim())); + if (b) b.click(); + })()""") + time.sleep(3) + # 2. extract secret from dialog + secret = page.evaluate("""(() => { + const dlg = document.querySelector('dialog[open]'); + const m = (dlg || document).innerText.match(/\\b([A-Z2-7]{16,})\\b/); + return m ? m[1] : null; + })()""") + log("2fa secret: " + str(secret)) + if not secret: + page.screenshot(path=OUT + f"\\pr_2fa_nosecret_{uname}.png") + return None, None + # 3. close dialog (X button, fallback Escape) + closed = page.evaluate("""(() => { + const dlg = document.querySelector('dialog[open]'); + if (!dlg) return 'nodialog'; + const x = dlg.querySelector('button[aria-label="Close"], .Overlay-closeButton, button[data-close-dialog-id]'); + if (x) { x.click(); return 'x'; } + return 'nox'; + })()""") + log("2fa dialog close: " + str(closed)) + if closed == "nox": + page.keyboard.press("Escape") + time.sleep(2) + # dialog may persist — force remove overlay via Escape if still open + still = page.evaluate("(() => !!document.querySelector('dialog[open]'))()") + if still: + page.keyboard.press("Escape") + time.sleep(1.5) + page.evaluate("""(() => { + const dlg = document.querySelector('dialog[open]'); + if (dlg) dlg.close ? dlg.close() : dlg.removeAttribute('open'); + })()""") + time.sleep(1) + # 4. type TOTP code: focus via evaluate + keyboard.type (survives overlay/viewport issues) + # human touch: 'open authenticator app' pause + variable per-key delay + human_sleep(1.8, 0.9) + entered = False + for attempt in range(2): + code = pyotp.TOTP(secret).now() + log(f"2fa code={code} (attempt {attempt + 1})") + page.evaluate("""(() => { + const i = document.querySelector("input[name=otp][data-target*='appOtpInput']"); + if (i) { i.scrollIntoView({block: 'center'}); i.focus(); } + })()""") + human_sleep(0.9, 0.4) + # variable typing speed, occasional slow key + for ch in str(code): + page.keyboard.type(ch, delay=0) + d = random.uniform(0.09, 0.22) + if random.random() < 0.15: + d += random.uniform(0.2, 0.5) + time.sleep(d) + time.sleep(2.5) + # verify value landed + val = page.evaluate("""(() => document.querySelector("input[name=otp][data-target*='appOtpInput']").value)""") + if val == code: + entered = True + # 5. scroll to Continue + click + page.evaluate("""(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => /^continue$/i.test((x.innerText||'').trim())); + if (b) b.scrollIntoView({block: 'center'}); + })()""") + time.sleep(1) + r = page.evaluate("""(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => /^continue$/i.test((x.innerText||'').trim())); + if (b && !b.disabled) { b.click(); return 'clicked'; } + return 'state:' + (b ? b.disabled : 'nobtn'); + })()""") + log("2fa continue: " + str(r)) + # nobtn == step already advanced (observed live) — treat as success + if r in ("clicked", "state:nobtn", "state:false"): + break + # code window rotated — retry + time.sleep(5) + if not entered: + page.screenshot(path=OUT + f"\\pr_2fa_nocontinue_{uname}.png") + return secret, None + time.sleep(15) + # 6. recovery step: download codes file (this also unlocks "I have saved") + body = page.evaluate("document.body.innerText") + m = re.search(r"\b([0-9a-f]{6}(?:-[0-9a-f]{6,}){6,})\b", body) + recovery_inline = m.group(1) if m else None + codes = None + dl_path = os.path.join(OUT, "recovery_codes_download.txt") + try: + with page.expect_download(timeout=25000) as dl: + page.evaluate("""(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => /^download$/i.test((x.innerText||'').trim()) && x.offsetParent !== null); + if (b) b.click(); + })()""") + codes = dl.value + path = dl.value.path() + # parse: each line "xxxxx-yyyyy" + txt = open(path, encoding="utf-8").read() + codes = [c for c in re.findall(r"\b([a-z0-9]{5}-[a-z0-9]{5})\b", txt, re.I)] + import shutil + shutil.copy(path, dl_path) + log(f"2fa codes downloaded: {len(codes)}") + except Exception as e: + log("2fa download exc: " + str(e)[:120]) + if recovery_inline: + codes = [recovery_inline] + time.sleep(3) + # 7. finalize: "I have saved my recovery codes" + fin = page.evaluate("""(() => { + const b = Array.from(document.querySelectorAll('button')).find(x => /i have saved my recovery codes/i.test((x.innerText||'').trim())); + if (b && !b.disabled) { b.click(); return 'clicked'; } + return 'disabled:' + (b ? b.disabled : 'nobtn'); + })()""") + log("2fa finalize: " + str(fin)) + time.sleep(12) + return secret, codes + + +def process_account(account, proxy_label="HOME"): + uname = account["username"] + email = account["email"] + password = account["password"] + log(f"=== POSTREG {uname} ({email}) ===") + updates = {"provider": "github", "username": uname} + avatar_path = make_avatar(uname) + new_username = gen_new_username() + first, last = random.choice(NAMES_POOL) + bio = random.choice(BIOS) + cfg = proxy_cfg(proxy_label) + with Camoufox(proxy=cfg, headless=True, humanize=True) as browser: + page = browser.new_page() + st, url = login(page, email, password, uname) + log("login: " + st) + if st == "2FA_ALREADY": + upsert_account({**updates, "status": "OK_VERIFIED", "twofa_enabled": 1}) + return "2FA_ALREADY" + if st != "OK": + if st == "DEVICE_VERIFY": + if not wait_device_code(page, account): + upsert_account({**updates, "status": "DEVICE_VERIFY_FAIL"}) + return "DEVICE_VERIFY_FAIL" + log("device verified") + else: + upsert_account({**updates, "status": st}) + return st + # ---- avatar ---- + av = upload_avatar(page, avatar_path) + log("avatar: " + str(av)) + updates["avatar"] = avatar_path + # ---- profile: name + bio ---- + set_profile(page, first, last, bio) + updates["bio"] = bio + # ---- repo ---- + repo_name = (uname + "-lab")[:60] + repo_type = "own" if random.random() < 0.7 else "fork" + if repo_type == "own": + made = create_repo(page, repo_name, account) + else: + made = fork_repo(page) + repo_name = None + log(f"repo({repo_type}): {made}") + if made: + updates["repo_name"] = repo_name + updates["repo_type"] = repo_type + # ---- 2FA ---- + secret, codes = enable_2fa_totp(page, uname) + if secret and secret != "ALREADY": + updates["totp_secret"] = secret + updates["totp_ok"] = 1 + updates["twofa_enabled"] = 1 + if codes: + updates["backup_codes"] = codes + elif secret == "ALREADY": + updates["twofa_enabled"] = 1 + else: + log("2FA FAILED for " + uname) + # GitHub: rename disabled for fresh accounts ("contact us") — skip + page.screenshot(path=OUT + "\\pr_final.png") + updates["status"] = "POSTREG_DONE" + upsert_account(updates) + # TG push + try: + from gh_autoreg import tg_push_creds + tg_push_creds(email, uname, password) + except Exception as e: + log("tg push exc: " + str(e)[:100]) + return "DONE" + + +def main(): + limit = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + uname_filter = sys.argv[2] if len(sys.argv) > 2 else None + gh_db.init() + if uname_filter: + acc = gh_db.get_by_username(uname_filter) + accounts = [acc] if acc else [] + else: + accounts = gh_db.fetch("github", "OK_VERIFIED", limit=1000) + # only un-warmed accounts; no fallback to already-warmed ones + accounts = [a for a in accounts if not a.get("twofa_enabled")][:limit or 1] + if not accounts: + print("no accounts to process") + return 0 + ok = 0 + for a in accounts[: (limit or len(accounts))]: + res = None + try: + res = process_account(a, proxy_label="HOME") # direct: ZTE modem dead + if res in ("DONE", "2FA_ALREADY"): + ok += 1 + except Exception as e: + log(f"process EXC {a['username']}: {type(e).__name__} {str(e)[:200]}") + upsert_account({"provider": "github", "username": a["username"], + "status": "OK_VERIFIED", "err": f"{type(e).__name__}: {str(e)[:160]}"}) + # fast cadence for unattended workers: short gap, skip trailing sleep + gap = random.uniform(30, 60) if res in ("DONE", "2FA_ALREADY") else random.uniform(15, 30) + log(f"waiting {int(gap)}s before next account") + time.sleep(gap) + log(f"postreg finished: ok={ok}/{len(accounts[:limit or 100])}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/autoreg/gh_runner.py b/autoreg/gh_runner.py new file mode 100644 index 0000000..ee59965 --- /dev/null +++ b/autoreg/gh_runner.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +"""Batch runner for GitHub autoreg. Alternates between HOME IP and VPS SOCKS +to spread ban risk, with human-ish pauses. Continues until target count of +OK_VERIFIED accounts is reached. Progress journaled so restarts are safe. +Usage: python gh_runner.py [target_total] [start_idx] +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import subprocess, time, json, random, sys, os + +OUT = str(_w("tmp/bpproxy_run")) +ACCOUNTS = OUT + r"\github_accounts.jsonl" +STATE = OUT + r"\gh_runner_state.json" +PY = _PY +SCRIPT = OUT + r"\gh_autoreg.py" + +TARGET = int(sys.argv[1]) if len(sys.argv) > 1 else 50 +START = int(sys.argv[2]) if len(sys.argv) > 2 else 10 +LIMIT = int(sys.argv[3]) if len(sys.argv) > 3 else 0 # max accounts this run, 0 = unlimited + +def log(m): + line = f"[{time.strftime('%H:%M:%S')}] RUNNER: {m}" + print(line, flush=True) + +def read_state(): + try: + with open(STATE, encoding="utf-8") as f: + return json.load(f) + except Exception: + return {"done": 0, "tries": 0, "next_idx": START, "errors": {}} + +def write_state(st): + with open(STATE, "w", encoding="utf-8") as f: + json.dump(st, f, ensure_ascii=False, indent=1) + +def count_ok(): + n = 0 + try: + with open(ACCOUNTS, encoding="utf-8") as f: + for line in f: + try: + if json.loads(line).get("status") == "OK_VERIFIED": + n += 1 + except Exception: + pass + except Exception: + pass + return n + +def run_one(idx, source): + env = os.environ.copy() + env["PYTHONIOENCODING"] = "utf-8" + proc = subprocess.run([PY, SCRIPT, str(idx).zfill(3), source, "gmail"], + capture_output=True, text=True, env=env, timeout=600) + return proc.returncode, proc.stdout[-600:] + +def main(): + st = read_state() + ok_total = count_ok() + log(f"state: done_total_ok={ok_total} target={TARGET} next_idx={st['next_idx']}") + if ok_total >= TARGET: + log("target already reached, nothing to do") + return + sources = ["SOCKSH"] + done_this_run = 0 + while ok_total < TARGET and (not LIMIT or done_this_run < LIMIT): + idx = st["next_idx"] + st["next_idx"] += 1 + st["tries"] += 1 + source = random.choice(sources) + log(f"== account {idx} via {source} (have {ok_total}/{TARGET}) ==") + rc = None + for attempt in range(3): + try: + rc, tail = run_one(idx, source if attempt == 0 else random.choice(sources)) + log(f"rc={rc} tail={tail[-200:].strip()[:180]}") + except subprocess.TimeoutExpired: + rc = 90 + log("timeout 600s") + except Exception as e: + rc = 99 + log("launch err: " + str(e)[:100]) + if rc == 0: + done_this_run += 1 + break + if rc in (7, 5, 4, 6, 1, 3): # late-stage/logic - no retry value + break + # rc 2 = FORM_TIMEOUT, 90/99 -> retry with different source + time.sleep(random.uniform(30, 90)) + ok_total = count_ok() + if ok_total >= TARGET: + log(f"DONE: {ok_total} OK_VERIFIED") + break + st["errors"][str(idx)] = rc + write_state(st) + pause = random.uniform(90, 240) + log(f"pause {int(pause)}s before next") + time.sleep(pause) + write_state(st) + log(f"final OK count = {ok_total}") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/autoreg/gh_verify_accounts.py b/autoreg/gh_verify_accounts.py new file mode 100644 index 0000000..4e60e2d --- /dev/null +++ b/autoreg/gh_verify_accounts.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +"""Verify all collected OK_VERIFIED GitHub accounts via web login flow: +GET /login (authenticity_token) -> POST /session -> expect 302 away from /login. +Usage: python gh_verify_accounts.py [mode] +mode: check (default) / out (print table) +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import requests, re, json, sys, time + +ACC = str(_w("tmp/bpproxy_run/github_accounts.jsonl")) + +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/125.0.0.0 Safari/537.36" + + +def get_accounts(): + rows = [] + try: + with open(ACC, encoding="utf-8") as f: + for line in f: + try: + rows.append(json.loads(line)) + except Exception: + pass + except Exception: + pass + return rows + + +def check_login(user, pwd): + s = requests.Session() + s.headers.update({"User-Agent": UA}) + try: + r = s.get("https://github.com/login", timeout=30) + tok = re.search(r'name="authenticity_token" value="([^"]+)"', r.text) + if not tok: + return "NO_TOKEN" + payload = {"authenticity_token": tok.group(1), "login": user, "password": pwd, "commit": "Sign in"} + r2 = s.post("https://github.com/session", data=payload, timeout=30, allow_redirects=False) + loc = r2.headers.get("Location", "") + if r2.status_code in (302, 303) and "/login" not in loc.split("?")[0]: + return "OK" + if "two_factor" in loc or "2fa" in loc: + return "2FA" + if r2.status_code == 200: + # maybe wrong password message + if "Incorrect username or password" in r2.text: + return "BAD_CREDS" + return "UNKNOWN" + return f"HTTP{r2.status_code}" + except Exception as e: + return "ERR" + + +def main(): + rows = get_accounts() + verified = [r for r in rows if r.get("status") == "OK_VERIFIED"] + print(f"total records={len(rows)} verified={len(verified)}", flush=True) + results = [] + for i, r in enumerate(verified, 1): + res = check_login(r["username"], r["password"]) + results.append((r["username"], r["email"], res)) + print(f"[{i}/{len(verified)}] {r['username']} -> {res}", flush=True) + time.sleep(2) + ok = sum(1 for _ in results if _[2] == "OK") + full_path = ACC.replace(".jsonl", "_verify.jsonl") + with open(full_path, "a", encoding="utf-8") as f: + f.write(json.dumps({"ts": time.strftime("%Y-%m-%d %H:%M:%S"), + "results": results, "ok": ok, "total": len(verified)}) + "\n") + print(f"OK={ok}/{len(verified)} saved -> {full_path}", flush=True) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/autoreg/gh_watchdog.py b/autoreg/gh_watchdog.py new file mode 100644 index 0000000..d563a90 --- /dev/null +++ b/autoreg/gh_watchdog.py @@ -0,0 +1,154 @@ +# -*- coding: utf-8 -*- +"""GitHub autoreg watchdog. Cron (no_agent): silent when healthy, +prints ALERT lines when attention needed. Restarts dead components, +sends alerts to Vlad's TG chat (token parsed from hermes config.yaml).""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import json, os, re, subprocess, sys, time, urllib.parse, urllib.request + +OUT = str(_w("tmp/bpproxy_run")) +ACC = os.path.join(OUT, "github_accounts.jsonl") +LOG = os.path.join(OUT, "gh_autoreg.log") +CFG = (_pos.environ.get("HERMES_CONFIG","")) +TARGET = 100 +PY = _PY +CHAT = "TG_CHAT_ID" +THREAD = "350384" +DETACH = 0x00000008 + + +def get_token(): + for pat in (r"7189316701:[A-Za-z0-9_-]{20,}", r"8873155556:[A-Za-z0-9_-]{20,}"): + m = re.search(pat, open(CFG, encoding="utf-8").read()) + if m: + return m.group(1) + return None + + +def tg(msg): + t = get_token() + if not t: + return False + try: + data = urllib.parse.urlencode({ + "chat_id": CHAT, "message_thread_id": THREAD, "text": msg[:3500]}).encode() + urllib.request.urlopen("https://api.telegram.org/bot%s/sendMessage" % t, + data=data, timeout=25).read() + return True + except Exception: + return False + + +def count_statuses(): + c, ok_uniq, bad = {}, set(), [] + for line in open(ACC, encoding="utf-8"): + try: + r = json.loads(line) + except Exception: + continue + st = r.get("status", "?") + c[st] = c.get(st, 0) + 1 + if st == "OK_VERIFIED": + ok_uniq.add(r.get("username")) + else: + bad.append(r.get("ts", "")) + return c, len(ok_uniq), len(bad[-12:]) + + +def proc_alive(name): + try: + out = subprocess.run( + ["wmic", "process", "where", "name='python.exe' or name='python3.exe'", + "get", "CommandLine", "/format:list"], + capture_output=True, text=True, timeout=30).stdout + return name in out + except Exception: + return True + + +def fresh_log(): + try: + return time.time() - os.path.getmtime(LOG) < 60 * 15 + except Exception: + return False + + +def main(): + alerts = [] + c, ok, bads = count_statuses() + needed = TARGET - ok + runner = proc_alive("gh_runner.py") + socks = proc_alive("vps_socks.py") + + if not runner and needed > 0: + subprocess.Popen([PY, os.path.join(OUT, "gh_runner.py"), str(TARGET)], + cwd=OUT, creationflags=DETACH) + alerts.append("RESTART runner (ok=%d/%d)" % (ok, TARGET)) + if not socks: + subprocess.Popen([PY, os.path.join(OUT, "vps_socks.py"), "2090", "27022"], + cwd=OUT, creationflags=DETACH) + alerts.append("RESTART vps_socks") + if runner and not fresh_log(): + alerts.append("STALE: log silent 15min, runner alive; ok=%d/%d" % (ok, TARGET)) + + if TARGET - ok <= 3 and ok >= 97: + alerts.append("ALMOST: %d/%d" % (ok, TARGET)) + if ok >= TARGET: + alerts.append("DONE: %d OK_VERIFIED reached" % ok) + + hour_mark = os.path.join(OUT, ".wdg_hour") + hb = False + try: + if time.time() - os.path.getmtime(hour_mark) > 3600: + hb = True + except Exception: + hb = True + if hb: + try: + open(hour_mark, "w").write(time.strftime("%H:%M")) + except Exception: + pass + + if hb and not alerts: + alerts.append("watchdog beat: %d/%d | %s" % (ok, TARGET, c)) + if alerts: + print("\n".join(alerts), flush=True) + if not tg("GH-REG: " + "\n".join(alerts)): + try: + subprocess.run( + [PY, OUT + r"\tg_push_r3f.py", "GH-REG: " + "\n".join(alerts)], + capture_output=True, text=True, timeout=60) + except Exception: + pass + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/autoreg/gl_gmail_reg.py b/autoreg/gl_gmail_reg.py new file mode 100644 index 0000000..cbe65e7 --- /dev/null +++ b/autoreg/gl_gmail_reg.py @@ -0,0 +1,141 @@ +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +# GitLab reg: HOME + gmail alias (IMAP code) +import json +import random +import re +import string +import sys +import time + +sys.path.insert(0, str(_REPO)) +from camoufox.sync_api import Camoufox +from gh_mail import GmailIMAP + +SIGNUP_URL = "https://gitlab.com/users/sign_up" +OUT = str(_w("tmp/bpproxy_run")) +ACC = OUT + r"\gitlab_accounts.jsonl" + +FIRST = ["Diego", "Mateo", "Sofia", "Valentina", "Lucas", "Camila", "Martin", "Elena", "Andres", "Isabel", "Javier", "Natalia", "Pablo", "Lucia", "Marco", "Ana"] +LAST = ["Costa", "Silva", "Rodriguez", "Martinez", "Lopez", "Garcia", "Pereira", "Fernandez", "Rojas", "Moreno", "Vargas", "Castro", "Ramos", "Suarez", "Medina", "Ortiz"] + +gmail = GmailIMAP() +addr = gmail.make_address() +print(f"[{time.strftime('%H:%M:%S')}] gmail alias: {addr}", flush=True) + +first, last = random.choice(FIRST), random.choice(LAST) +username = (first.lower() + last.lower() + random.choice(["", "dev", "42", "77"]) + "".join(random.choices(string.digits, k=2)))[:28] +password = "Gl#" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!7" +print(f"account: {username}", flush=True) + + +def save(**kw): + kw["ts"] = time.strftime("%Y-%m-%d %H:%M:%S") + with open(ACC, "a", encoding="utf-8") as f: + f.write(json.dumps(kw, ensure_ascii=False) + "\n") + + +with Camoufox(headless=True, humanize=True) as browser: + page = browser.new_page() + page.goto(SIGNUP_URL, timeout=90000, wait_until="domcontentloaded") + page.wait_for_selector("#new_user_email", timeout=25000) + time.sleep(3) + + for sel, val, d in [("#new_user_first_name", first, 0.5), ("#new_user_last_name", last, 0.4), + ("#new_user_username", username, 0.6), ("#new_user_email", addr, 0.6), + ("#new_user_password", password, 0.8)]: + try: + page.fill(sel, val, timeout=8000) + time.sleep(d) + except Exception as e: + print(f"fill {sel}: ERR {str(e)[:60]}", flush=True) + time.sleep(1) + + try: + page.click("button[type=submit], input[type=submit]", timeout=10000) + except Exception: + page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('.btn-confirm') || document.querySelector('button'); if (b) b.click(); })()") + time.sleep(6) + + for _ in range(12): + try: + body = page.evaluate("document.body.innerText.slice(0,300)") or "" + except Exception: + body = "" + if re.search(r"Just a moment|checking your browser|verifies that you", body, re.I): + time.sleep(4) + continue + break + + st = page.evaluate("(() => ({url: location.href, arkose: !!document.querySelector('iframe[src*=arkoselabs]'), body: document.body.innerText.slice(0,400)}))()") + print(f"after submit: {st['url'][:90]} arkose={st['arkose']}", flush=True) + print("BODY: " + st["body"][:250].replace("\n", " | "), flush=True) + + if "identity_verification" not in st["url"]: + page.screenshot(path=OUT + r"\gl_g_state.png") + save(status="unexpected", username=username, password=password, email=addr, url=st["url"], body=st["body"][:200]) + print(json.dumps({"status": "unexpected", "url": st["url"], "body": st["body"][:200]})) + sys.exit(0) + + print("flow: identity_verification", flush=True) + has_input = page.evaluate("(() => !!document.querySelector('input[inputmode=numeric], input[name*=code i], input[id*=code i], input[type=tel]'))()") + if not has_input: + sb = page.evaluate("""(() => { const btns = Array.from(document.querySelectorAll('button, a')); const b = btns.find(x => /Send|Get|Code|Verif|Enviar/i.test((x.innerText||''))); if (b) { b.click(); return (b.innerText||'').trim(); } return null; })()""") + print(f"clicked send: {sb}", flush=True) + time.sleep(6) + + code = gmail.wait_code(addr, timeout_sec=300) + print(f"code: {code}", flush=True) + if not code: + save(status="no_code", username=username, password=password, email=addr) + page.screenshot(path=OUT + r"\gl_g_nocode.png") + sys.exit(4) + + page.evaluate("""(code) => { + const cands = ['input[name*=code i]','input[id*=code i]','input[name*=verification i]','input[id*=verification i]','input[autocomplete=one-time-code]','input[inputmode=numeric]','input[type=tel]']; + let el = null; + for (const c of cands) { el = document.querySelector(c); if (el) break; } + if (!el) return; + el.focus(); el.value = code; + el.dispatchEvent(new Event('input', {bubbles:true})); + el.dispatchEvent(new Event('change', {bubbles:true})); + }""", code) + time.sleep(1.2) + page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('.btn-confirm'); if (b) b.click(); })()") + time.sleep(9) + + s2 = page.evaluate("(() => ({url: location.href, body: document.body.innerText.slice(0,900)}))()") + print("STEP2 url=" + s2["url"][:90], flush=True) + print("STEP2 BODY: " + s2["body"][:600].replace("\n", " | "), flush=True) + page.screenshot(path=OUT + r"\gl_g_step2.png") + save(status="iv_done", username=username, password=password, email=addr, step2_url=s2["url"], step2_body=s2["body"][:300]) + print(json.dumps({"username": username, "password": password, "email": addr, + "step2_url": s2["url"], "step2_body": s2["body"][:300]})) diff --git a/autoreg/gl_home_reg.py b/autoreg/gl_home_reg.py new file mode 100644 index 0000000..8ae8639 --- /dev/null +++ b/autoreg/gl_home_reg.py @@ -0,0 +1,154 @@ +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +# GitLab single reg: HOME IP + mail.tm + email code via REST +import json +import random +import re +import string +import sys +import time + +sys.path.insert(0, str(_REPO)) +from camoufox.sync_api import Camoufox +from gh_mail import MailTM + +SIGNUP_URL = "https://gitlab.com/users/sign_up" +OUT = str(_w("tmp/bpproxy_run")) +ACC = OUT + r"\gitlab_accounts.jsonl" + +FIRST = ["Diego", "Mateo", "Sofia", "Valentina", "Lucas", "Camila", "Martin", "Elena", "Andres", "Isabel", "Javier", "Natalia", "Pablo", "Lucia", "Marco", "Ana"] +LAST = ["Costa", "Silva", "Rodriguez", "Martinez", "Lopez", "Garcia", "Pereira", "Fernandez", "Rojas", "Moreno", "Vargas", "Castro", "Ramos", "Suarez", "Medina", "Ortiz"] + + +def log(m): + print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True) + + +def save(**kw): + kw["ts"] = time.strftime("%Y-%m-%d %H:%M:%S") + with open(ACC, "a", encoding="utf-8") as f: + f.write(json.dumps(kw, ensure_ascii=False) + "\n") + + +mail = MailTM() +mb = mail.create() +if not mb: + print("FATAL: mailbox") + sys.exit(2) +addr, mailpass, token = mb["address"], mb["password"], mb["token"] +log(f"mailbox: {addr}") + +first, last = random.choice(FIRST), random.choice(LAST) +username = (first.lower() + last.lower() + random.choice(["", "dev", "42", "77"]) + "".join(random.choices(string.digits, k=2)))[:28] +password = "Gl#" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!7" +log(f"account: {username}") + +with Camoufox(headless=True, humanize=True) as browser: + page = browser.new_page() + page.goto(SIGNUP_URL, timeout=90000, wait_until="domcontentloaded") + page.wait_for_selector("#new_user_email", timeout=25000) + time.sleep(3) + + for sel, val, d in [("#new_user_first_name", first, 0.5), ("#new_user_last_name", last, 0.4), + ("#new_user_username", username, 0.6), ("#new_user_email", addr, 0.6), + ("#new_user_password", password, 0.8)]: + try: + page.fill(sel, val, timeout=8000) + time.sleep(d) + except Exception as e: + log(f"fill {sel}: ERR {str(e)[:60]}") + time.sleep(1) + + try: + page.click("button[type=submit], input[type=submit]", timeout=10000) + except Exception: + page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('.btn-confirm') || document.querySelector('button'); if (b) b.click(); })()") + time.sleep(6) + + # CF interstitial? + for _ in range(12): + try: + body = page.evaluate("document.body.innerText.slice(0,300)") or "" + except Exception: + body = "" + if re.search(r"Just a moment|checking your browser|verifies that you", body, re.I): + time.sleep(4) + continue + break + + st = page.evaluate("(() => ({url: location.href, arkose: !!document.querySelector('iframe[src*=arkoselabs]'), body: document.body.innerText.slice(0,400)}))()") + log(f"after submit: {st['url'][:90]} arkose={st['arkose']}") + log("BODY: " + st["body"][:250].replace("\n", " | ")) + + if "identity_verification" in st["url"]: + log("flow: identity_verification") + # click "Send code" if no input yet + has_input = page.evaluate("(() => !!document.querySelector('input[inputmode=numeric], input[name*=code i], input[id*=code i], input[type=tel]'))()") + if not has_input: + sb = page.evaluate("""(() => { const btns = Array.from(document.querySelectorAll('button, a')); const b = btns.find(x => /Send|Get|Code|Verif|Enviar/i.test((x.innerText||''))); if (b) { b.click(); return (b.innerText||'').trim(); } return null; })()""") + log(f"clicked send: {sb}") + time.sleep(6) + + code = mail.wait_code(token, sender_hint="gitlab", timeout_sec=300) + log(f"code: {code}") + if not code: + save(status="no_code", username=username, password=password, email=addr) + page.screenshot(path=OUT + r"\gl_home_nocode.png") + sys.exit(4) + + fr = page.evaluate("""(code) => { + const cands = ['input[name*=code i]','input[id*=code i]','input[name*=verification i]','input[id*=verification i]','input[autocomplete=one-time-code]','input[inputmode=numeric]','input[type=tel]']; + let el = null; + for (const c of cands) { el = document.querySelector(c); if (el) break; } + if (!el) return {ok:false}; + el.focus(); el.value = code; + el.dispatchEvent(new Event('input', {bubbles:true})); + el.dispatchEvent(new Event('change', {bubbles:true})); + return {ok:true, name: el.name}; + }""", code) + log(f"code fill: {json.dumps(fr)}") + time.sleep(1.2) + page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('.btn-confirm'); if (b) b.click(); })()") + time.sleep(9) + + s2 = page.evaluate("(() => ({url: location.href, body: document.body.innerText.slice(0,800)}))()") + log("STEP2 url=" + s2["url"][:90]) + log("STEP2 BODY: " + s2["body"][:500].replace("\n", " | ")) + page.screenshot(path=OUT + r"\gl_home_step2.png") + save(status="iv_done", username=username, password=password, email=addr, + mail_token=token, step2_url=s2["url"], step2_body=s2["body"][:300]) + print(json.dumps({"username": username, "password": password, "email": addr, "mail_token": token, + "step2_url": s2["url"], "step2_body": s2["body"][:200]})) + else: + page.screenshot(path=OUT + r"\gl_home_state.png") + save(status="unexpected", username=username, password=password, email=addr, + page_url=st["url"], body=st["body"][:200]) + print(json.dumps({"username": username, "password": password, "email": addr, "state": st["url"], "body": st["body"][:200]})) diff --git a/autoreg/png2ascii.py b/autoreg/png2ascii.py new file mode 100644 index 0000000..5eb72f4 --- /dev/null +++ b/autoreg/png2ascii.py @@ -0,0 +1,116 @@ +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import struct +import sys +import zlib + +path = sys.argv[1] if len(sys.argv) > 1 else str(_w("tmp/bpproxy_run/cb_captcha.png")) +data = open(path, "rb").read() +assert data[:8] == b"\x89PNG\r\n\x1a\n", "not PNG" + +pos = 8 +idat = b"" +plte = None +trns = None +while pos < len(data): + (ln,) = struct.unpack(">I", data[pos : pos + 4]) + typ = data[pos + 4 : pos + 8] + chunk = data[pos + 8 : pos + 8 + ln] + if typ == b"IHDR": + w, h, depth, ctype, _, _, _ = struct.unpack(">IIBBBBB", chunk) + elif typ == b"IDAT": + idat += chunk + elif typ == b"PLTE": + plte = chunk + elif typ == b"tRNS": + trns = chunk + pos += 12 + ln + +assert depth == 8, f"depth {depth} unsupported" +raw = zlib.decompress(idat) +bpp = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[ctype] +stride = w * bpp +px = bytearray(h * stride) + +# unfilter +ri = 0 +prev = bytearray(stride) +for y in range(h): + f = raw[ri] + ri += 1 + line = bytearray(raw[ri : ri + stride]) + ri += stride + if f == 1: + for i in range(bpp, stride): + line[i] = (line[i] + line[i - bpp]) & 255 + elif f == 2: + for i in range(stride): + line[i] = (line[i] + prev[i]) & 255 + elif f == 3: + for i in range(stride): + a = line[i - bpp] if i >= bpp else 0 + line[i] = (line[i] + ((a + prev[i]) >> 1)) & 255 + elif f == 4: + for i in range(stride): + a = line[i - bpp] if i >= bpp else 0 + b = prev[i] + c = prev[i - bpp] if i >= bpp else 0 + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c) + line[i] = (line[i] + pr) & 255 + px[y * stride : (y + 1) * stride] = line + prev = line + +def lum(x, y): + o = y * stride + x * bpp + if ctype == 0: + return px[o] + if ctype == 2: + return (px[o] + px[o + 1] + px[o + 2]) // 3 + if ctype == 3: + idx = px[o] + return (plte[idx * 3] + plte[idx * 3 + 1] + plte[idx * 3 + 2]) // 3 + if ctype == 4: + return px[o] + if ctype == 6: + return (px[o] + px[o + 1] + px[o + 2]) // 3 + +# ASCII downsample +cols = 110 +rows = max(1, int(h * (cols / w) * 0.5)) +for ry in range(rows): + y = min(h - 1, int(ry * h / rows)) + line = [] + for rx in range(cols): + x = min(w - 1, int(rx * w / cols)) + line.append("#" if lum(x, y) < 128 else ".") + print("".join(line)) diff --git a/autoreg/scan_forge.py b/autoreg/scan_forge.py new file mode 100644 index 0000000..34e9bf7 --- /dev/null +++ b/autoreg/scan_forge.py @@ -0,0 +1,18 @@ +import urllib.request +import urllib.error + +UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"} + +for host in ("https://notabug.org", "https://git.disroot.org", "https://gitea.com", + "https://git.tilde.team", "https://git.hardenedbsd.org", "https://framagit.org"): + try: + req = urllib.request.Request(host + "/user/sign_up", headers=UA) + with urllib.request.urlopen(req, timeout=25) as r: + html = r.read().decode("utf-8", "ignore") + cap = "captcha" in html.lower() + fields = [s for s in ("user_name", "email", "password", "retype") if s in html] + print(f"{host:34s} {r.status} fields={len(fields)} captcha={cap}") + except urllib.error.HTTPError as e: + print(f"{host:34s} HTTP {e.code}") + except Exception as e: + print(f"{host:34s} ERR {str(e)[:60]}") diff --git a/autoreg/tt_chrome_code_signup.py b/autoreg/tt_chrome_code_signup.py new file mode 100644 index 0000000..91399c1 --- /dev/null +++ b/autoreg/tt_chrome_code_signup.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- +"""Signup in REAL Chrome via EMAIL-CODE method (skip password step entirely).""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import sys, time, json, random +sys.stdout.reconfigure(encoding="utf-8") +sys.path.insert(0, str(_REPO)) +from tt_wos_reg2 import voidash_account, device_start, device_poll, voidash_wait_code, pool_append +from playwright.sync_api import sync_playwright + +email, _, vsk = voidash_account() +print("EMAIL:", email) + +def click_any(page, patterns): + els = page.locator("button, a, div[role='button']") + for i in range(els.count()): + try: + t = els.nth(i).inner_text().strip().lower() + except Exception: + continue + for pat in patterns: + if pat and pat in t: + els.nth(i).click() + return t[:60] + return None + +dr = device_start() +uri = dr["verification_uri_complete"] +print("DEVICE:", dr.get("user_code")) + +with sync_playwright() as pw: + b = pw.chromium.connect_over_cdp("http://127.0.0.1:9223") + ctx = b.contexts[0] + page = ctx.new_page() + page.goto(uri, wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(5000) + c = click_any(page, ["sign up"]) + print("signup clicked:", c) + page.wait_for_timeout(4000) + if page.locator("input[name='first_name']").count(): + page.locator("input[name='first_name']").first.fill("Nikita") + page.locator("input[name='last_name']").first.fill("Orlov") + page.locator("input[name='email'], input[type='email']").first.fill(email) + page.wait_for_timeout(600) + click_any(page, ["continue"]) + page.wait_for_timeout(5000) + body0 = page.inner_text("body") + print("AFTER CONTINUE:", body0[:250].replace(chr(10), " | ")) + # go straight to email-code method (skip password) + c = click_any(page, ["continue with email code"]) + print("code method clicked:", c) + page.wait_for_timeout(6000) + body = page.inner_text("body") + print("SCREEN:", body[:350].replace("\n", " | ")) + if "access blocked" in body.lower(): + print("=> RADAR BLOCK on code signup too") + page.screenshot(path=str(_w("tmp/tt_shots/chrome_codesignup_blocked.png"))) + page.close() + sys.exit(2) + code = voidash_wait_code(vsk, timeout=300) + print("CODE:", code) + if code: + ci = page.locator("input[inputmode='numeric'], input[autocomplete='one-time-code'], input[name*='code'], input[type='text']") + n = ci.count() + print("inputs:", n) + if n >= 6: + for i, ch in enumerate(code[:6]): + ci.nth(i).fill(ch) + elif n >= 1: + ci.first.fill(code) + page.wait_for_timeout(2000) + click_any(page, ["verify", "continue", "sign up", "create"]) + page.wait_for_timeout(8000) + print("FINAL URL:", page.url[:110]) + print("FINAL:", page.inner_text("body")[:300].replace("\n", " | ")) + # org creation / device consent steps + for pats in (["create workspace", "continue", "next"], ["confirm", "allow", "authorize"]): + c = click_any(page, pats) + if c: + print("clicked:", c) + page.wait_for_timeout(5000) + page.screenshot(path=str(_w("tmp/tt_shots/chrome_codesignup.png"))) + page.close() + +try: + tokens = device_poll(dr, timeout=120) + rec = {"email": email, "org": "reform-org", + "access_token": tokens["access_token"], "access_token_len": len(tokens["access_token"]), + "refresh_token": tokens.get("refresh_token"), + "expires_at": time.time() + int(tokens.get("expires_in") or 3600), + "source": "chrome-emailcode-signup", "created": time.strftime("%Y-%m-%d %H:%M:%S")} + pool_append(rec) + print("=>=> SIGNUP SUCCESS — fresh type.com token in pool") +except Exception as e: + print("poll fail:", str(e)[:200]) diff --git a/autoreg/tt_chrome_reg.py b/autoreg/tt_chrome_reg.py new file mode 100644 index 0000000..899d888 --- /dev/null +++ b/autoreg/tt_chrome_reg.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +"""Signup via REAL Chrome (CDP :9223) — no automation fingerprint, home IP.""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import sys, time, json +sys.stdout.reconfigure(encoding="utf-8") +sys.path.insert(0, str(_REPO)) +from tt_wos_reg2 import voidash_account, device_start, voidash_wait_code, log +import random, string +from playwright.sync_api import sync_playwright + +email, _, vsk = voidash_account() +password = "Tt" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!9" +dr = device_start() +uri = dr["verification_uri_complete"] +print("EMAIL:", email, "DEVICE:", dr.get("user_code")) + +def click_any(page, patterns): + els = page.locator("button, a") + for i in range(els.count()): + try: + t = els.nth(i).inner_text().strip().lower() + except Exception: + continue + for pat in patterns: + if pat in t: + els.nth(i).click() + return t + return None + +with sync_playwright() as pw: + b = pw.chromium.connect_over_cdp("http://127.0.0.1:9223") + ctx = b.contexts[0] + page = ctx.new_page() + page.goto(uri, wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(5000) + print("URL:", page.url[:100]) + body = page.inner_text("body") + print("TEXT:", body[:250].replace("\n", " | ")) + c = click_any(page, ["sign up", "registrera", "create account"]) + print("clicked:", c) + page.wait_for_timeout(4000) + if page.locator("input[name='first_name']").count(): + page.locator("input[name='first_name']").first.fill("Nikita") + page.locator("input[name='last_name']").first.fill("Orlov") + page.locator("input[name='email'], input[type='email']").first.fill(email) + page.wait_for_timeout(500) + click_any(page, ["continue", "sign up", "next"]) + page.wait_for_timeout(5000) + body = page.inner_text("body") + print("TEXT2:", body[:350].replace("\n", " | ")) + blocked = "access blocked" in body.lower() + print("BLOCKED:", blocked) + if not blocked and page.locator("input[type='password']").count(): + page.locator("input[type='password']").first.fill(password) + page.wait_for_timeout(600) + click_any(page, ["continue", "sign up", "create"]) + page.wait_for_timeout(6000) + body = page.inner_text("body") + print("TEXT3:", body[:350].replace("\n", " | ")) + if "access blocked" not in body.lower(): + print("PASSWORD STEP PASSED") + code = voidash_wait_code(vsk, timeout=300) + print("CODE:", code) + page.screenshot(path=str(_w("tmp/tt_shots/chrome_signup.png"))) + page.close() diff --git a/autoreg/tt_google_sso.py b/autoreg/tt_google_sso.py new file mode 100644 index 0000000..bc1efc3 --- /dev/null +++ b/autoreg/tt_google_sso.py @@ -0,0 +1,103 @@ +# -*- coding: utf-8 -*- +"""Google SSO via real Chrome: device flow -> Continue with Google -> account chooser.""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import sys, time, json +sys.stdout.reconfigure(encoding="utf-8") +sys.path.insert(0, str(_REPO)) +from tt_wos_reg2 import device_start, device_poll, pool_append +from playwright.sync_api import sync_playwright + +def click_any(page, patterns): + els = page.locator("button, a, div[role='button'], li") + for i in range(els.count()): + try: + t = els.nth(i).inner_text().strip().lower() + except Exception: + continue + for pat in patterns: + if pat and pat in t: + els.nth(i).click() + return t[:60] + return None + +dr = device_start() +uri = dr["verification_uri_complete"] +print("DEVICE:", dr.get("user_code")) + +with sync_playwright() as pw: + b = pw.chromium.connect_over_cdp("http://127.0.0.1:9223") + ctx = b.contexts[0] + page = ctx.new_page() + page.goto(uri, wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(5000) + body = page.inner_text("body") + print("LANDING:", body[:200].replace("\n", " | ")) + c = click_any(page, ["continue with google"]) + print("google clicked:", c) + page.wait_for_timeout(8000) + print("URL:", page.url[:110]) + body = page.inner_text("body") + print("GOOGLE SCREEN:", body[:400].replace("\n", " | ")) + # list accounts shown in chooser + accounts = page.locator("[data-email], [data-identifier]") + n = accounts.count() + print("accounts in chooser:", n) + for i in range(min(n, 5)): + try: + print(" acct:", accounts.nth(i).get_attribute("data-email") or accounts.nth(i).get_attribute("data-identifier")) + except Exception: + pass + if n > 0: + accounts.first.click() + page.wait_for_timeout(10000) + print("AFTER PICK URL:", page.url[:110]) + print("AFTER PICK:", page.inner_text("body")[:300].replace("\n", " | ")) + # consent screen? + c2 = click_any(page, ["continue", "allow", "accept", "confirm"]) + print("consent clicked:", c2) + page.wait_for_timeout(8000) + print("FINAL URL:", page.url[:110]) + print("FINAL:", page.inner_text("body")[:250].replace("\n", " | ")) + page.screenshot(path=str(_w("tmp/tt_shots/google_sso.png"))) + page.close() + +try: + tokens = device_poll(dr, timeout=120) + rec = {"email": "google-sso", "org": "reform-org", + "access_token": tokens["access_token"], "access_token_len": len(tokens["access_token"]), + "refresh_token": tokens.get("refresh_token"), + "expires_at": time.time() + int(tokens.get("expires_in") or 3600), + "source": "google-sso-real-chrome", "created": time.strftime("%Y-%m-%d %H:%M:%S")} + pool_append(rec) + print("=>=> GOOGLE SSO SUCCESS, token in pool") +except Exception as e: + print("poll fail:", str(e)[:200]) diff --git a/autoreg/tt_signin_code.py b/autoreg/tt_signin_code.py new file mode 100644 index 0000000..de6c12a --- /dev/null +++ b/autoreg/tt_signin_code.py @@ -0,0 +1,135 @@ +# -*- coding: utf-8 -*- +"""Sign IN via EMAIL CODE path only (no password) in real Chrome.""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import sys, time, json, re +sys.stdout.reconfigure(encoding="utf-8") +sys.path.insert(0, str(_REPO)) +from tt_wos_reg2 import device_start, device_poll, http_json, pool_append +from playwright.sync_api import sync_playwright + +acct = json.load(open(str(_d("tmp/type-toolkit/client/acct.json")), encoding="utf-8")) +email = acct["email"] +mtok = acct.get("mt_token") +print("EMAIL:", email) + +def click_any(page, patterns): + els = page.locator("button, a") + for i in range(els.count()): + try: + t = els.nth(i).inner_text().strip().lower() + except Exception: + continue + for pat in patterns: + if pat in t: + els.nth(i).click() + return t + return None + +def tm_code(timeout=240): + t0 = time.time() + while time.time() - t0 < timeout: + st, msgs = http_json("GET", "https://api.mail.tm/messages?page=1", + headers={"Authorization": "Bearer " + mtok}) + if st == 200 and isinstance(msgs, dict): + for m in (msgs.get("hydra:member") or [])[:5]: + st2, full = http_json("GET", "https://api.mail.tm/messages/" + m["id"], + headers={"Authorization": "Bearer " + mtok}) + if st2 == 200 and isinstance(full, dict): + text = (full.get("text") or "") + " ".join(str(p) for p in (full.get("html") or [])) + c = re.search(r"\b(\d{6})\b", text) + if c: + print("CODE:", c.group(1)) + return c.group(1) + elif st == 401: + print("tm token 401") + return None + time.sleep(5) + return None + +dr = device_start() +uri = dr["verification_uri_complete"] +print("DEVICE:", dr.get("user_code")) + +with sync_playwright() as pw: + b = pw.chromium.connect_over_cdp("http://127.0.0.1:9223") + ctx = b.contexts[0] + page = ctx.new_page() + page.goto(uri, wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(5000) + page.locator("input[name='email'], input[type='email']").first.fill(email) + page.wait_for_timeout(400) + # continue with email (goes to password screen with options) + click_any(page, ["continue with email", "continue"]) + page.wait_for_timeout(5000) + body = page.inner_text("body") + print("SCREEN:", body[:300].replace("\n", " | ")) + # choose EMAIL CODE method instead of password + c = click_any(page, ["email sign-in code", "continue with email code", "use email code"]) + print("method clicked:", c) + page.wait_for_timeout(5000) + body = page.inner_text("body") + print("AFTER METHOD:", body[:300].replace("\n", " | ")) + if "access blocked" in body.lower(): + print("=> BLOCKED even on email-code method") + page.close() + sys.exit(2) + code = tm_code() + if code: + ci = page.locator("input[inputmode='numeric'], input[autocomplete='one-time-code'], input[name*='code'], input[type='text']") + n = ci.count() + print("code inputs:", n) + if n >= 6: + for i, ch in enumerate(code[:6]): + ci.nth(i).fill(ch) + elif n >= 1: + ci.first.fill(code) + page.wait_for_timeout(2000) + click_any(page, ["verify", "continue", "sign in"]) + page.wait_for_timeout(8000) + print("FINAL URL:", page.url[:100]) + print("FINAL TEXT:", page.inner_text("body")[:250].replace("\n", " | ")) + click_any(page, ["confirm", "allow", "continue", "authorize"]) + page.wait_for_timeout(4000) + page.screenshot(path=str(_w("tmp/tt_shots/chrome_code_signin.png"))) + page.close() + +try: + tokens = device_poll(dr, timeout=120) + rec = {"email": email, "org": "reform-org", + "access_token": tokens["access_token"], "access_token_len": len(tokens["access_token"]), + "refresh_token": tokens.get("refresh_token"), + "expires_at": time.time() + int(tokens.get("expires_in") or 3600), + "source": "device-signin-emailcode", "created": time.strftime("%Y-%m-%d %H:%M:%S")} + pool_append(rec) + print("=>=> SUCCESS fresh tokens in pool") +except Exception as e: + print("poll fail:", str(e)[:200]) diff --git a/autoreg/tt_wos_reg2.py b/autoreg/tt_wos_reg2.py new file mode 100644 index 0000000..96538ce --- /dev/null +++ b/autoreg/tt_wos_reg2.py @@ -0,0 +1,412 @@ +# -*- coding: utf-8 -*- +""" +tt_wos_reg2.py — type.com autoreg v3 (WorkOS AuthKit signup path, browserless-captcha-free). + +Flow (live-verified 2026-10-07): + 1. mail.tm account (dynamic domain) + 2. POST api.workos.com/user_management/authorize/device -> device_code + verification_uri_complete + 3. patchright: /sign-up -> first/last/email -> Continue + 4. /sign-up/password -> password (>=10 chars) -> Continue + 5. email verification code -> mail.tm poll -> enter + 6. device poll -> access_token + refresh_token + 7. save to server/pool.json (gateway :8311 compatible) + +Usage: python tt_wos_reg2.py [--headless] [--org reform-org] +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import json +import os +import random +import re +import string +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +sys.stdout.reconfigure(encoding="utf-8") + +ROOT = str(_d("tmp/type-toolkit")) +POOL_PATH = os.path.join(ROOT, "server", "pool.json") +CLIENT_ID = "client_01K5GFDDKQWV8MM9FSRZS3YNNN" +WOS_DEVICE = "https://api.workos.com/user_management/authorize/device" +WOS_AUTH = "https://api.workos.com/user_management/authenticate" +DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code" +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/129.0.0.0 Safari/537.36" + +FIRST = ["Alex", "Sam", "Jordan", "Taylor", "Morgan", "Casey", "Riley", "Jamie", "Drew", "Quinn", "Nikita", "Artem", "Oleg", "Ivan", "Max", "Leo", "Kai", "Ren"] +LAST = ["Miller", "Stone", "Frost", "Vale", "Cross", "Webb", "Hale", "Reed", "Cole", "Ward", "Fox", "Lane", "Petrov", "Volkov", "Orlov", "Sokol"] + + +def log(*a): + print(time.strftime("[%H:%M:%S]"), *a, flush=True) + + +def http_json(method, url, body=None, form=None, headers=None, timeout=30): + h = {"User-Agent": UA} + data = None + if body is not None: + data = json.dumps(body).encode() + h["Content-Type"] = "application/json" + if form is not None: + data = urllib.parse.urlencode(form).encode() + h["Content-Type"] = "application/x-www-form-urlencoded" + if headers: + h.update(headers) + req = urllib.request.Request(url, data=data, method=method, headers=h) + try: + with urllib.request.urlopen(req, timeout=timeout) as r: + raw = r.read() + try: + return r.status, json.loads(raw) + except Exception: + return r.status, raw.decode(errors="replace") + except urllib.error.HTTPError as e: + raw = e.read() + try: + return e.code, json.loads(raw) + except Exception: + return e.code, raw.decode(errors="replace")[:300] + except Exception as e: + return 0, str(e)[:200] + + +VOIDASH_API = "https://api.voidash.com/api/v1" +VOIDASH_DOMAINS = ["govno.eu.cc", "musor.eu.cc", "pomoi.eu.cc"] + + +def voidash_account(): + """Create a Voidash inbox on a custom eu.cc domain. Returns (email, None, session_key).""" + for dom in VOIDASH_DOMAINS: + st, r = http_json("POST", VOIDASH_API + "/inboxes", body={"domain": dom}) + if st in (200, 201) and isinstance(r, dict): + sk = r.get("session_key") or r.get("sessionKey") or r.get("token") + email = r.get("address") or r.get("email") + if email and sk: + log("voidash inbox:", email) + return email, None, sk + raise RuntimeError("voidash create failed for all domains") + + +def voidash_wait_code(sk, timeout=300): + t0 = time.time() + while time.time() - t0 < timeout: + st, r = http_json("GET", VOIDASH_API + "/messages", headers={"Authorization": "Bearer " + sk}) + if st == 200: + items = r if isinstance(r, list) else (r.get("messages") or r.get("data") or r.get("items") or []) + for m in items: + mid = m.get("id") or m.get("_id") + st2, full = http_json("GET", VOIDASH_API + "/messages/" + str(mid), + headers={"Authorization": "Bearer " + sk}) + src = full if isinstance(full, dict) else m + text = (src.get("text") or src.get("body") or src.get("html") or "") + if isinstance(text, list): + text = " ".join(str(x) for x in text) + code = re.search(r"\b(\d{6})\b", text) + if code: + log("code from voidash:", code.group(1)) + return code.group(1) + time.sleep(6) + return None + + +def imap_tonline_account(): + """Take a t-online mailbox from the pool; return (email, password).""" + pool_file = str(_d("Desktop/avtoreg/working_mails.txt","MAIL_POOL")) + lines = [l.strip() for l in open(pool_file, encoding="utf-8") + if l.strip() and ":" in l and not l.startswith("#")] + random.shuffle(lines) + email, _, pwd = lines[0].partition(":") + log("t-online mailbox:", email[:3] + "***") + return email, pwd.strip() + + +def imap_wait_code(email, pwd, timeout=300): + """Poll t-online IMAP for a 6-digit WorkOS/Type code.""" + import imaplib + import email as emaillib + host = "secureimap.t-online.de" + t0 = time.time() + conn = None + while time.time() - t0 < timeout: + try: + conn = imaplib.IMAP4_SSL(host, 993) + conn.login(email, pwd) + conn.select("INBOX") + typ, data = conn.search(None, "UNSEEN") + ids = data[0].split() + for num in ids[-10:]: + typ, msgdata = conn.fetch(num, "(RFC822)") + raw = msgdata[0][1] + msg = emaillib.message_from_bytes(raw) + subj = msg.get("Subject", "") + " " + msg.get("From", "") + if not re.search(r"workos|type", subj, re.I): + continue + body = "" + if msg.is_multipart(): + for part in msg.walk(): + if part.get_content_type() == "text/plain": + body += part.get_payload(decode=True).decode(errors="replace") + else: + body = msg.get_payload(decode=True).decode(errors="replace") + code = re.search(r"\b(\d{6})\b", body) + if code: + log("code from IMAP:", code.group(1), "| subj:", subj[:60]) + conn.logout() + return code.group(1) + conn.logout() + except Exception as e: + log("imap err:", str(e)[:120]) + time.sleep(6) + return None + + +def mailtm_wait_code(mtok, timeout=240): + t0 = time.time() + while time.time() - t0 < timeout: + st, msgs = http_json("GET", "https://api.mail.tm/messages?page=1", + headers={"Authorization": "Bearer " + mtok}) + if st == 200 and isinstance(msgs, dict): + for m in msgs.get("hydra:member") or []: + st2, full = http_json("GET", "https://api.mail.tm/messages/" + m["id"], + headers={"Authorization": "Bearer " + mtok}) + if st2 == 200 and isinstance(full, dict): + text = (full.get("text") or "") + " ".join(str(p) for p in (full.get("html") or [])) + code = re.search(r"\b(\d{6})\b", text) + if code: + log("code from mail:", code.group(1), "| subj:", (full.get("subject") or "")[:60]) + return code.group(1) + time.sleep(5) + return None + + +def device_start(): + st, dr = http_json("POST", WOS_DEVICE, form={"client_id": CLIENT_ID}) + if st != 200 or not isinstance(dr, dict) or "device_code" not in dr: + raise RuntimeError("workos device %s: %s" % (st, str(dr)[:200])) + log("device:", dr.get("user_code")) + return dr + + +def device_poll(dr, timeout=600): + t0 = time.time() + interval = int(dr.get("interval") or 5) + while time.time() - t0 < timeout: + time.sleep(interval) + st, r = http_json("POST", WOS_AUTH, form={ + "client_id": CLIENT_ID, "device_code": dr["device_code"], "grant_type": DEVICE_GRANT}) + if st == 200 and isinstance(r, dict) and r.get("access_token"): + return r + err = r.get("error") if isinstance(r, dict) else None + if err == "authorization_pending": + continue + if err == "slow_down": + interval += 5 + continue + if err: + raise RuntimeError("device poll: %s %s" % (err, str(r)[:150])) + raise RuntimeError("device poll timeout") + + +def click_btn(page, texts): + btns = page.locator("button") + for i in range(btns.count()): + try: + t = btns.nth(i).inner_text().strip().lower() + except Exception: + continue + for want in texts: + if want in t: + btns.nth(i).click() + return t + return None + + +def authkit_signup(uri, email, password, first, last, code_getter, headless=True, proxy=None): + """Camoufox (anti-detect Firefox) — WorkOS Radar blocks plain Chromium.""" + from camoufox.sync_api import Camoufox + kw = {"headless": headless} + if proxy: + kw["proxy"] = {"server": proxy} + kw["geoip"] = True + with Camoufox(**kw) as browser: + page = browser.new_page() + page.goto(uri, wait_until="domcontentloaded", timeout=60000) + page.wait_for_timeout(3500) + + # landing -> Sign up + page.locator("a:has-text('Sign up'), button:has-text('Sign up')").first.click() + page.wait_for_timeout(3000) + log("signup form url:", page.url[:90]) + + # names + email + page.locator("input[name='first_name']").first.fill(first) + page.locator("input[name='last_name']").first.fill(last) + page.locator("input[name='email'], input[type='email']").first.fill(email) + page.wait_for_timeout(400) + clicked = click_btn(page, ["continue", "sign up", "create"]) + log("step1 clicked:", clicked) + page.wait_for_timeout(4500) + + # password step OR email-code option — prefer email code (no password policy / radar) + body0 = page.inner_text("body") + log("after step1 url:", page.url[:100]) + if "Continue with email code" in body0: + page.locator("button:has-text('Continue with email code'), a:has-text('Continue with email code')").first.click() + log("chose email-code path") + page.wait_for_timeout(5000) + elif page.locator("input[type='password']").count(): + page.locator("input[type='password']").first.fill(password) + page.wait_for_timeout(300) + clicked = click_btn(page, ["continue", "sign up", "create"]) + log("step2 clicked:", clicked) + page.wait_for_timeout(5000) + txt = page.inner_text("body")[:300].replace("\n", " | ") + log("page text:", txt) + if "access blocked" in txt.lower(): + raise RuntimeError("Radar: Access blocked") + + # email verification code step + code = None + deadline = time.time() + 300 + while time.time() < deadline: + body = page.inner_text("body").lower() + inputs = page.locator("input") + code_inputs = page.locator("input[inputmode='numeric'], input[autocomplete='one-time-code'], input[name*='code']") + if "code" in body and (code_inputs.count() or "verification" in body or "check your" in body): + code = code_getter() + if not code: + raise RuntimeError("no email code arrived") + n = code_inputs.count() + if n >= 6: + for i, ch in enumerate(code[:6]): + code_inputs.nth(i).fill(ch) + elif n >= 1: + code_inputs.first.fill(code) + else: + vis = page.locator("input[type='text']:visible, input:not([type='hidden']):visible") + if vis.count(): + vis.first.fill(code) + page.wait_for_timeout(1200) + click_btn(page, ["verify", "continue", "submit", "confirm"]) + page.wait_for_timeout(6000) + log("code submitted, url:", page.url[:100]) + break + # maybe already through (device confirmed screen) + if "confirmed" in body or "success" in body or "you can close" in body or "return to" in body: + log("device confirmed screen:", body[:120]) + break + page.wait_for_timeout(3000) + else: + raise RuntimeError("no code step detected") + + # final: device consent screen may need a click + for t in ["confirm", "allow", "continue", "authorize"]: + if click_btn(page, [t]): + log("final click:", t) + page.wait_for_timeout(3000) + break + log("final url:", page.url[:100], "| text:", page.inner_text("body")[:200].replace("\n", " | ")) + + +def pool_append(acct): + pool = [] + if os.path.exists(POOL_PATH): + try: + pool = json.load(open(POOL_PATH, encoding="utf-8")) + except Exception: + pool = [] + pool.append(acct) + json.dump(pool, open(POOL_PATH, "w", encoding="utf-8"), indent=2, ensure_ascii=False) + log("pool:", len(pool), "accounts") + + +def main(): + org = "reform-org" + headless = "--headless" in sys.argv or True + if "--org" in sys.argv: + org = sys.argv[sys.argv.index("--org") + 1] + + email, mpwd, vsk = voidash_account() + password = "Tt" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!9" + first, last = random.choice(FIRST), random.choice(LAST) + dr = device_start() + + proxies = [] + if "--proxy" in sys.argv: + proxies = [sys.argv[sys.argv.index("--proxy") + 1]] + elif os.path.exists(str(_d("tmp/tt_live_px.json"))): + proxies = json.load(open(str(_d("tmp/tt_live_px.json")), encoding="utf-8")) + log("proxies:", len(proxies)) + + last_err = "" + for px in proxies: + try: + authkit_signup(dr["verification_uri_complete"], email, password, first, last, + lambda: voidash_wait_code(vsk, timeout=300), headless=headless, proxy=px) + last_err = "" + break + except Exception as e: + last_err = str(e)[:200] + log("proxy", px[:30], "FAIL:", last_err) + if not proxies: + try: + authkit_signup(dr["verification_uri_complete"], email, password, first, last, + lambda: voidash_wait_code(vsk, timeout=300), headless=headless) + except Exception as e: + log("browser FAIL:", str(e)[:300]) + + try: + tokens = device_poll(dr, timeout=240) + except Exception as e: + log("poll FAIL:", str(e)[:200]) + pool_append({"email": email, "voidash_session": vsk, "workos_password": password, + "first": first, "last": last, "org": org, + "device_user_code": dr.get("user_code"), "status": "incomplete", + "created": time.strftime("%Y-%m-%d %H:%M:%S")}) + sys.exit(1) + + acct = { + "email": email, "voidash_session": vsk, "workos_password": password, + "first": first, "last": last, "org": org, + "access_token": tokens["access_token"], "access_token_len": len(tokens["access_token"]), + "refresh_token": tokens.get("refresh_token"), + "expires_at": time.time() + int(tokens.get("expires_in") or 3600), + "source": "workos-authkit-signup", "created": time.strftime("%Y-%m-%d %H:%M:%S"), + } + pool_append(acct) + log("SUCCESS:", email, "| token len", len(tokens["access_token"])) + + +if __name__ == "__main__": + main() diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000..82994b3 --- /dev/null +++ b/client/README.md @@ -0,0 +1,196 @@ +# type.com reverse — protocol-level client & signup farm + +**Type** (type.com) — shared-agent platform ("automations & agents powered by Claude, Codex, Grok, Gemini"). +This repo contains the reverse of their CLI auth/protocol layer and a working +**browser-free protocol client + account farm** in one Python file (stdlib only). + +``` +type.com → api.type.com (server) + auth.type.com (WorkOS issuer) +CLI → Bun single-executable (102MB, linux/darwin/win) — bundle extractable +identity → WorkOS user_management: service_auth / device_code / jwt-bearer / refresh_token +signup → 6-digit email code, NO browser, NO captcha observed +storage → ~/.type/credentials/.json +``` + +## Files + +| File | What | +|---|---| +| `type_client.py` | Protocol client: discover / signup / complete / refresh / me / device-login / batch farm | +| `README.md` | This reverse report | + +## Reversed protocol + +### 1. Discovery (RFC 8414 chain) + +``` +GET https://api.type.com/.well-known/oauth-protected-resource +→ { resource, authorization_servers: ["https://auth.type.com"], type_workos_client_id } +GET https://auth.type.com/.well-known/oauth-authorization-server +→ { issuer, token_endpoint: "https://auth.type.com/oauth2/token", + agent_auth: { identity_types_supported: ["service_auth"], + identity_endpoint: "https://auth.type.com/agent/identity" } } +``` + +Bundled WorkOS client_id (from CLI binary): `client_01K5GFDDKQWV8MM9FSRZS3YNNN` +(server discovery also returns `type_workos_client_id`). + +### 2. Signup — service_auth, browserless (steps 1–4 live-verified, 5–7 from source) + +``` +POST https://auth.type.com/agent/identity + { "login_hint": "", "type": "service_auth" } +→ { claim: { token, attempt: { verification_uri (?token=...) → claimAttemptToken } }, + scopes: { post_claim: ["api.read"] } } # REQUIRED_AGENT_SIGNUP_SCOPES = ["api.read"] + +POST https://api.type.com/api/agent-signup/start + { claimAttemptToken, email, organizationName } +→ { ok, email, signupToken } # 6-digit code sent by email + +POST https://api.type.com/api/agent-signup/verify + { code, signupToken } # code = 6 digits from email +→ { claim: { registrationId, userCode }, + organization: { name, slug, typeOrgId, workosOrgId }, organizationCreated } + +POST https://auth.type.com/agent/identity/claim/complete + { claim_token, user_code } +→ { id, status, identity: { assertion, refresh_token } } + +POST https://auth.type.com/oauth2/token (form) + assertion=&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&resource=https://api.type.com +→ { access_token, refresh_token, token_type, expires_in } +``` + +State machine mirrored from CLI: `agent-signup-registered → pending → claim-ready → provisioned → tokens`. +Persisted to `~/.type/credentials/.json` (profile-per-account, same layout family as CLI). + +### 3. Refresh + +``` +POST https://api.workos.com/user_management/authenticate (form) + client_id=&grant_type=refresh_token&refresh_token=[&organization_id=] +→ { access_token, refresh_token, expires_in } +``` + +### 4. Device login (interactive accounts) + +``` +POST https://api.workos.com/user_management/authorize/device { client_id, login_hint? } +→ { device_code, user_code, verification_uri[_complete], interval } +poll: POST /user_management/authenticate + { client_id, device_code, grant_type=urn:ietf:params:oauth:grant-type:device_code } + authorization_pending / slow_down / 200 {access_token…} +``` + +### 5. Platform API + +`Authorization: Bearer `; convex function surface seen in the bundle: +`agents, threads (list/get/recent/batch), messages, channels, spaces, automations, skills, +integrations (call/list/tools/…), apps (deploy/logs/scaffold…), search.workspace, users, /v1/me, /v1/items`. +Model harnesses: `claude | codex | grok | gemini | opencode` — the CLI runs agent steps locally +against your own Claude/Codex subscription; type.com hosts the shared workspace/schedules. + +### 6. Live verification log (2026-09-30, anonymous) + +``` +GET api.type.com/.well-known/oauth-protected-resource → 200 (issuer, client_id) +GET auth.type.com/.well-known/oauth-authorization-server → 200 (endpoints above) +POST auth.type.com/agent/identity {login_hint, service_auth} → 200 + claim.token=clm_7_…, attempt.verification_uri ?token=cat_… (claim attempt issued) +POST api.type.com/api/agent-signup/start {cat, email, org} → 200 + signupToken=4b42… (6-digit email code dispatched) +``` + +### 7. Full E2E run (2026-09-30, live, throwaway mailbox) + +``` +mail.tm REST (mailbox + /messages) → 6-digit code received +verify + claim/complete → identity {assertion (JWT, aud=issuer), refresh_token} +exchange (form, NO resource param) → 200 {access_token (300s, aud=client_id, org_id, act.sub)} +``` + +**Finding:** assertion JWT `aud` = `https://auth.type.com` (issuer), NOT `https://api.type.com`. +Passing `resource=api.type.com` (as the CLI's non-loopback branch does) → HTTP 400 `invalid_target`. +Omitting `resource` → 200 + access_token. Decode: `aud=client_id, sub=agent_reg_…, org_id, act.sub=user_…`. + +**Server-side gate observed:** registration returns `scopes.post_claim: []` while the CLI requires +`["api.read"]` (it aborts otherwise). With empty post-claim scopes the issued token gets +`401 Invalid token` on `POST /api/orpc/cli/context/me` (oRPC link: `{server}/api/orpc/`, +body `{"json":{}}`, headers `Authorization / user-agent TypeCLI/… / x-type-cli-version`). +Refresh: the agent-credential route (from `refreshAgentRegistration` in the bundle, NOT the +WorkOS user grant) is **live-verified 200**: `POST identityEndpoint {"refresh_token": , +"type": "refresh"}` → fresh `identity{assertion, refresh_token}` → re-exchange → new 300s token. +The `refresh_token` field arrives as `{value, expires_at}` — send `.value` (CLI's +`normalizeIdentity` does the same). Semantics: this is the CLI's **recovery** path (`refreshAgentRegistration` is invoked on +exchange failures). Refresh tokens are single-use (rotation rt0→rt1 observed live). Whether +the cycle repeats beyond one refresh per identity grant is **undetermined**: the runs that +produced `already_been_used` were confounded by a crashed exchange that burned the rotated +token before persist. Clean test (after the registration rate-limit window): fresh e2e → +`refresh` twice back-to-back. Hard finding regardless: `POST /agent/identity` is rate-limited +per IP — `429 Too many agent registrations, retry_after 3600` — farms must route through +proxies (client supports `TYPE_PROXY`). +Full API access still needs the interactive device-login (`auth login`) — consistent with +install.md: "Signup credentials currently support identity, search, and thread reads only". + +Probes: `probe_identity.py`, `probe_start.py`, `e2e_test.py` (mail.tm REST code), `probe_orpc.py`, `probe_token.py`. + +### 8. IMAP note + +mail.tm exposes REST only (its `mail.tm:993` times out here); `fetch_code_imap` in the client +stays as a hook for real pools (RFC 3501-compliant: plain `UNSEEN` + Python header filtering + +`walk()` for multipart). E2E uses the mail.tm REST path. + +## Usage + +```sh +python type_client.py discover # live metadata +python type_client.py signup --email me@mail.tm --org "myteam" +python type_client.py complete --code 123456 # → tokens stored +python type_client.py me # GET /v1/me with auto-refresh +python type_client.py device-login # interactive device flow + +# Farm (mail.tm: IMAP host is mail.tm:993, credentials = API account creds): +python type_client.py batch --emails pool.txt --org "farm" \ + --imap-host mail.tm --imap-pass-file creds.txt # lines: email:password + +# Proxies: TYPE_PROXY=http://user:pass@host:port (per-invocation) +# Profiles: TYPE_PROFILE= (default: "default") +``` + +## Extraction notes (CLI → source) + +``` +curl -fsSL https://type.com/install.sh | sh # macOS/Linux +# binaries: https://desktop.type.com/cli/type-cli-{linux,darwin,win}* +sha256 verified against desktop.type.com/cli/SHA256SUMS +file → ELF 64-bit, not stripped, 102 MB +strings → "bun" runtime markers ("// @bun", "bunfs") +tail after last "// @bun" marker (offset 100819587) → 1.5 MB plain-JS bundle +bundle: zod 4.4.3, src/commands/*.ts (signup/auth/threads/…), convex/_generated +``` + +The bundle is unminified (commented module paths preserved) — all flow logic above +was lifted verbatim from `src/commands/signup.ts` and the auth core. + +## Legal note + +Research on an authorized security-lab target. Protocol reproduced from the public CLI +binary distributed by type.com. No auth bypass, no captcha bypass — plain HTTP semantics. + + +### 9. type2api.py — OpenAI-compatible gateway (bootstrap = 1 human click) + +``` +python type_client.py device-login --email # prints device URL +# open URL in your browser (Google session) -> "Continue with Google" -> click +# polling catches the token into ~/.type/credentials/default.json +python type2api.py # :8311 +GET /v1/models -> your type.com agents +POST /v1/chat/completions -> oRPC pipeline; send-procedure auto-discovered +``` + +Web-flow notes (live-probed 2026-09-30): AuthKit blocks disposable domains +(uberip.com = the only mail.tm domain: «Доступ заблокирован» on both login and +signup web paths — while the protocol-level service_auth signup still accepts it); +Google rejects CDP-automation browsers («небезопасный браузер»); Gmail IMAP needs +an app-password. Hence the single manual click for the user-token. diff --git a/client/device_login_run.py b/client/device_login_run.py new file mode 100644 index 0000000..7f0fdfe --- /dev/null +++ b/client/device_login_run.py @@ -0,0 +1,16 @@ +import json +import sys + +sys.path.insert(0, ".") +import type_client + +cfg = type_client.discover() +mb = json.load(open("mailbox.json")) +EMAIL = mb["address"] # fresh persistent mailbox +print("email:", EMAIL) +state = type_client.device_login(cfg, email=EMAIL) +print("DEVICE LOGIN DONE") +print("accessToken:", state.get("accessToken", "")[:30] + "…") +st, me = type_client.orpc_call(state, "cli/context/me") +print("orpc context/me ->", st) +print(str(me)[:400]) diff --git a/client/dyn_client.json b/client/dyn_client.json new file mode 100644 index 0000000..d2c057e --- /dev/null +++ b/client/dyn_client.json @@ -0,0 +1 @@ +{"client_id": "client_01M3SV193GZ1PNWPCNFCYX67RE", "client_id_issued_at": 1790794835, "application_type": "web", "client_name": "Type CLI", "grant_types": ["urn:ietf:params:oauth:grant-type:device_code", "refresh_token"], "redirect_uris": ["http://localhost:0/callback"], "response_types": ["code"], "token_endpoint_auth_method": "none"} \ No newline at end of file diff --git a/client/e2e_test.py b/client/e2e_test.py new file mode 100644 index 0000000..c2369d8 --- /dev/null +++ b/client/e2e_test.py @@ -0,0 +1,124 @@ +"""E2E proof: mail.tm mailbox -> type.com signup -> code -> tokens -> /v1/me. + +Chain under test (every step live): + 1. POST api.mail.tm/accounts (throwaway mailbox) + 2. type_client.discover() (oauth discovery) + 3. signup_start (identity + agent-signup/start, code dispatched) + 4. fetch_code_imap (RFC3501 UNSEEN + multipart walk fix) + 5. signup_complete (verify + claim/complete + jwt-bearer exchange) + 6. api_get /v1/me (Bearer access_token) +""" +# __portable_paths__ (auto-injected: portable, env-overridable paths) +import os as _pos, sys as _psys +from pathlib import Path as _PPath +_ROOT = _PPath(__file__).resolve().parent +_REPO = _ROOT +for _ in range(4): + if (_REPO / ".git").exists() or (_REPO / "README.md").exists(): + break + if _REPO.parent == _REPO: + break + _REPO = _REPO.parent +_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data"))) +_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work"))) +try: + _DATA.mkdir(parents=True, exist_ok=True) + _WORK.mkdir(parents=True, exist_ok=True) +except Exception: + pass +_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable +_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home()) +def _d(name, env=None): + """Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override.""" + if env and _pos.environ.get(env): + return _PPath(_pos.environ[env]) + return _DATA / name +def _w(name=""): + """Work-dir path under ./_work (or $TOOLKIT_WORK).""" + return (_WORK / name) if name else _WORK +# --- end portable prelude --- + +import json +import random +import re +import string +import time +import sys +import urllib.error +import urllib.request + +sys.path.insert(0, str(_REPO)) +import type_client + +CTX = type_client._CTX + + +def mailtm_get(path, token=None): + req = urllib.request.Request( + "https://api.mail.tm" + path, + headers={"Accept": "application/json", **({"Authorization": "Bearer "+token} if token else {})}, + method="GET", + ) + with urllib.request.urlopen(req, timeout=30, context=CTX) as r: + return json.load(r) + + +def mailtm_post(path, body, token=None): + req = urllib.request.Request( + "https://api.mail.tm" + path, + data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", "Accept": "application/json", + **({"Authorization": "Bearer " + token} if token else {})}, + method="POST", + ) + with urllib.request.urlopen(req, timeout=30, context=CTX) as r: + return json.load(r) + + +resp = mailtm_get("/domains") +dom_list = resp["hydra:member"] if isinstance(resp, dict) else resp +domains = [d["domain"] for d in dom_list if d.get("isActive", True)] +domain = domains[0] +local = "e2e" + "".join(random.choices(string.ascii_lowercase + string.digits, k=10)) +address = local + "@" + domain +password = "Tp" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!9" +try: + acct = mailtm_post("/accounts", {"address": address, "password": password}) + print(f"[1] mailbox created: {address} (domain {domain})") +except urllib.error.HTTPError as e: + print("mailbox create failed:", e.code, e.read().decode()[:300]) + raise SystemExit(1) + +cfg = type_client.discover() +print(f"[2] discovery ok: issuer={cfg['issuer']}") +state = type_client.signup_start(cfg, address, "e2e lab") +print(f"[3] signup start ok: signupToken={state['signupToken'][:8]}… code dispatched") + +jwt = mailtm_post("/token", {"address": address, "password": password})["token"] +code = None +deadline = time.time() + 240 +while time.time() < deadline and not code: + time.sleep(8) + msgs = mailtm_get("/messages", token=jwt) + msgs = msgs["hydra:member"] if isinstance(msgs, dict) else msgs + for msg in msgs: + body = mailtm_get(f"/messages/{msg['id']}", token=jwt) + text = body.get("text") or "" + if not text and body.get("html"): + html = body["html"] + text = html if isinstance(html, str) else "".join(html) + codes = re.findall(r"\b(\d{6})\b", text) + if codes: + code = codes[-1] + break +if not code: + raise RuntimeError("no code via mail.tm REST within 240s") +print(f"[4] REST code fetched: {code}") + +state = type_client.signup_complete(cfg, state, code) +org = state.get("organization") or {} +print(f"[5] signup complete: org={org.get('slug')} accessToken={'yes' if state.get('accessToken') else 'NO'}") + +st, me = type_client.api_get(state) +print(f"[6] GET /v1/me -> HTTP {st}") +print(json.dumps(me, indent=2, ensure_ascii=False)[:1200]) diff --git a/client/probe_identity.py b/client/probe_identity.py new file mode 100644 index 0000000..507a65c --- /dev/null +++ b/client/probe_identity.py @@ -0,0 +1,19 @@ +import json, urllib.request, urllib.error, ssl + +ctx = ssl.create_default_context() +ctx.check_hostname = False +ctx.verify_mode = ssl.CERT_NONE + +req = urllib.request.Request( + "https://auth.type.com/agent/identity", + data=json.dumps({"login_hint": "throwaway.test.reg@gmail.com", "type": "service_auth"}).encode(), + headers={"Content-Type": "application/json", "User-Agent": "type-cli/rev (python)"}, + method="POST", +) +try: + with urllib.request.urlopen(req, timeout=30, context=ctx) as r: + print("HTTP", r.status) + print(json.dumps(json.load(r), indent=2)[:1500]) +except urllib.error.HTTPError as e: + print("HTTP", e.code) + print(e.read().decode("utf-8", "replace")[:1500]) diff --git a/client/probe_identity_refresh.py b/client/probe_identity_refresh.py new file mode 100644 index 0000000..6818469 --- /dev/null +++ b/client/probe_identity_refresh.py @@ -0,0 +1,39 @@ +import json +import sys +import urllib.error +import urllib.request + +sys.path.insert(0, ".") +import type_client + +state = type_client.load_profile() +cfg = type_client.discover() +rt = state.get("refreshToken") +rt = rt.get("value") if isinstance(rt, dict) else rt +print("refreshToken:", rt[:20] + "…") + +req = urllib.request.Request( + cfg["identity_endpoint"], + data=json.dumps({"refresh_token": rt, "type": "refresh"}).encode(), + headers={"Content-Type": "application/json", "User-Agent": "type-cli/rev (python)"}, + method="POST", +) +try: + with urllib.request.urlopen(req, timeout=30, context=type_client._CTX) as r: + body = json.load(r) + print("identity refresh -> 200:", json.dumps(body, ensure_ascii=False)[:500]) + identity = body.get("identity") or {} + assertion = identity.get("assertion") + if assertion: + state2 = dict(state) + state2["assertion"] = assertion + new_rt = identity.get("refresh_token") + if new_rt: + state2["refreshToken"] = new_rt + state2 = type_client.exchange(cfg, state2) + type_client.save_profile(state2) + print("re-exchange OK; expires_at:", state2["expiresAt"]) + st, me = type_client.orpc_call(state2, "cli/context/me") + print("orpc context/me ->", st, json.dumps(me, ensure_ascii=False)[:300]) +except urllib.error.HTTPError as e: + print("identity refresh ->", e.code, e.read().decode()[:300]) diff --git a/client/probe_orpc.py b/client/probe_orpc.py new file mode 100644 index 0000000..f6c568e --- /dev/null +++ b/client/probe_orpc.py @@ -0,0 +1,42 @@ +import json +import sys +import urllib.error +import urllib.request + +sys.path.insert(0, ".") +import type_client + +state = type_client.load_profile() +cfg = type_client.discover() +state = type_client.exchange(cfg, state) +token = state["accessToken"] +CTX = type_client._CTX +CLI_VERSION = "0.0.0-rev" + + +def call(label, path, body=None): + req = urllib.request.Request( + "https://api.type.com/api/orpc/" + path, + data=json.dumps({"json": body or {}}).encode(), + method="POST", + headers={ + "Content-Type": "application/json", + "Authorization": "Bearer " + token, + "User-Agent": f"TypeCLI/{CLI_VERSION}", + "x-type-cli-version": CLI_VERSION, + }, + ) + try: + with urllib.request.urlopen(req, timeout=30, context=CTX) as r: + raw = r.read().decode("utf-8", "replace") + print(f"{label} -> {r.status} {raw[:400]}") + return json.loads(raw) if raw else None + except urllib.error.HTTPError as e: + print(f"{label} -> {e.code} {e.read().decode()[:250]}") + return None + + +call("cli/context/me", "cli/context/me") +call("cli/threads/list", "cli/threads/list") +call("cliAuth/listOrganizations", "cliAuth/listOrganizations") +call("cli/agents/list", "cli/agents/list") diff --git a/client/probe_refresh.py b/client/probe_refresh.py new file mode 100644 index 0000000..5f302a2 --- /dev/null +++ b/client/probe_refresh.py @@ -0,0 +1,45 @@ +import json +import sys +import urllib.error +import urllib.parse +import urllib.request + +sys.path.insert(0, ".") +import type_client + +state = type_client.load_profile() +form = { + "client_id": state.get("clientId") or "client_01K5GFDDKQWV8MM9FSRZS3YNNN", + "grant_type": "refresh_token", + "refresh_token": state["refreshToken"], +} +org = (state.get("organization") or {}).get("workosOrgId") +if org: + form["organization_id"] = org +req = urllib.request.Request( + "https://api.workos.com/user_management/authenticate", + data=urllib.parse.urlencode(form).encode(), + headers={"Content-Type": "application/x-www-form-urlencoded"}, + method="POST", +) +try: + with urllib.request.urlopen(req, timeout=30, context=type_client._CTX) as r: + body = json.load(r) + print("refresh @workos -> 200:", {k: (v[:24] + "…" if isinstance(v, str) and len(v) > 24 else v) for k, v in body.items()}) + # try the fresh token against the oRPC API + tok = body["access_token"] + req2 = urllib.request.Request( + "https://api.type.com/api/orpc/cli/context/me", + data=json.dumps({"json": {}}).encode(), + method="POST", + headers={ + "Content-Type": "application/json", + "Authorization": "Bearer " + tok, + "User-Agent": "TypeCLI/rev", + "x-type-cli-version": "0.0.0", + }, + ) + with urllib.request.urlopen(req2, timeout=30, context=type_client._CTX) as r2: + print("orpc context/me ->", r2.status, r2.read().decode()[:400]) +except urllib.error.HTTPError as e: + print("refresh @workos ->", e.code, e.read().decode()[:300]) diff --git a/client/probe_start.py b/client/probe_start.py new file mode 100644 index 0000000..495ff0a --- /dev/null +++ b/client/probe_start.py @@ -0,0 +1,27 @@ +import json, urllib.request, urllib.error, urllib.parse, ssl + +ctx = ssl.create_default_context() +ctx.check_hostname = False +ctx.verify_mode = ssl.CERT_NONE + +email = "throwaway.test.reg@gmail.com" +vuri = "https://auth.type.com/agent-claim?token=cat_ywILqSA7QnXgWZvCWN7CnsD-omQ581Xe" +cat = urllib.parse.parse_qs(urllib.parse.urlparse(vuri).query)["token"][0] +body = { + "claimAttemptToken": cat, + "email": email, + "organizationName": "test lab", +} +req = urllib.request.Request( + "https://api.type.com/api/agent-signup/start", + data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", "User-Agent": "type-cli/rev (python)"}, + method="POST", +) +try: + with urllib.request.urlopen(req, timeout=30, context=ctx) as r: + print("HTTP", r.status) + print(json.dumps(json.load(r), indent=2)[:800]) +except urllib.error.HTTPError as e: + print("HTTP", e.code) + print(e.read().decode("utf-8", "replace")[:800]) diff --git a/client/probe_token.py b/client/probe_token.py new file mode 100644 index 0000000..def8e37 --- /dev/null +++ b/client/probe_token.py @@ -0,0 +1,39 @@ +import base64 +import json +import sys + +sys.path.insert(0, ".") +import type_client + +state = type_client.load_profile() +cfg = type_client.discover() +state = type_client.exchange(cfg, state) +tok = state["accessToken"] +seg = tok.split(".")[1] +seg += "=" * (-len(seg) % 4) +payload = json.loads(base64.urlsafe_b64decode(seg)) +print(json.dumps(payload, indent=2)[:900]) +print("scopes in state identity:", "refreshToken" if state.get("refreshToken") else "none") + +# WorkOS refresh_token grant (identity refresh token from claim/complete) +import urllib.error +import urllib.parse +import urllib.request + +form = { + "client_id": state.get("clientId") or "client_01K5GFDDKQWV8MM9FSRZS3YNNN", + "grant_type": "refresh_token", + "refresh_token": state["refreshToken"], +} +req = urllib.request.Request( + "https://auth.type.com/oauth2/token", + data=urllib.parse.urlencode(form).encode(), + headers={"Content-Type": "application/x-www-form-urlencoded"}, + method="POST", +) +try: + with urllib.request.urlopen(req, timeout=30, context=type_client._CTX) as r: + body = json.load(r) + print("refresh via issuer -> 200:", {k: (v[:20] + "…" if isinstance(v, str) and len(v) > 20 else v) for k, v in body.items()}) +except urllib.error.HTTPError as e: + print("refresh via issuer ->", e.code, e.read().decode()[:200]) diff --git a/client/type2api.py b/client/type2api.py new file mode 100644 index 0000000..6a2ebd9 --- /dev/null +++ b/client/type2api.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +""" +type2api.py — OpenAI-compatible gateway over type.com (protocol reverse). + +Bootstrap (one human click): + 1. python type_client.py device-login --email + 2. Open the printed URL in YOUR browser (Google session) -> "Continue with Google" + 3. Polling catches the token -> saved to ~/.type/credentials/.json + 4. python type2api.py -> serves on :8311 + +Endpoints: + GET /v1/models -> agents from cli/agents/list + POST /v1/chat/completions -> thread pipeline over oRPC + (message-send procedure is auto-discovered: the CLI bundle only calls + read procedures, so this server probes send/create names live and + logs which the server exposes with the user token) + +Zero dependencies (stdlib). Token auto-refreshed via device-refresh grant. +""" +import json +import os +import sys +import time +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import type_client # noqa: E402 + +PORT = int(os.environ.get("TYPE2API_PORT", "8311")) +PROFILE = os.environ.get("TYPE_PROFILE", "default") +SEND_PROCEDURE_CANDIDATES = [ + "cli/threads/create", + "cli/messages/create", + "cli/threads/send", + "cli/chat/send", + "cli/agents/run", + "cli/threads/message", +] + + +def get_state(): + state = type_client.load_profile() + if not state or not state.get("accessToken"): + raise RuntimeError("no access token: run `python type_client.py device-login` first") + if time.time() > state.get("expiresAt", 0): + cfg = type_client.discover(state.get("server") or type_client.SERVER) + state = type_client.refresh(cfg, state) + return state + + +def try_state(): + try: + return get_state(), None + except Exception as e: + return None, str(e) + + +def orpc(state, procedure, args=None): + return type_client.orpc_call(state, procedure, args) + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _send(self, code, payload): + body = json.dumps(payload, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/v1/models": + state = get_state() + st, agents = orpc(state, "cli/agents/list") + items = [] + if st == 200 and isinstance(agents, dict): + raw = agents.get("json") or agents + for a in (raw.get("agents") or raw.get("data") or []): + items.append({"id": f"type-{a.get('handle') or a.get('id')}", "object": "model", "owned_by": "type.com"}) + self._send(200, {"object": "list", "data": items}) + elif self.path == "/health": + self._send(200, {"ok": True, "profile": PROFILE}) + else: + self._send(404, {"error": {"message": "not found"}}) + + def do_POST(self): + if self.path != "/v1/chat/completions": + self._send(404, {"error": {"message": "not found"}}) + return + length = int(self.headers.get("Content-Length") or 0) + req = json.loads(self.rfile.read(length) or b"{}") + messages = req.get("messages") or [] + content_last = messages[-1].get("content", "") if messages else "" + prompt = json.dumps(content_last, ensure_ascii=False) if not isinstance(content_last, str) else content_last + state, err = try_state() + if err: + self._send(500, {"error": {"message": err, "type": "auth_error"}}) + return + # discover the send procedure once (logged; cache in .type/send_proc.json) + cache = os.path.join(type_client.CRED_DIR, "send_proc.json") + proc = None + if os.path.exists(cache): + proc = json.load(open(cache)).get("procedure") + if not proc: + for cand in SEND_PROCEDURE_CANDIDATES: + st, body = orpc(state, cand, {"text": prompt}) + if st == 200: + proc = cand + json.dump({"procedure": proc}, open(cache, "w")) + print(f"[type2api] send procedure discovered: {proc}") + break + if st not in (404,): + print(f"[type2api] {cand}: exists but rejected (HTTP {st}) - wrong args/scope") + if proc: + st, body = orpc(state, proc, {"text": prompt, "messages": messages}) + content = (body.get("json") if isinstance(body, dict) else None) or body + if isinstance(content, dict): + content = content.get("content") or content.get("text") or json.dumps(content, ensure_ascii=False) + else: + content = str(content) + else: + st = 501 + content = ( + "type2api: token OK but no send procedure exposed to this scope; " + "probed " + ", ".join(SEND_PROCEDURE_CANDIDATES) + ". " + "See README: full message flow runs through local harnesses." + ) + if st != 200: + self._send(502 if st in (400, 404, 422) else 501, { + "error": {"message": str(content), "type": "type_upstream", "upstream_status": st} + }) + return + out = { + "id": f"chatcmpl-type-{int(time.time()*1000)}", + "object": "chat.completion", + "created": int(time.time()), + "model": req.get("model", "type-default"), + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": str(content)}, + "finish_reason": "stop", + } + ], + } + self._send(200, out) + + +def main(): + get_state() # fail fast if no token + print(f"type2api on :{PORT} (profile {PROFILE})") + ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/client/type_client.py b/client/type_client.py new file mode 100644 index 0000000..74aeacb --- /dev/null +++ b/client/type_client.py @@ -0,0 +1,490 @@ +#!/usr/bin/env python3 +""" +type_client.py — protocol-level client for type.com (Type shared-agent platform). + +Reversed from type-cli (Bun single-executable, `bun build --compile`): + installer : https://type.com/install.sh -> https://desktop.type.com/cli/ + server : https://api.type.com (prod) / https://api.typestaging.com (staging) + identity : WorkOS user_management (device + jwt-bearer + refresh_token grants) + signup : "service_auth" agent registration, 6-digit email code, NO BROWSER + storage : ~/.type/credentials/{profile}.json (CLI-compatible) + +Zero dependencies (stdlib only). Python 3.9+. + +Usage: + python type_client.py discover + python type_client.py signup --email me@mail.com --org "myteam" + python type_client.py complete --code 123456 + python type_client.py status + python type_client.py refresh + python type_client.py me + python type_client.py device-login + python type_client.py batch --emails emails.txt --org "farm" # IMAP hook below +""" +import argparse +import json +import os +import ssl +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +SERVER = os.environ.get("TYPE_SERVER_URL", "https://api.type.com") +WORKOS_AUTHENTICATE_URL = "https://api.workos.com/user_management/authenticate" +WORKOS_DEVICE_AUTHORIZE_URL = "https://api.workos.com/user_management/authorize/device" +AGENT_TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer" +DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code" +BUNDLED_WORKOS_CLIENT_ID = "client_01K5GFDDKQWV8MM9FSRZS3YNNN" # extracted from CLI +CRED_DIR = os.path.join( + os.environ.get("TYPE_CONFIG_DIR", os.path.join(os.path.expanduser("~"), ".type")), + "credentials", +) +PROFILE = os.environ.get("TYPE_PROFILE", "default") + +_CTX = ssl.create_default_context() +if os.environ.get("TYPE_INSECURE") == "1": + _CTX.check_hostname = False + _CTX.verify_mode = ssl.CERT_NONE + + +def _proxies(): + handlers = [] + proxy = os.environ.get("TYPE_PROXY") # http://user:pass@host:port + if proxy: + handlers.append(urllib.request.ProxyHandler({"http": proxy, "https": proxy})) + opener = urllib.request.build_opener(*handlers) if handlers else None + return opener + + +def http_json(method, url, body=None, form=None, token=None, expect=None): + """JSON/form request -> (status, dict). Non-JSON responses become {"_raw": str}.""" + headers = {"User-Agent": "type-cli/rev (python)"} + data = None + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + if form is not None: + data = urllib.parse.urlencode(form).encode() + headers["Content-Type"] = "application/x-www-form-urlencoded" + if token: + headers["Authorization"] = "Bearer " + token + req = urllib.request.Request(url, data=data, headers=headers, method=method) + opener = _proxies() + urlopen = opener.urlopen if opener else urllib.request.urlopen + try: + resp = urlopen(req, timeout=30, context=_CTX) + raw = resp.read() + status = resp.status + except urllib.error.HTTPError as e: + raw = e.read() + status = e.code + try: + parsed = json.loads(raw.decode("utf-8", "replace")) + if not isinstance(parsed, dict): + parsed = {"_raw": parsed} + except Exception: + parsed = {"_raw": raw.decode("utf-8", "replace")} + if expect is not None and status != expect: + raise RuntimeError(f"{method} {url} -> {status}: {parsed}") + return status, parsed + + +def load_profile(): + path = os.path.join(CRED_DIR, PROFILE + ".json") + if not os.path.exists(path): + return None + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def save_profile(state): + os.makedirs(CRED_DIR, exist_ok=True) + path = os.path.join(CRED_DIR, PROFILE + ".json") + with open(path, "w", encoding="utf-8") as f: + json.dump(state, f, indent=2, ensure_ascii=False) + return path + + +# ---------------------------------------------------------------- discovery +def discover(server=SERVER): + """RFC 8414 chain the CLI walks: protected-resource -> authorization server.""" + st, pr = http_json("GET", server + "/.well-known/oauth-protected-resource") + if st != 200: + raise RuntimeError(f"protected-resource discovery HTTP {st}: {pr}") + issuer = (pr.get("authorization_servers") or [""])[0].rstrip("/") + client_id = pr.get("type_workos_client_id") or BUNDLED_WORKOS_CLIENT_ID + meta = None + for well_known in ( + "/.well-known/oauth-authorization-server", + "/.well-known/openid-configuration", + ): + st, meta = http_json("GET", issuer + well_known) + if st == 200 and isinstance(meta, dict): + break + if not isinstance(meta, dict) or "token_endpoint" not in meta: + raise RuntimeError(f"authorization-server metadata not found on {issuer}") + agent_auth = meta.get("agent_auth") or {} + cfg = { + "server": server, + "issuer": issuer, + "resource": (pr.get("resource") or server).rstrip("/"), + "client_id": client_id, + "token_endpoint": meta["token_endpoint"], + "identity_endpoint": agent_auth.get("identity_endpoint"), + "identity_types": agent_auth.get("identity_types_supported"), + } + return cfg + + +# ---------------------------------------------------------------- signup +def signup_start(cfg, email, org_name, state=None): + """service_auth registration + agent-signup/start -> state saved, email code sent.""" + if not state: + st, reg = http_json( + "POST", + cfg["identity_endpoint"], + body={"login_hint": email, "type": "service_auth"}, + expect=200, + ) + claim = reg.get("claim") or {} + attempt = claim.get("attempt") or {} + vuri = attempt.get("verification_uri") or "" + claim_attempt_token = ( + (urllib.parse.parse_qs(urllib.parse.urlparse(vuri).query).get("token") or [None])[0] + ) + if not claim.get("token") or not claim_attempt_token: + raise RuntimeError(f"unexpected registration payload: {reg}") + state = { + "kind": "agent-signup-registered", + "email": email, + "organizationName": org_name, + "claimToken": claim["token"], + "claimAttemptToken": claim_attempt_token, + "issuer": cfg["issuer"], + "resource": cfg["resource"], + "tokenEndpoint": cfg["token_endpoint"], + "clientId": cfg["client_id"], + } + st, resp = http_json( + "POST", + cfg["server"] + "/api/agent-signup/start", + body={ + "claimAttemptToken": state["claimAttemptToken"], + "email": state["email"], + "organizationName": state["organizationName"], + }, + expect=200, + ) + state["signupToken"] = resp.get("signupToken") + state["kind"] = "agent-signup-pending" + save_profile(state) + return state + + +def signup_complete(cfg, state, code): + """verify 6-digit code -> complete WorkOS claim -> jwt-bearer exchange -> tokens.""" + code = (code or "").strip() + if not (code.isdigit() and len(code) == 6): + raise SystemExit("code must be 6 digits") + st, resp = http_json( + "POST", + cfg["server"] + "/api/agent-signup/verify", + body={"code": code, "signupToken": state["signupToken"]}, + expect=200, + ) + claim = resp["claim"] + org = resp["organization"] + state.update( + { + "kind": "agent-signup-claim-ready", + "registrationId": claim["registrationId"], + "userCode": claim["userCode"], + "organization": org, + "organizationCreated": resp.get("organizationCreated"), + } + ) + st, done = http_json( + "POST", + cfg["issuer"] + "/agent/identity/claim/complete", + body={"claim_token": state["claimToken"], "user_code": claim["userCode"]}, + ) + if st != 200: + raise RuntimeError(f"claim/complete HTTP {st}: {done}") + identity = done.get("identity") or {} + assertion = identity.get("assertion") + refresh_token = identity.get("refresh_token") or identity.get("refreshToken") + if isinstance(refresh_token, dict): # {value, expires_at} per normalizeIdentity + refresh_token = refresh_token.get("value") + if not assertion: + raise RuntimeError(f"claim/complete returned no assertion: {done}") + state.update( + { + "kind": "agent-signup-provisioned", + "assertion": assertion, + "refreshToken": refresh_token, + } + ) + save_profile(state) # persist before exchange so a failed exchange is retryable + return exchange(cfg, state) + + +def exchange(cfg, state): + # assertion aud == issuer (auth.type.com), NOT the api resource: sending + # resource=api.type.com yields HTTP 400 invalid_target. Omit unless forced. + form = { + "assertion": state["assertion"], + "grant_type": AGENT_TOKEN_EXCHANGE_GRANT, + } + if os.environ.get("TYPE_EXCHANGE_RESOURCE"): + form["resource"] = os.environ["TYPE_EXCHANGE_RESOURCE"] + token_endpoint = (cfg or {}).get("token_endpoint") or state.get("tokenEndpoint") + if not token_endpoint: + raise RuntimeError("profile has no tokenEndpoint; run signup again") + st, tokens = http_json("POST", token_endpoint, form=form) + if st != 200: + raise RuntimeError(f"token exchange HTTP {st}: {tokens}") + state.update( + { + "kind": "tokens", + "accessToken": tokens["access_token"], + "refreshToken": tokens.get("refresh_token") or state.get("refreshToken"), + "tokenType": tokens.get("token_type"), + "expiresAt": time.time() + int(tokens.get("expires_in") or 3600), + } + ) + save_profile(state) + return state + + +# ---------------------------------------------------------------- refresh / API +def refresh(cfg, state): + """Agent-credential refresh (bundle: refreshAgentRegistration): + POST identityEndpoint {refresh_token, type:"refresh"} -> fresh assertion + -> jwt-bearer exchange (no resource) -> new access_token. Live-verified 200.""" + rt = state.get("refreshToken") + rt = rt.get("value") if isinstance(rt, dict) else rt + if not rt: + raise RuntimeError("no refreshToken in profile; run signup/complete again") + issuer = (cfg or {}).get("issuer") or state.get("issuer") + endpoint = (cfg or {}).get("identity_endpoint") or (issuer + "/agent/identity" if issuer else None) + if not endpoint: + raise RuntimeError("profile has no issuer; run signup or device-login first") + st, body = http_json( + "POST", + endpoint, + body={"refresh_token": rt, "type": "refresh"}, + ) + if st != 200: + raise RuntimeError(f"identity refresh HTTP {st}: {body}") + identity = body.get("identity") or {} + state["assertion"] = identity["assertion"] + new_rt = identity.get("refresh_token") + if new_rt: + state["refreshToken"] = new_rt.get("value") if isinstance(new_rt, dict) else new_rt + save_profile(state) # persist rotation BEFORE exchange: single-use rt must not burn + return exchange(cfg, state) + + +def api_get(state, path="/v1/me"): + st, body = http_json("GET", state.get("server", SERVER) + path, token=state["accessToken"]) + return st, body + + +def orpc_call(state, procedure, args=None): + """oRPC call: POST {server}/api/orpc/{procedure} body {"json": args}. + Procedures (from bundle): cli/context/me, cli/threads/list, cliAuth/listOrganizations… + Note: service_auth tokens currently carry empty post_claim scopes -> API returns + 401 Invalid token; full access requires device-login (auth login).""" + st, body = http_json( + "POST", + state.get("server", SERVER) + "/api/orpc/" + procedure, + body={"json": args or {}}, + token=state["accessToken"], + ) + return st, body + + +# ---------------------------------------------------------------- device login +def device_login(cfg, email=None): + form = {"client_id": cfg["client_id"]} + if email: + form["login_hint"] = email + st, dr = http_json("POST", WORKOS_DEVICE_AUTHORIZE_URL, form=form, expect=200) + print(f"Open: {dr.get('verification_uri_complete') or dr.get('verification_uri')}") + print(f"User code: {dr.get('user_code')}") + interval = int(dr.get("interval") or 5) + deadline = time.time() + 900 + while time.time() < deadline: + time.sleep(interval) + form = { + "client_id": cfg["client_id"], + "device_code": dr["device_code"], + "grant_type": DEVICE_CODE_GRANT, + } + st, tokens = http_json("POST", WORKOS_AUTHENTICATE_URL, form=form) + if st == 200: + state = { + "kind": "tokens", + "server": cfg["server"], + "accessToken": tokens["access_token"], + "refreshToken": tokens.get("refresh_token"), + "expiresAt": time.time() + int(tokens.get("expires_in") or 3600), + } + save_profile(state) + return state + err = tokens.get("error") if isinstance(tokens, dict) else None + if err == "authorization_pending": + continue + if err == "slow_down": + interval += 5 + continue + raise RuntimeError(f"device grant stopped: {err or st}") + raise RuntimeError("device grant timeout") + + +# ---------------------------------------------------------------- IMAP hook +def fetch_code_imap(email, password, host="mail.tm", folder="INBOX", wait=180): + """Hook for mail pools: reads the newest 6-digit code from signup mail. + Adapt host/credentials to your pool provider.""" + import imaplib + import email as emaillib + import re + + deadline = time.time() + wait + while time.time() < deadline: + m = imaplib.IMAP4_SSL(host) + m.login(email, password) + m.select(folder) + # RFC 3501 has no infix OR — plain UNSEEN, filter headers in Python. + _, ids = m.search(None, "UNSEEN") + for i in (ids[0] or b"").split()[-5:]: + _, data = m.fetch(i, "(RFC822)") + raw = data[0][1] if data and isinstance(data[0], tuple) else None + if raw is None: + continue + msg = emaillib.message_from_bytes(raw) + sender = (msg.get("From") or "").lower() + subject = (msg.get("Subject") or "").lower() + if "type" not in sender and "type" not in subject: + continue + body = "" + for part in msg.walk(): # multipart/alternative safe + if part.get_content_type() == "text/plain": + payload = part.get_payload(decode=True) + if payload: + body += payload.decode("utf-8", "replace") + codes = re.findall(r"\b(\d{6})\b", body) + if codes: + m.logout() + return codes[-1] + m.logout() + time.sleep(10) + raise RuntimeError("no code within wait window") + + +def batch_register(emails_file, org, imap_host="mail.tm", imap_pass_file=None): + """Farm: one signup per line of `email:password`. Needs IMAP for codes.""" + cfg = discover() + results = [] + passes = {} + if imap_pass_file: + for line in open(imap_pass_file, encoding="utf-8"): + if ":" in line: + e, p = line.strip().split(":", 1) + passes[e] = p + for line in open(emails_file, encoding="utf-8"): + email = line.strip().lower() + if not email: + continue + os.environ["TYPE_PROFILE"] = email.replace("@", "_at_").replace(".", "_") + globals()["PROFILE"] = os.environ["TYPE_PROFILE"] + try: + state = signup_start(cfg, email, org) + code = None + if email in passes: + code = fetch_code_imap(email, passes[email], host=imap_host) + else: + code = input(f"[{email}] code from email> ").strip() + state = signup_complete(cfg, state, code) + st, me = api_get(state) + results.append({"email": email, "ok": st == 200, "org": state.get("organization")}) + print(f"OK {email} -> {state.get('organization', {}).get('slug')}") + except Exception as e: + results.append({"email": email, "ok": False, "error": str(e)}) + print(f"FAIL {email}: {e}") + out = os.path.join(os.path.dirname(emails_file) or ".", "type_batch_result.json") + with open(out, "w", encoding="utf-8") as f: + json.dump(results, f, indent=2) + print(f"results -> {out}") + + +# ---------------------------------------------------------------- cli +def main(): + ap = argparse.ArgumentParser(description="type.com protocol client") + sub = ap.add_subparsers(dest="cmd", required=True) + sub.add_parser("discover") + sp = sub.add_parser("signup") + sp.add_argument("--email", required=True) + sp.add_argument("--org", required=True) + cp = sub.add_parser("complete") + cp.add_argument("--code", required=True) + sub.add_parser("status") + sub.add_parser("refresh") + sub.add_parser("me") + dp = sub.add_parser("device-login") + dp.add_argument("--email") + bp = sub.add_parser("batch") + bp.add_argument("--emails", required=True) + bp.add_argument("--org", required=True) + bp.add_argument("--imap-host", default="mail.tm") + bp.add_argument("--imap-pass-file") + args = ap.parse_args() + + if args.cmd == "discover": + cfg = discover() + print(json.dumps(cfg, indent=2)) + elif args.cmd == "signup": + cfg = discover() + state = signup_start(cfg, args.email, args.org) + print(f"code sent to {state['email']} (state saved).") + print(f"next: python {sys.argv[0]} complete --code <6digits> [--profile {PROFILE}]") + elif args.cmd == "complete": + state = load_profile() + if not state or state.get("kind") not in ("agent-signup-pending", "agent-signup-verifying"): + raise SystemExit("no pending signup in this profile") + cfg = discover(state.get("server") or SERVER) + state = signup_complete(cfg, state, args.code) + print(f"PROVISIONED org={state.get('organization', {}).get('slug')} " + f"accessToken={'yes' if state.get('accessToken') else 'no'}") + elif args.cmd == "status": + state = load_profile() + print(json.dumps( + {k: v for k, v in (state or {}).items() + if k not in ("assertion", "accessToken", "refreshToken", "signupToken")}, + indent=2, ensure_ascii=False)) + elif args.cmd == "refresh": + state = load_profile() + cfg = discover(state.get("server") or SERVER) + state = refresh(cfg, state) + print(f"refreshed, expires_at={state['expiresAt']}") + elif args.cmd == "me": + state = load_profile() + if state.get("kind") != "tokens": + raise SystemExit("profile has no access token; run signup/complete or device-login") + if time.time() > state.get("expiresAt", 0): + refresh(discover(state.get("server") or SERVER), state) + state = load_profile() + st, me = orpc_call(state, "cli/context/me") + print(st, json.dumps(me, indent=2, ensure_ascii=False)[:2000]) + elif args.cmd == "device-login": + cfg = discover() + device_login(cfg, email=args.email) + print("tokens stored") + elif args.cmd == "batch": + batch_register(args.emails, args.org, args.imap_host, args.imap_pass_file) + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..2b56962 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +Pillow +camoufox +playwright +pyotp +requests +# after install: python -m playwright install chromium && python -m camoufox fetch diff --git a/server/dashboard.html b/server/dashboard.html new file mode 100644 index 0000000..9e7cfed --- /dev/null +++ b/server/dashboard.html @@ -0,0 +1,114 @@ + + + + +type-toolkit — control plane + + + +

type-toolkit

+
type.com agent platform — autoreg / pool / OpenAI-compat gateway. gateway :8311
+ +
oRPC API закрыт сервером для agent-токенов (401 Invalid token, aud-политика). Пул, авторег и ротация identity работают полностью — см. FINDINGS.md.
+ +
+

Gateway :8311

—
+

Аккаунтов в пуле

—
+

С токеном

—
+

Обновлено

—
+
+ +
+ + + + +
+ + + +
emailorgсозданпосл. refreshстатусtoken
+ +

Лог

+
+ + + + diff --git a/server/gateway.py b/server/gateway.py new file mode 100644 index 0000000..6379bd3 --- /dev/null +++ b/server/gateway.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +""" +gateway.py - OpenAI-compatible gateway over the type.com agent pool. +Port 8311. Stdlib only. Pool-aware: rotates accounts from server/pool.json, +auto-refreshes identity (rotating refresh_token) before use. + +Endpoints: + GET /v1/models -> static agent catalog (pool-backed) + GET /health -> {"ok", "pool", "upstream_mode"} + POST /v1/chat/completions -> oRPC bridge (cli/messages/send etc.) + Upstream api.type.com currently rejects agent tokens with + 401 Invalid token (aud=client, server policy - see FINDINGS.md), + so completions return the upstream status verbatim. +""" +import json +import os +import sys +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +ROOT = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, ROOT) + +POOL_PATH = os.path.join(ROOT, "pool.json") +PORT = int(os.environ.get("TYPE2API_PORT", "8311")) +UA = "TypeCLI/1.0.0" +TOKEN_TTL = 3600 + +POOL_LOCK = threading.Lock() +_ROBIN = {"i": 0} +STATS = {"requests": 0, "upstream_401": 0, "upstream_200": 0, "refreshes": 0} + + +def log(msg): + print("[gateway %s] %s" % (time.strftime("%H:%M:%S"), msg), flush=True) + + +def api(method, url, body=None, form=None, headers=None, timeout=30): + h = {"Content-Type": "application/json", "User-Agent": UA} + if headers: + h.update(headers) + data = None + if body is not None: + data = json.dumps(body).encode() + if form is not None: + data = urllib.parse.urlencode(form).encode() + h["Content-Type"] = "application/x-www-form-urlencoded" + req = urllib.request.Request(url, data=data, headers=h, method=method) + try: + r = urllib.request.urlopen(req, timeout=timeout) + raw = r.read() + status = r.status + except urllib.error.HTTPError as e: + raw = e.read() + status = e.code + except Exception as e: + return 0, {"error": str(e)} + try: + parsed = json.loads(raw or b"{}") + except Exception: + parsed = {"_raw": raw.decode("utf-8", "replace")[:300]} + return status, parsed + + +def load_pool(): + if not os.path.exists(POOL_PATH): + return [] + try: + with open(POOL_PATH, encoding="utf-8") as f: + return json.load(f) + except Exception: + return [] + + +def save_pool(pool): + tmp = POOL_PATH + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(pool, f, indent=1) + os.replace(tmp, POOL_PATH) + + +def refresh_account(acct): + """Identity refresh (rotating rt) + jwt-bearer exchange. Live-verified flow.""" + rt = acct.get("refresh_token") + if not rt: + raise RuntimeError("no refresh_token for %s" % acct.get("email")) + st, body = api("POST", "https://auth.type.com/agent/identity", + body={"refresh_token": rt, "type": "refresh"}) + if st != 200: + raise RuntimeError("identity refresh %s: %s" % (st, str(body)[:120])) + ident = body.get("identity") or {} + new_rt = (ident.get("refresh_token") or {}).get("value") + if ident.get("assertion"): + acct["assertion"] = ident["assertion"] + if new_rt: + acct["refresh_token"] = new_rt + st2, tok = api("POST", acct.get("token_endpoint", "https://auth.type.com/oauth2/token"), + form={"assertion": acct["assertion"], + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer"}) + at = tok.get("access_token") + if not at: + raise RuntimeError("exchange %s: %s" % (st2, str(tok)[:120])) + acct["access_token"] = at + acct["access_token_len"] = len(at) + acct["last_refresh"] = time.strftime("%Y-%m-%d %H:%M:%S") + acct["last_status"] = "refresh:%s/exchange:%s" % (st, st2) + acct["token_expires_at"] = time.time() + TOKEN_TTL + STATS["refreshes"] += 1 + return acct + + +def pick_account(): + """Round-robin a pool account with a live-ish token; refresh if stale.""" + with POOL_LOCK: + pool = load_pool() + usable = [a for a in pool if a.get("refresh_token")] + if not usable: + raise RuntimeError("pool empty: POST http://127.0.0.1:8312/api/autoreg first") + acct = usable[_ROBIN["i"] % len(usable)] + _ROBIN["i"] += 1 + if time.time() > acct.get("token_expires_at", 0): + refresh_account(acct) + with POOL_LOCK: + pool = load_pool() + for i, a in enumerate(pool): + if a.get("email") == acct["email"]: + pool[i] = acct + save_pool(pool) + return acct + + +def orpc(acct, procedure, args=None): + return api("POST", "https://api.type.com/api/orpc/" + procedure, + body={"json": args or {}}, + headers={"Authorization": "Bearer " + acct["access_token"]}) + + +SEND_PROCEDURE_CANDIDATES = [ + "cli/threads/create", "cli/messages/create", "cli/threads/send", + "cli/chat/send", "cli/agents/run", "cli/threads/message", +] + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _send(self, code, payload): + body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + with POOL_LOCK: + pool = load_pool() + self._send(200, { + "ok": True, + "port": PORT, + "pool": {"count": len(pool), "with_token": sum(1 for a in pool if a.get("access_token"))}, + "stats": STATS, + "upstream_mode": "agent-pool (oRPC gated server-side: 401 Invalid token)", + }) + elif self.path == "/v1/models": + self._send(200, {"object": "list", "data": [ + {"id": "type-agent", "object": "model", "owned_by": "type.com"}, + {"id": "type-default", "object": "model", "owned_by": "type.com"}, + ]}) + else: + self._send(404, {"error": {"message": "not found"}}) + + def do_POST(self): + if self.path != "/v1/chat/completions": + self._send(404, {"error": {"message": "not found"}}) + return + length = int(self.headers.get("Content-Length") or 0) + try: + req = json.loads(self.rfile.read(length) or b"{}") + except Exception: + req = {} + STATS["requests"] += 1 + messages = req.get("messages") or [] + last = messages[-1].get("content", "") if messages else "" + prompt = last if isinstance(last, str) else json.dumps(last, ensure_ascii=False) + try: + acct = pick_account() + except Exception as e: + self._send(500, {"error": {"message": str(e), "type": "pool_error"}}) + return + # probe live procedures with the account token + last_err = None + for proc in SEND_PROCEDURE_CANDIDATES: + st, body = orpc(acct, proc, {"text": prompt}) + if st == 200: + STATS["upstream_200"] += 1 + content = body + if isinstance(content, dict): + content = content.get("json") or content.get("content") or json.dumps(content, ensure_ascii=False) + out = { + "id": "chatcmpl-type-%d" % int(time.time() * 1000), + "object": "chat.completion", "created": int(time.time()), + "model": req.get("model", "type-agent"), + "choices": [{"index": 0, "message": {"role": "assistant", "content": str(content)}, + "finish_reason": "stop"}], + } + self._send(200, out) + return + last_err = (st, body) + if st == 404: + continue + break + STATS["upstream_401"] += 1 + st, body = last_err or (0, {"error": "no procedure"}) + self._send(502, { + "error": { + "message": "type.com oRPC rejected agent token: HTTP %s %s" % ( + st, json.dumps(body, ensure_ascii=False)[:300]), + "type": "type_upstream", + "upstream_status": st, + "note": "api.type.com requires aud=https://api.type.com (user token). " + "Agent tokens get 401 by server policy. See FINDINGS.md.", + }, + }) + + +def main(): + log("gateway on :%d, pool=%s" % (PORT, POOL_PATH)) + ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/server/manager.py b/server/manager.py new file mode 100644 index 0000000..b0b0f5c --- /dev/null +++ b/server/manager.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +""" +manager.py - type-toolkit control plane: autoreg API + account pool + dashboard. +Port 8312. Stdlib only. + +Endpoints: + GET / dashboard (dashboard.html) + GET /api/status {gateway, pool summary, log tail} + GET /api/accounts pool (redacted - no tokens) + POST /api/autoreg {"org": "reform-org"} -> register 1 account (60-180s) + POST /api/refresh refresh all accounts (identity refresh + jwt-bearer exchange) + +Autoreg flow (live-verified 2026-09-30): + mail.tm account -> auth.type.com/agent/identity (service_auth) + -> api.type.com/api/agent-signup/start -> email code via mail.tm + -> agent-signup/verify -> agent/identity/claim/complete + -> oauth2/token jwt-bearer exchange -> access_token +""" +import json +import os +import random +import re +import string +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +ROOT = os.path.dirname(os.path.abspath(__file__)) +POOL_PATH = os.path.join(ROOT, "pool.json") +DASH_PATH = os.path.join(ROOT, "dashboard.html") +GATEWAY_URL = os.environ.get("TYPE2API_URL", "http://127.0.0.1:8311") +PORT = int(os.environ.get("TYPE_MANAGER_PORT", "8312")) +UA = "TypeCLI/1.0.0" + +POOL_LOCK = threading.Lock() +LOG = [] + + +def log(msg): + LOG.append("[%s] %s" % (time.strftime("%H:%M:%S"), msg)) + del LOG[:-200] + print(msg, flush=True) + + +def api(method, url, body=None, form=None, headers=None, timeout=30): + h = {"Content-Type": "application/json", "User-Agent": UA} + if headers: + h.update(headers) + data = None + if body is not None: + data = json.dumps(body).encode() + if form is not None: + data = urllib.parse.urlencode(form).encode() + h["Content-Type"] = "application/x-www-form-urlencoded" + req = urllib.request.Request(url, data=data, headers=h, method=method) + try: + r = urllib.request.urlopen(req, timeout=timeout) + raw = r.read() + status = r.status + except urllib.error.HTTPError as e: + raw = e.read() + status = e.code + except Exception as e: + return 0, {"error": str(e)} + try: + parsed = json.loads(raw or b"{}") + except Exception: + parsed = {"_raw": raw.decode("utf-8", "replace")[:300]} + return status, parsed + + +# ---------------------------------------------------------------- pool +def load_pool(): + if not os.path.exists(POOL_PATH): + return [] + try: + with open(POOL_PATH, encoding="utf-8") as f: + return json.load(f) + except Exception: + return [] + + +def save_pool(pool): + tmp = POOL_PATH + ".tmp" + with open(tmp, "w", encoding="utf-8") as f: + json.dump(pool, f, indent=1) + os.replace(tmp, POOL_PATH) + + +def redact(acct): + return { + "email": acct.get("email"), + "org": (acct.get("org") or {}).get("slug") if isinstance(acct.get("org"), dict) else acct.get("org"), + "created_at": acct.get("created_at"), + "last_refresh": acct.get("last_refresh"), + "last_status": acct.get("last_status"), + "access_token_len": acct.get("access_token_len") or len(acct.get("access_token") or ""), + "has_refresh": bool(acct.get("refresh_token")), + } + + +# ---------------------------------------------------------------- autoreg (full_reg.py flow) +def autoreg_one(org="reform-org"): + user = "tt" + "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) + # dynamic mail.tm domain (hardcoded domains go stale -> 422 ConstraintViolation) + st, doms = api("GET", "https://api.mail.tm/domains") + dom = None + if st == 200 and isinstance(doms, dict): + for d in doms.get("hydra:member", []): + if d.get("isActive"): + dom = d.get("domain") + break + if not dom: + raise RuntimeError("mail.tm domains unavailable: %s" % str(doms)[:120]) + email = user + "@" + dom + mpwd = "Tp" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!" + + st, acc = api("POST", "https://api.mail.tm/accounts", body={"address": email, "password": mpwd}) + if st not in (200, 201): + raise RuntimeError("mail.tm create %s: %s" % (st, str(acc)[:150])) + st, tok = api("POST", "https://api.mail.tm/token", body={"address": email, "password": mpwd}) + mt = tok.get("token") + if not mt: + raise RuntimeError("mail.tm no token: %s" % str(tok)[:150]) + log("mail created %s" % email) + + st, reg = api("POST", "https://auth.type.com/agent/identity", + body={"type": "service_auth", "login_hint": email}) + claim = reg.get("claim") or {} + if not claim.get("token"): + raise RuntimeError("service_auth %s: %s" % (st, str(reg)[:200])) + cat = urllib.parse.parse_qs( + urllib.parse.urlparse(claim["attempt"]["verification_uri"]).query)["token"][0] + log("claim ok (HTTP %s)" % st) + + st, s = api("POST", "https://api.type.com/api/agent-signup/start", + body={"claimAttemptToken": cat, "email": email, "organizationName": org}) + if not s.get("signupToken"): + raise RuntimeError("signup/start %s: %s" % (st, str(s)[:200])) + log("signup started, waiting for email code") + + code = None + for _ in range(30): + time.sleep(6) + st, msgs = api("GET", "https://api.mail.tm/messages", + headers={"Authorization": "Bearer " + mt}) + lst = msgs.get("hydra:member", msgs if isinstance(msgs, list) else []) + for m in lst: + frm = (m.get("from") or {}).get("address", "") + if "type" in (frm + m.get("subject", "")).lower(): + st2, full = api("GET", "https://api.mail.tm/messages/" + m["id"], + headers={"Authorization": "Bearer " + mt}) + body_text = full.get("text", "") or json.dumps(full.get("html", [])) + codes = re.findall(r"\b(\d{6})\b", body_text) + if codes: + code = codes[-1] + break + if code: + break + if not code: + raise RuntimeError("no email code within 180s") + log("email code %s" % code) + + st, v = api("POST", "https://api.type.com/api/agent-signup/verify", + body={"code": code, "signupToken": s["signupToken"]}) + uc = (v.get("claim") or {}).get("userCode") + if not uc: + raise RuntimeError("verify %s: %s" % (st, str(v)[:200])) + log("verified, org=%s" % ((v.get("organization") or {}).get("slug"))) + + st, done = api("POST", "https://auth.type.com/agent/identity/claim/complete", + body={"claim_token": claim["token"], "user_code": uc}) + ident = done.get("identity") or {} + if not ident.get("assertion"): + raise RuntimeError("claim/complete %s: %s" % (st, str(done)[:200])) + log("identity issued") + + st, tok2 = api("POST", "https://auth.type.com/oauth2/token", form={ + "assertion": ident["assertion"], + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + }) + at = tok2.get("access_token") + log("exchange HTTP %s, token len %d" % (st, len(at or ""))) + if not at: + raise RuntimeError("exchange %s: %s" % (st, str(tok2)[:200])) + + return { + "email": email, + "mail_pwd": mpwd, + "mt_token": mt, + "assertion": ident.get("assertion"), + "refresh_token": (ident.get("refresh_token") or {}).get("value"), + "token_endpoint": "https://auth.type.com/oauth2/token", + "org": v.get("organization"), + "user_created": v.get("organizationCreated"), + "created_at": time.strftime("%Y-%m-%d %H:%M:%S"), + "last_refresh": time.strftime("%Y-%m-%d %H:%M:%S"), + "last_status": "exchange:%s" % st, + "access_token_len": len(at), + "access_token": at, + } + + +# ---------------------------------------------------------------- refresh (live-verified flow) +def refresh_one(acct): + rt = acct.get("refresh_token") + if not rt: + raise RuntimeError("no refresh_token") + st, body = api("POST", "https://auth.type.com/agent/identity", + body={"refresh_token": rt, "type": "refresh"}) + if st != 200: + raise RuntimeError("identity refresh %s: %s" % (st, str(body)[:150])) + ident = body.get("identity") or {} + new_rt = (ident.get("refresh_token") or {}).get("value") + if ident.get("assertion"): + acct["assertion"] = ident["assertion"] + if new_rt: + acct["refresh_token"] = new_rt + st2, tok = api("POST", acct.get("token_endpoint", "https://auth.type.com/oauth2/token"), + form={ + "assertion": acct["assertion"], + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + }) + at = tok.get("access_token") + if not at: + raise RuntimeError("exchange %s: %s" % (st2, str(tok)[:150])) + acct["access_token"] = at + acct["access_token_len"] = len(at) + acct["last_refresh"] = time.strftime("%Y-%m-%d %H:%M:%S") + acct["last_status"] = "refresh:%s/exchange:%s" % (st, st2) + return acct + + +# ---------------------------------------------------------------- http +class Handler(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _send(self, code, payload, ctype="application/json; charset=utf-8"): + if isinstance(payload, (dict, list)): + body = json.dumps(payload, ensure_ascii=False).encode("utf-8") + elif isinstance(payload, str): + body = payload.encode("utf-8") + else: + body = payload + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path in ("/", "/index.html", "/dashboard"): + try: + with open(DASH_PATH, "rb") as f: + self._send(200, f.read(), "text/html; charset=utf-8") + except Exception as e: + self._send(500, {"error": str(e)}) + elif self.path == "/api/status": + st, gw = api("GET", GATEWAY_URL + "/health", timeout=5) + with POOL_LOCK: + pool = load_pool() + self._send(200, { + "gateway": {"up": st == 200, "port": 8311, "body": gw}, + "pool": { + "count": len(pool), + "with_token": sum(1 for a in pool if a.get("access_token")), + }, + "log": LOG[-30:], + "now": time.strftime("%Y-%m-%d %H:%M:%S"), + }) + elif self.path == "/api/accounts": + with POOL_LOCK: + pool = load_pool() + self._send(200, [redact(a) for a in pool]) + elif self.path.split("?")[0] == "/files": + # agent-visible file browser (repo dir only; secrets redacted) + qs = urllib.parse.urlparse(self.path).query + q = urllib.parse.parse_qs(qs) + rel = (q.get("path") or [""])[0].replace("\\", "/").lstrip("/") + base = os.path.dirname(ROOT) # type-toolkit dir + target = os.path.normpath(os.path.join(base, rel)) + if not target.startswith(base): + self._send(403, {"error": "outside whitelist"}) + return + secret_names = {"pool.json", "acct.json", "api_token.json"} + try: + if os.path.isdir(target): + entries = [] + for name in sorted(os.listdir(target)): + if name in ("__pycache__", ".git"): + continue + p = os.path.join(target, name) + entries.append({"name": name, "dir": os.path.isdir(p), + "size": os.path.getsize(p) if os.path.isfile(p) else 0}) + self._send(200, {"path": rel or ".", "type": "dir", "entries": entries}) + elif os.path.isfile(target): + if os.path.basename(target) in secret_names or os.path.getsize(target) > 2 * 1024 * 1024: + self._send(200, {"path": rel, "type": "secret-or-big", + "note": "content withheld (credentials file or >2MB)"}) + else: + with open(target, "rb") as f: + self._send(200, {"path": rel, "type": "file", + "content": f.read().decode("utf-8", errors="replace")}) + else: + self._send(404, {"error": "not found"}) + except Exception as e: + self._send(500, {"error": str(e)}) + else: + self._send(404, {"error": "not found"}) + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + req = {} + if length: + try: + req = json.loads(self.rfile.read(length) or b"{}") + except Exception: + req = {} + if self.path == "/api/autoreg": + org = (req.get("org") or "reform-org").strip() or "reform-org" + try: + acct = autoreg_one(org) + with POOL_LOCK: + pool = load_pool() + pool.append(acct) + save_pool(pool) + log("autoreg OK %s -> %s" % (acct["email"], redact(acct)["org"])) + self._send(200, {"ok": True, "account": redact(acct)}) + except Exception as e: + log("autoreg FAIL: %s" % e) + self._send(500, {"ok": False, "error": str(e)}) + elif self.path == "/api/refresh": + with POOL_LOCK: + pool = load_pool() + results = [] + for a in pool: + try: + refresh_one(a) + results.append({"email": a["email"], "ok": True}) + log("refresh OK %s" % a["email"]) + except Exception as e: + a["last_status"] = "error:%s" % str(e)[:80] + results.append({"email": a["email"], "ok": False, "error": str(e)}) + log("refresh FAIL %s: %s" % (a["email"], str(e)[:100])) + with POOL_LOCK: + save_pool(pool) + self._send(200, results) + else: + self._send(404, {"error": "not found"}) + + +def main(): + log("manager on :%d (gateway %s)" % (PORT, GATEWAY_URL)) + ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever() + + +if __name__ == "__main__": + main() diff --git a/tools.json b/tools.json new file mode 100644 index 0000000..6b26433 --- /dev/null +++ b/tools.json @@ -0,0 +1,81 @@ +{ + "tools": [ + { + "type": "function", + "function": { + "name": "type_autoreg", + "description": "Register ONE new type.com agent account (mail.tm dynamic domain -> auth.type.com/agent/identity -> agent-signup start/verify -> jwt-bearer exchange). Takes 60-180s. Account lands in the gateway pool.", + "parameters": { + "type": "object", + "properties": { + "org": {"type": "string", "description": "Organization slug for signup. Default: reform-org", "default": "reform-org"} + } + } + } + }, + { + "type": "function", + "function": { + "name": "type_pool_refresh", + "description": "Refresh identity tokens for ALL accounts in the pool (rotating refresh_token + jwt-bearer re-exchange). Call when upstream returns 401/token expired.", + "parameters": {"type": "object", "properties": {}} + } + }, + { + "type": "function", + "function": { + "name": "type_status", + "description": "Manager status: gateway up/down (:8311), pool count, recent log lines.", + "parameters": {"type": "object", "properties": {}} + } + }, + { + "type": "function", + "function": { + "name": "type_accounts", + "description": "List pool accounts (redacted — no tokens): email, org, token lengths, last status.", + "parameters": {"type": "object", "properties": {}} + } + }, + { + "type": "function", + "function": { + "name": "tt_files", + "description": "Browse/read the type-toolkit repo from the agent. Directory listing or file content (<=2MB). Credential files (pool.json, acct.json, api_token.json) are withheld automatically.", + "parameters": { + "type": "object", + "properties": { + "path": {"type": "string", "description": "Repo-relative path, e.g. '' (root), 'server', 'autoreg/gh_autoreg.py', 'USAGE.md'", "default": ""} + } + } + } + }, + { + "type": "function", + "function": { + "name": "type_chat", + "description": "OpenAI-compatible chat completion via the gateway (:8311) — pool-backed rotation. NOTE: upstream api.type.com currently returns 401 on agent tokens (aud=client policy); status is proxied verbatim.", + "parameters": { + "type": "object", + "properties": { + "model": {"type": "string", "description": "Model id from /v1/models"}, + "messages": {"type": "array", "items": {"type": "object"}, "description": "Chat messages [{role, content}]"} + }, + "required": ["model", "messages"] + } + } + } + ], + "endpoints": { + "manager": "http://127.0.0.1:8312", + "gateway": "http://127.0.0.1:8311", + "tool_map": { + "type_autoreg": "POST manager:/api/autoreg {org}", + "type_pool_refresh": "POST manager:/api/refresh", + "type_status": "GET manager:/api/status", + "type_accounts": "GET manager:/api/accounts", + "tt_files": "GET manager:/files?path=...", + "type_chat": "POST gateway:/v1/chat/completions" + } + } +}