recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
@@ -0,0 +1,12 @@
|
|||||||
|
# TokenHarbor account password used for every pool login
|
||||||
|
TOKENHARBOR_PASSWORD=*** secrets into .env, never commit
|
||||||
|
# Key-aggregator gateway (th_local_api / claim push target)
|
||||||
|
TH_GATEWAY_URL=https://gateway.example.com/th
|
||||||
|
TH_GATEWAY_KEY=***
|
||||||
|
# Gmail backup mode
|
||||||
|
TH_GMAIL_USER=your-inbox@gmail.com
|
||||||
|
TH_GMAIL_APP_PASSWORD=*** IMAP
|
||||||
|
# VPS for new-api deploy (th_sync_vps.py)
|
||||||
|
VPS_HOST=YOUR_VPS_IP
|
||||||
|
VPS_USER=root
|
||||||
|
VPS_SSH_KEY=~/.ssh/id_ed25519
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
.env
|
||||||
|
*.session
|
||||||
|
tokenharbor_keys.txt
|
||||||
|
working_mails.txt
|
||||||
|
th_*_state.json
|
||||||
|
th_vps_deployed.json
|
||||||
|
_good_proxies.txt
|
||||||
|
__pycache__/
|
||||||
|
*.lock
|
||||||
|
*.log
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# TokenHarbor Auto-Reg Farm
|
||||||
|
|
||||||
|
Full pipeline for mass-registering [TokenHarbor](https://tokenharbor.ai) accounts, harvesting `thk_live_*` API keys and deploying them to a new-api VPS gateway as round-robin channels.
|
||||||
|
|
||||||
|
> **Note (Oct 2026):** the $5 welcome gift has been turned off by TokenHarbor. The claim step (`claim_gift`) now no-ops / fails gracefully — the rest of the pipeline (register -> verify -> API key -> deploy, free models) still works.
|
||||||
|
|
||||||
|
**Scale achieved:** 762 accounts processed, 1064 keys harvested, 357+ keys deployed as new-api channels (claude-haiku-5.5, mimo, deepseek-flash `:free` models).
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
t-online.de mail pool (17k accounts, IMAP)
|
||||||
|
|
|
||||||
|
v
|
||||||
|
th_tonline_claim.py -- Chrome CDP :9222 --> tokenharbor.ai
|
||||||
|
login -> verify email (IMAP) -> claim $5 -> create API key
|
||||||
|
|
|
||||||
|
v
|
||||||
|
tokenharbor_keys.txt (email | thk_live_... | timestamp)
|
||||||
|
|
|
||||||
|
+---> push to key-aggregator gateway (POST /provider/add)
|
||||||
|
+---> th_sync_vps.py --> new-api channels on VPS (1 key = 1 channel)
|
||||||
|
|
||||||
|
th_pipeline.py = watchdog loop: CDP alive -> claim chunk -> sync VPS -> repeat
|
||||||
|
th_proxy_router.py = rotating upstream proxy (127.0.0.1:8077) for fresh exit IPs
|
||||||
|
```
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `th_tonline_claim.py` | **Main worker.** t-online.de pool: login -> trigger verify -> IMAP wait -> verify -> $5 claim -> API key -> gateway push |
|
||||||
|
| `th_gmail_reg.py` | Backup mode: Gmail `+alias` signup flow (alias delivery gets blocked after first account) |
|
||||||
|
| `th_local_api.py` | Local HTTP API: `/register?count=N`, `/status`, `/keys`, `/push-all`, `/check-all-balances` |
|
||||||
|
| `th_sync_vps.py` | Validate new keys (live `/v1/models`) -> stop new-api -> INSERT channels+abilities into `one-api.db` -> start |
|
||||||
|
| `th_pipeline.py` | Endless loop: CDP watchdog + claim chunks + auto-sync. Lock file prevents double instances |
|
||||||
|
| `th_proxy_router.py` | Rotating HTTP/CONNECT proxy for Chrome `--proxy-server=http://127.0.0.1:8077` |
|
||||||
|
| `th_reg_v2.py` | Signup-mode variant (fresh registration instead of pool login) |
|
||||||
|
| `th_verify_fix.py` | Re-runs verify step for accounts stuck unverified |
|
||||||
|
| `th_batch_runner.py` | Simple batch wrapper |
|
||||||
|
| `th_stealth.py` | Camoufox/playwright stealth variant |
|
||||||
|
| `th_parallel.py` | Multi-tab parallel CDP variant |
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 0. secrets into .env (see .env.example)
|
||||||
|
cp .env.example .env # fill values
|
||||||
|
|
||||||
|
# 1. mail pool: email:password lines, one per account (t-online.de IMAP)
|
||||||
|
# -> working_mails.txt
|
||||||
|
|
||||||
|
# 2. Chrome with CDP (Chrome 151+ REQUIRES --remote-allow-origins=*)
|
||||||
|
chrome.exe --remote-debugging-port=9222 --remote-allow-origins=* --user-data-dir=%USERPROFILE%/.chrome-cdp-profile
|
||||||
|
|
||||||
|
# 3. optional rotating proxy
|
||||||
|
python th_proxy_router.py &
|
||||||
|
|
||||||
|
# 4. farm N accounts
|
||||||
|
python th_tonline_claim.py 100
|
||||||
|
|
||||||
|
# 5. deploy fresh keys to VPS new-api
|
||||||
|
python th_sync_vps.py
|
||||||
|
|
||||||
|
# or full auto loop
|
||||||
|
python th_pipeline.py 300 15
|
||||||
|
```
|
||||||
|
|
||||||
|
## Critical pitfalls (learned the hard way)
|
||||||
|
|
||||||
|
1. **$5 gift requires verified email.** `/api/welcome/claim` returns `403 email_not_verified` otherwise. Dashboard "Verify your email" button sends a FRESH letter — use it, then IMAP-wait with baseline UIDs only (60s timeout).
|
||||||
|
2. **Gmail `+alias` gets blocked** by TokenHarbor after the first account — letters stop arriving. Use a real mail pool (t-online.de works).
|
||||||
|
3. **React inputs:** `input.value = x` does nothing. You must use the native setter:
|
||||||
|
```js
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set;
|
||||||
|
nativeSet.call(inp, v); inp.dispatchEvent(new Event('input',{bubbles:true}));
|
||||||
|
```
|
||||||
|
4. **Next.js routing:** `window.location.href = '/dashboard/api-keys'` leaves the page in LOADING forever. Use CDP `Page.navigate` + wait for `"API keys" in text and "LOADING" not in text`.
|
||||||
|
5. **Hidden buttons:** API-keys page has many invisible `Create key` buttons from other rows — always check `b.offsetParent !== null && !b.disabled`.
|
||||||
|
6. **Gift claim is two-step:** header button ("1 gift ready to claim") opens modal, THEN "Claim" inside modal, 2s sleep between.
|
||||||
|
7. **Rate limit:** >1 account/min starts rejecting signups (redirect to `/login?mode=signup`). Sleep 2s+, back off to 5-10s on mass fails.
|
||||||
|
8. **new-api SQLite writes:** ALWAYS `systemctl stop new-api` before writing `one-api.db`, start after — otherwise GORM/WAL cache drops your channels on restart.
|
||||||
|
9. **API key creation fails ~7-8%** (Next.js race) — normal, move on.
|
||||||
|
10. **Orphan workers:** killing the pipeline does NOT kill child `th_tonline_claim.py` — they fight over CDP and produce 0 keys. Kill by cmdline match first (`psutil`).
|
||||||
|
11. **free-models toggle:** some accounts have free models OFF -> channel returns 403 on `mimo-*:free`. Probe each channel, strip mimo from models+abilities if off.
|
||||||
|
12. **Channel config that survives:** `auto_ban=0`, `weight=10`, `RetryTimes=10`, `RetryCooldownSeconds=90`.
|
||||||
|
|
||||||
|
## new-api channel schema (per key)
|
||||||
|
|
||||||
|
- `type=1, status=1, base_url=https://tokenharbor.ai, tag=tokenharbor`
|
||||||
|
- `models`: `claude-haiku-5.5,mimo-v2.6-flash,mimo-v2.5,deepseek-v4.1-flash-th,deepseek-v4-flash-th`
|
||||||
|
- `model_mapping`: public name -> `<upstream>:free`
|
||||||
|
- `abilities`: one row per model
|
||||||
|
|
||||||
|
## Key format
|
||||||
|
|
||||||
|
`thk_live_` + 64 chars `[a-zA-Z0-9_-]`. Validate with `GET https://tokenharbor.ai/v1/models` + `Authorization: Bearer <key>`.
|
||||||
|
|
||||||
|
## Channel
|
||||||
|
|
||||||
|
More farms, gateways and free-tier abuse writeups: [@AlStack](https://t.me/AlStack)
|
||||||
|
|
||||||
|
## Disclaimer
|
||||||
|
|
||||||
|
Research/automation toolkit. Bring your own mail pool, proxies and infrastructure. Secrets live in `.env` (gitignored) — nothing sensitive in this repo.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
python-dotenv
|
||||||
|
playwright
|
||||||
|
websocket-client
|
||||||
|
# after install: python -m playwright install chromium
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
TokenHarbor batch runner: runs multiple batches of th_tonline_claim.py
|
||||||
|
until we have enough keys.
|
||||||
|
"""
|
||||||
|
# __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, json, time, sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
STATE_FILE = Path(__file__).parent / "th_tonline_state.json"
|
||||||
|
TARGET = 200 # Total target accounts
|
||||||
|
BATCH_SIZE = 100
|
||||||
|
|
||||||
|
def restart_chrome():
|
||||||
|
"""Kill and restart Chrome with CDP"""
|
||||||
|
subprocess.run("taskkill /F /IM chrome.exe 2>nul", shell=True)
|
||||||
|
time.sleep(2)
|
||||||
|
chrome_temp = str(_w("AppData/Local/Temp/chrome_cdp"))
|
||||||
|
subprocess.Popen([
|
||||||
|
r"C:\Program Files\Google\Chrome\Application\chrome.exe",
|
||||||
|
"--remote-debugging-port=9222",
|
||||||
|
"--remote-allow-origins=*",
|
||||||
|
f"--user-data-dir={chrome_temp}",
|
||||||
|
"--no-first-run",
|
||||||
|
"--no-default-browser-check",
|
||||||
|
"about:blank"
|
||||||
|
])
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
while True:
|
||||||
|
state = json.load(open(STATE_FILE)) if STATE_FILE.exists() else {"done": [], "fail": []}
|
||||||
|
done = len(state["done"])
|
||||||
|
|
||||||
|
if done >= TARGET:
|
||||||
|
print(f"\nTARGET REACHED: {done} done, stopping")
|
||||||
|
break
|
||||||
|
|
||||||
|
remaining = TARGET - done
|
||||||
|
batch = min(BATCH_SIZE, remaining)
|
||||||
|
print(f"\nRunning batch: {batch} accounts (have {done}, need {TARGET})")
|
||||||
|
|
||||||
|
# Check if Chrome is running
|
||||||
|
import urllib.request
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen("http://127.0.0.1:9222/json/version", timeout=5)
|
||||||
|
except:
|
||||||
|
print("Chrome not running, restarting...")
|
||||||
|
restart_chrome()
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
["python", "-u", "th_tonline_claim.py", str(batch)],
|
||||||
|
cwd=Path(__file__).parent,
|
||||||
|
capture_output=False,
|
||||||
|
timeout=600
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
print(f"Batch failed with exit code {result.returncode}")
|
||||||
|
# Check if Chrome died
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen("http://127.0.0.1:9222/json/version", timeout=5)
|
||||||
|
except:
|
||||||
|
restart_chrome()
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Update state
|
||||||
|
state = json.load(open(STATE_FILE))
|
||||||
|
done = len(state["done"])
|
||||||
|
print(f"Progress: {done}/{TARGET}")
|
||||||
|
|
||||||
|
print("Done!")
|
||||||
+283
@@ -0,0 +1,283 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Fast Gmail-alias TokenHarbor auto-reg with $5 gift claim.
|
||||||
|
Uses your-inbox+th{N}@gmail.com → all emails go to one inbox.
|
||||||
|
"""
|
||||||
|
import json, time, re, ssl, sys, threading
|
||||||
|
from pathlib import Path
|
||||||
|
from datetime import datetime
|
||||||
|
from urllib.request import urlopen, Request
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
import websocket
|
||||||
|
import imaplib
|
||||||
|
import email as em
|
||||||
|
import os
|
||||||
|
# Account passwords live in <project root>/.env (gitignored). Guarded import:
|
||||||
|
# python-dotenv is not a declared dependency of these standalone scripts.
|
||||||
|
try:
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# ── Config ──
|
||||||
|
BASE_URL = "https://tokenharbor.ai"
|
||||||
|
PASSWORD = os.environ["TOKENHARBOR_PASSWORD"]
|
||||||
|
CDP_HOST = "127.0.0.1"
|
||||||
|
CDP_PORT = 9222
|
||||||
|
GMAIL = os.environ.get("TH_GMAIL_USER", "your-inbox@gmail.com")
|
||||||
|
GMAIL_PASS = os.environ["GMAIL_PASS"]
|
||||||
|
GATEWAY_URL = "https://gateway.example.com/th"
|
||||||
|
GATEWAY_KEY = os.environ.get("TH_GATEWAY_KEY", "")
|
||||||
|
KEYS_FILE = Path(__file__).parent / "tokenharbor_keys.txt"
|
||||||
|
STATE_FILE = Path(__file__).parent / "th_gmail_state.json"
|
||||||
|
|
||||||
|
state = {"keys": [], "next_id": 1, "done": 0, "fail": 0}
|
||||||
|
|
||||||
|
def load_state():
|
||||||
|
global state
|
||||||
|
if STATE_FILE.exists():
|
||||||
|
try: state = json.loads(STATE_FILE.read_text())
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
def save_state():
|
||||||
|
STATE_FILE.write_text(json.dumps(state, indent=2, default=str))
|
||||||
|
|
||||||
|
# ── CDP ──
|
||||||
|
def js(cdp, code, timeout=15):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Runtime.evaluate",
|
||||||
|
"params": {"expression": code, "returnByValue": True, "awaitPromise": True}}))
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
cdp["ws"].settimeout(1)
|
||||||
|
try:
|
||||||
|
data = json.loads(cdp["ws"].recv())
|
||||||
|
if data.get("id") == mid:
|
||||||
|
r = data.get("result", {}).get("result", {})
|
||||||
|
return r.get("value"), data.get("subtype")
|
||||||
|
except: pass
|
||||||
|
return None, "timeout"
|
||||||
|
|
||||||
|
def nav(cdp, url):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Page.navigate", "params": {"url": url}}))
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
def connect_cdp():
|
||||||
|
try:
|
||||||
|
tabs = json.loads(urlopen(f"http://{CDP_HOST}:{CDP_PORT}/json").read())
|
||||||
|
req = Request(f"http://{CDP_HOST}:{CDP_PORT}/json/new?url=about:blank", method="PUT")
|
||||||
|
data = json.loads(urlopen(req).read())
|
||||||
|
ws = websocket.create_connection(data["webSocketDebuggerUrl"], timeout=10)
|
||||||
|
return {"ws": ws, "id": 0}
|
||||||
|
except Exception as e:
|
||||||
|
print(f"CDP FAILED: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ── Gmail IMAP ──
|
||||||
|
def get_verify_link_gmail(alias_email, timeout=60):
|
||||||
|
"""Get verification link from Gmail for a specific alias."""
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
try:
|
||||||
|
mail = imaplib.IMAP4_SSL("imap.gmail.com", 993, ssl_context=ctx, timeout=10)
|
||||||
|
mail.login(GMAIL, GMAIL_PASS)
|
||||||
|
mail.select("INBOX")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" Gmail login failed: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
try:
|
||||||
|
status, data = mail.search(None, f'TO "{alias_email}"')
|
||||||
|
if status == "OK" and data[0]:
|
||||||
|
for mid in reversed(data[0].split()[-3:]):
|
||||||
|
status, msg_data = mail.fetch(mid, "(RFC822)")
|
||||||
|
if status != "OK": continue
|
||||||
|
msg = em.message_from_bytes(msg_data[0][1])
|
||||||
|
body = ""
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.get_content_type() in ("text/plain", "text/html"):
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if payload: body += payload.decode("utf-8", errors="replace")
|
||||||
|
else:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload: body = payload.decode("utf-8", errors="replace")
|
||||||
|
links = re.findall(r'https://tokenharbor\.ai/verify-email\?token=[^\s"<>]+', body)
|
||||||
|
if links:
|
||||||
|
mail.logout()
|
||||||
|
return links[0]
|
||||||
|
time.sleep(3)
|
||||||
|
except: time.sleep(5)
|
||||||
|
try: mail.logout()
|
||||||
|
except: pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ── Registration ──
|
||||||
|
def register_one(cdp, alias_email, alias_id):
|
||||||
|
nav(cdp, f"{BASE_URL}/login?mode=signup")
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
js(cdp, f"""
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ nativeSet.call(e, '{alias_email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ nativeSet.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Create account')) { b.click(); break; } }""")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
time.sleep(5)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
return None, f"signup failed: {url}"
|
||||||
|
|
||||||
|
# Verify email via Gmail
|
||||||
|
print(f" Waiting for verify email...", file=sys.stderr)
|
||||||
|
verify_link = get_verify_link_gmail(alias_email, timeout=60)
|
||||||
|
if not verify_link:
|
||||||
|
print(f" No verify email — skipping $5 claim", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
nav(cdp, verify_link)
|
||||||
|
time.sleep(4)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "verify=success" in str(url) or "dashboard" in str(url):
|
||||||
|
print(f" Email verified!", file=sys.stderr)
|
||||||
|
|
||||||
|
# Claim $5 gift
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard")
|
||||||
|
time.sleep(3)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('gift') && b.textContent.includes('ready')) { b.click(); break; } }""")
|
||||||
|
time.sleep(2)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Claim') { b.click(); break; } }""")
|
||||||
|
time.sleep(3)
|
||||||
|
print(f" $5 claimed!", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
print(f" Verify failed: {url}", file=sys.stderr)
|
||||||
|
|
||||||
|
# Create API key
|
||||||
|
# Use Page.navigate for full page load
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Page.navigate",
|
||||||
|
"params": {"url": f"{BASE_URL}/dashboard/api-keys"}}))
|
||||||
|
time.sleep(8)
|
||||||
|
|
||||||
|
# Wait for page to fully load
|
||||||
|
for _ in range(10):
|
||||||
|
t, _ = js(cdp, "document.body.innerText")
|
||||||
|
if "API keys" in str(t) and "LOADING" not in str(t) and "Create and manage" in str(t):
|
||||||
|
break
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
# Click "+ New key" (visible button only)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim().includes('New key') && b.offsetParent !== null) { b.click(); break; } }""")
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
label = f"th{alias_id}"
|
||||||
|
# Fill label (visible input only)
|
||||||
|
js(cdp, f"""
|
||||||
|
var inputs = document.querySelectorAll('input[type="text"]');
|
||||||
|
for(var inp of inputs) {{
|
||||||
|
if(inp.offsetParent !== null) {{
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
nativeSet.call(inp, '{label}');
|
||||||
|
inp.dispatchEvent(new Event('input', {{bubbles:true}}));
|
||||||
|
inp.dispatchEvent(new Event('change', {{bubbles:true}}));
|
||||||
|
break;
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
""")
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
# Click "Create key" (visible, enabled)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Create key' && !b.disabled && b.offsetParent !== null) {
|
||||||
|
b.click(); break;
|
||||||
|
} }""")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
page, _ = js(cdp, "document.body.innerText")
|
||||||
|
match = re.search(r'thk_live_[a-zA-Z0-9_-]{40,}', str(page))
|
||||||
|
api_key = match.group(0) if match else None
|
||||||
|
|
||||||
|
if api_key:
|
||||||
|
with open(KEYS_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{alias_email} | {api_key} | {datetime.now().isoformat()}\n")
|
||||||
|
return api_key, None
|
||||||
|
return None, "no key on page"
|
||||||
|
|
||||||
|
# ── Push to VPS ──
|
||||||
|
def push_key(api_key):
|
||||||
|
try:
|
||||||
|
data = json.dumps({"provider": "tokenharbor", "key": api_key}).encode()
|
||||||
|
req = Request(f"{GATEWAY_URL}/provider/add?provider=tokenharbor",
|
||||||
|
data=data,
|
||||||
|
headers={"Content-Type": "application/json", "Authorization": f"Bearer {GATEWAY_KEY}"},
|
||||||
|
method="POST")
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
return json.loads(resp.read()), resp.status
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}, 500
|
||||||
|
|
||||||
|
# ── Worker ──
|
||||||
|
def worker(count, start_id):
|
||||||
|
global state
|
||||||
|
cdp = connect_cdp()
|
||||||
|
if not cdp:
|
||||||
|
print("No CDP — aborting", file=sys.stderr)
|
||||||
|
return
|
||||||
|
|
||||||
|
for i in range(count):
|
||||||
|
alias_id = start_id + i
|
||||||
|
alias_email = f"your-inbox+th{alias_id}@gmail.com"
|
||||||
|
print(f"[{i+1}/{count}] REG: {alias_email}", file=sys.stderr)
|
||||||
|
|
||||||
|
key, err = register_one(cdp, alias_email, alias_id)
|
||||||
|
if key:
|
||||||
|
state["done"] += 1
|
||||||
|
state["keys"].append({"email": alias_email, "key": key, "label": f"th{alias_id}",
|
||||||
|
"pushed": False, "created": datetime.now().isoformat()})
|
||||||
|
|
||||||
|
# Push immediately
|
||||||
|
result, status = push_key(key)
|
||||||
|
if status == 200:
|
||||||
|
state["keys"][-1]["pushed"] = True
|
||||||
|
print(f" OK + PUSHED: {key[:25]}...", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
print(f" OK (push failed): {key[:25]}...", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
state["fail"] += 1
|
||||||
|
print(f" FAIL: {err}", file=sys.stderr)
|
||||||
|
|
||||||
|
save_state()
|
||||||
|
|
||||||
|
# Small delay between registrations to avoid rate limiting
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
cdp["ws"].close()
|
||||||
|
print(f"\nDONE: {state['done']} OK, {state['fail']} FAIL", file=sys.stderr)
|
||||||
|
|
||||||
|
# ── Main ──
|
||||||
|
if __name__ == "__main__":
|
||||||
|
load_state()
|
||||||
|
count = int(sys.argv[1]) if len(sys.argv) > 1 else 10
|
||||||
|
start_id = state.get("next_id", 1)
|
||||||
|
print(f"Starting {count} registrations from th{start_id}...", file=sys.stderr)
|
||||||
|
worker(count, start_id)
|
||||||
|
state["next_id"] = start_id + count
|
||||||
|
save_state()
|
||||||
|
print(f"Final: {state['done']}/{count} done, {state['fail']} fail", file=sys.stderr)
|
||||||
+562
@@ -0,0 +1,562 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
th_local_api v2.0 — локальный API авторегистрации TokenHarbor.
|
||||||
|
Регает через локальный CDP, сразу пушит ключи на VPS-шлюз.
|
||||||
|
Swap-механизм: при 0 балансе — замена на свежий ключ.
|
||||||
|
|
||||||
|
Endpoints:
|
||||||
|
POST /register?count=N&push=true — рега N аккаунтов, опционально пуш на VPS
|
||||||
|
GET /status — статистика пула и ключей
|
||||||
|
GET /keys — список всех ключей
|
||||||
|
POST /push?key=thk_... — пуш одного ключа на VPS
|
||||||
|
POST /push-all — пуш всех неотправленных ключей
|
||||||
|
POST /swap?provider=X&dead_key=X — замена сдохшего ключа
|
||||||
|
GET /balance?key=thk_... — проверка баланса ключа
|
||||||
|
GET /health — health check
|
||||||
|
"""
|
||||||
|
# __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, time, re, ssl, imaplib, email as em, sys, threading
|
||||||
|
from pathlib import Path
|
||||||
|
from datetime import datetime
|
||||||
|
from urllib.request import urlopen, Request
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
import urllib.parse
|
||||||
|
import websocket
|
||||||
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||||
|
import os
|
||||||
|
# Account passwords live in <project root>/.env (gitignored). Guarded import:
|
||||||
|
# python-dotenv is not a declared dependency of these standalone scripts.
|
||||||
|
try:
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# ── Config ──
|
||||||
|
BASE_URL = "https://tokenharbor.ai"
|
||||||
|
PASSWORD = os.environ["TOKENHARBOR_PASSWORD"]
|
||||||
|
CDP_HOST = "127.0.0.1"
|
||||||
|
CDP_PORT = 9222
|
||||||
|
GATEWAY_URL = "https://gateway.example.com/th"
|
||||||
|
GATEWAY_KEY = os.environ.get("TH_GATEWAY_KEY", "")
|
||||||
|
POOL_FILE = Path(str(_d("Downloads/Telegram Desktop/working_mails.txt","MAIL_POOL")))
|
||||||
|
KEYS_FILE = Path(__file__).parent / "tokenharbor_keys.txt"
|
||||||
|
STATE_FILE = Path(__file__).parent / "th_local_state.json"
|
||||||
|
API_PORT = 8767
|
||||||
|
|
||||||
|
# ── State ──
|
||||||
|
state = {
|
||||||
|
"keys": [], # [{email, key, label, balance, balance_checked, pushed, dead}]
|
||||||
|
"reg_queue": 0,
|
||||||
|
"reg_done": 0,
|
||||||
|
"reg_fail": 0,
|
||||||
|
"reg_active": False,
|
||||||
|
"last_balance_check": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
def load_state():
|
||||||
|
global state
|
||||||
|
if STATE_FILE.exists():
|
||||||
|
try:
|
||||||
|
state = json.loads(STATE_FILE.read_text())
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def save_state():
|
||||||
|
STATE_FILE.write_text(json.dumps(state, indent=2, default=str))
|
||||||
|
|
||||||
|
def load_pool():
|
||||||
|
with open(POOL_FILE, "r", encoding="utf-8") as f:
|
||||||
|
return [l.strip() for l in f if ":" in l and "@" in l]
|
||||||
|
|
||||||
|
def load_used_emails():
|
||||||
|
used = set()
|
||||||
|
if KEYS_FILE.exists():
|
||||||
|
for line in KEYS_FILE.read_text().splitlines():
|
||||||
|
if "|" in line:
|
||||||
|
used.add(line.split("|")[0].strip())
|
||||||
|
for k in state.get("keys", []):
|
||||||
|
used.add(k.get("email", ""))
|
||||||
|
return used
|
||||||
|
|
||||||
|
|
||||||
|
# ── CDP Helpers ──
|
||||||
|
def js(cdp, code, timeout=15):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Runtime.evaluate",
|
||||||
|
"params": {"expression": code, "returnByValue": True, "awaitPromise": True}}))
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
cdp["ws"].settimeout(1)
|
||||||
|
try:
|
||||||
|
data = json.loads(cdp["ws"].recv())
|
||||||
|
if data.get("id") == mid:
|
||||||
|
r = data.get("result", {}).get("result", {})
|
||||||
|
return r.get("value"), data.get("subtype")
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
return None, "timeout"
|
||||||
|
|
||||||
|
def nav(cdp, url):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Page.navigate", "params": {"url": url}}))
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
def connect_cdp():
|
||||||
|
try:
|
||||||
|
tabs = json.loads(urlopen(f"http://{CDP_HOST}:{CDP_PORT}/json").read())
|
||||||
|
# Always create a new tab for registration — don't reuse logged-in tabs
|
||||||
|
req = Request(f"http://{CDP_HOST}:{CDP_PORT}/json/new?url=about:blank", method="PUT")
|
||||||
|
data = json.loads(urlopen(req).read())
|
||||||
|
ws = websocket.create_connection(data["webSocketDebuggerUrl"], timeout=10)
|
||||||
|
print(f" CDP: new tab {data['id']}", file=sys.stderr)
|
||||||
|
return {"ws": ws, "id": 0}
|
||||||
|
except Exception as e:
|
||||||
|
print(f" CDP FAILED: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ── IMAP ──
|
||||||
|
def get_verify_link(email_addr, email_pass, timeout=30):
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
try:
|
||||||
|
mail = imaplib.IMAP4_SSL("secureimap.t-online.de", 993, ssl_context=ctx, timeout=15)
|
||||||
|
mail.login(email_addr, email_pass)
|
||||||
|
mail.select("INBOX")
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
try:
|
||||||
|
for query in ['(FROM "tokenharbor")', '(FROM "verify@tokenharbor.ai")', 'ALL']:
|
||||||
|
status, data = mail.search(None, query)
|
||||||
|
if status == "OK" and data[0]:
|
||||||
|
for mid in reversed(data[0].split()[-5:]):
|
||||||
|
status, msg_data = mail.fetch(mid, "(RFC822)")
|
||||||
|
if status != "OK":
|
||||||
|
continue
|
||||||
|
msg = em.message_from_bytes(msg_data[0][1])
|
||||||
|
body = ""
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.get_content_type() in ("text/plain", "text/html"):
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if payload:
|
||||||
|
body += payload.decode("utf-8", errors="replace")
|
||||||
|
else:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload:
|
||||||
|
body = payload.decode("utf-8", errors="replace")
|
||||||
|
links = re.findall(r'https://tokenharbor\.ai/verify-email\?token=[^\s"<>]+', body)
|
||||||
|
if links:
|
||||||
|
mail.logout()
|
||||||
|
return links[0]
|
||||||
|
time.sleep(3)
|
||||||
|
except:
|
||||||
|
time.sleep(5)
|
||||||
|
try:
|
||||||
|
mail.logout()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# ── Registration ──
|
||||||
|
def register_one(cdp, email, email_pass):
|
||||||
|
nav(cdp, f"{BASE_URL}/login?mode=signup")
|
||||||
|
time.sleep(3)
|
||||||
|
js(cdp, f"""
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ nativeSet.call(e, '{email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ nativeSet.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Create account')) { b.click(); break; } }""")
|
||||||
|
time.sleep(5)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
time.sleep(5)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
return None, f"signup redirect failed: {url}"
|
||||||
|
|
||||||
|
# Try email verification, but don't fail if it's not found
|
||||||
|
verify_link = get_verify_link(email, email_pass)
|
||||||
|
if verify_link:
|
||||||
|
nav(cdp, verify_link)
|
||||||
|
time.sleep(5)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "verify=success" not in str(url) and "dashboard" not in str(url):
|
||||||
|
print(f" Verify link failed, continuing anyway", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
print(f" No verify email found, continuing anyway", file=sys.stderr)
|
||||||
|
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard")
|
||||||
|
time.sleep(3)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('gift') && b.textContent.includes('ready')) { b.click(); break; } }""")
|
||||||
|
time.sleep(2)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Claim') { b.click(); break; } }""")
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard/api-keys")
|
||||||
|
time.sleep(3)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('New key')) { b.click(); break; } }""")
|
||||||
|
time.sleep(1.5)
|
||||||
|
label = email.split("@")[0][:12]
|
||||||
|
# React-style input — use native value setter
|
||||||
|
js(cdp, f"""var inp = document.querySelector('input[type="text"]');
|
||||||
|
if(inp) {{
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
nativeSet.call(inp, '{label}');
|
||||||
|
inp.dispatchEvent(new Event('input', {{bubbles:true}}));
|
||||||
|
}}""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Create key') && !b.disabled) { b.click(); break; } }""")
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
page, _ = js(cdp, "document.body.innerText")
|
||||||
|
match = re.search(r'thk_live_[a-zA-Z0-9_-]{40,}', str(page))
|
||||||
|
api_key = match.group(0) if match else None
|
||||||
|
|
||||||
|
if api_key:
|
||||||
|
with open(KEYS_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{email} | {api_key} | {datetime.now().isoformat()}\n")
|
||||||
|
return api_key, None
|
||||||
|
return None, "no key on page"
|
||||||
|
|
||||||
|
|
||||||
|
# ── Push to VPS Gateway ──
|
||||||
|
def push_key_to_gateway(provider, api_key, label=""):
|
||||||
|
"""Push a key to the VPS gateway via /provider/add"""
|
||||||
|
try:
|
||||||
|
data = json.dumps({
|
||||||
|
"provider": provider,
|
||||||
|
"key": api_key,
|
||||||
|
"label": label or "auto-reg",
|
||||||
|
}).encode()
|
||||||
|
req = Request(
|
||||||
|
f"{GATEWAY_URL}/provider/add",
|
||||||
|
data=data,
|
||||||
|
headers={
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Authorization": f"Bearer {GATEWAY_KEY}",
|
||||||
|
},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
return json.loads(resp.read()), resp.status
|
||||||
|
except HTTPError as e:
|
||||||
|
return {"error": str(e), "body": e.read().decode()[:200]}, e.code
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}, 500
|
||||||
|
|
||||||
|
|
||||||
|
# ── Balance Check ──
|
||||||
|
def check_balance(api_key):
|
||||||
|
"""Check balance via TokenHarbor API"""
|
||||||
|
try:
|
||||||
|
req = Request(
|
||||||
|
f"{BASE_URL}/v1/models",
|
||||||
|
headers={"Authorization": f"Bearer {api_key}"},
|
||||||
|
)
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
return True, resp.status # key works
|
||||||
|
except HTTPError as e:
|
||||||
|
body = e.read().decode()[:500]
|
||||||
|
if e.code == 401:
|
||||||
|
return False, "invalid"
|
||||||
|
if e.code == 402 or "balance" in body.lower() or "credit" in body.lower():
|
||||||
|
return False, "no_balance"
|
||||||
|
return False, f"error_{e.code}"
|
||||||
|
except Exception as e:
|
||||||
|
return False, str(e)
|
||||||
|
|
||||||
|
|
||||||
|
# ── Registration Worker ──
|
||||||
|
def reg_worker(count, push=True):
|
||||||
|
global state
|
||||||
|
state["reg_active"] = True
|
||||||
|
state["reg_queue"] = count
|
||||||
|
state["reg_done"] = 0
|
||||||
|
state["reg_fail"] = 0
|
||||||
|
save_state()
|
||||||
|
|
||||||
|
cdp = connect_cdp()
|
||||||
|
if not cdp:
|
||||||
|
state["reg_active"] = False
|
||||||
|
save_state()
|
||||||
|
return
|
||||||
|
|
||||||
|
pool = load_pool()
|
||||||
|
used = load_used_emails()
|
||||||
|
available = []
|
||||||
|
for line in pool:
|
||||||
|
email_addr, email_pass = line.split(":", 1)
|
||||||
|
if email_addr not in used:
|
||||||
|
available.append((email_addr, email_pass))
|
||||||
|
if len(available) >= count:
|
||||||
|
break
|
||||||
|
|
||||||
|
for i, (email, pwd) in enumerate(available):
|
||||||
|
try:
|
||||||
|
print(f" [{i+1}/{len(available)}] REG: {email}", file=sys.stderr)
|
||||||
|
key, err = register_one(cdp, email, pwd)
|
||||||
|
if key:
|
||||||
|
print(f" OK: {key[:20]}...", file=sys.stderr)
|
||||||
|
state["reg_done"] += 1
|
||||||
|
state["keys"].append({
|
||||||
|
"email": email,
|
||||||
|
"key": key,
|
||||||
|
"label": email.split("@")[0][:12],
|
||||||
|
"balance": "unknown",
|
||||||
|
"balance_checked": None,
|
||||||
|
"pushed": False,
|
||||||
|
"dead": False,
|
||||||
|
"created": datetime.now().isoformat(),
|
||||||
|
})
|
||||||
|
save_state()
|
||||||
|
|
||||||
|
if push:
|
||||||
|
result, code = push_key_to_gateway("tokenharbor", key, email.split("@")[0][:12])
|
||||||
|
if code == 200:
|
||||||
|
state["keys"][-1]["pushed"] = True
|
||||||
|
save_state()
|
||||||
|
else:
|
||||||
|
print(f" FAIL: {err}", file=sys.stderr)
|
||||||
|
state["reg_fail"] += 1
|
||||||
|
except Exception as e:
|
||||||
|
print(f" ERR: {e}", file=sys.stderr)
|
||||||
|
state["reg_fail"] += 1
|
||||||
|
save_state()
|
||||||
|
|
||||||
|
cdp["ws"].close()
|
||||||
|
state["reg_active"] = False
|
||||||
|
state["reg_queue"] = 0
|
||||||
|
save_state()
|
||||||
|
|
||||||
|
|
||||||
|
# ── HTTP Server ──
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def _json(self, data, code=200):
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Access-Control-Allow-Origin", "*")
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(json.dumps(data, indent=2, default=str).encode())
|
||||||
|
|
||||||
|
def _parse_qs(self):
|
||||||
|
parsed = urllib.parse.urlparse(self.path)
|
||||||
|
return dict(urllib.parse.parse_qsl(parsed.query)), parsed.path
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
params, path = self._parse_qs()
|
||||||
|
|
||||||
|
if path == "/" or path == "":
|
||||||
|
self._json({
|
||||||
|
"service": "th-local-api",
|
||||||
|
"version": "2.0",
|
||||||
|
"endpoints": {
|
||||||
|
"POST /register?count=N&push=true": "register N accounts",
|
||||||
|
"GET /status": "pool + keys stats",
|
||||||
|
"GET /keys": "list all keys",
|
||||||
|
"POST /push?key=thk_...": "push one key to VPS",
|
||||||
|
"POST /push-all": "push all unpushed keys",
|
||||||
|
"POST /swap?provider=X&dead_key=X": "swap dead key",
|
||||||
|
"GET /balance?key=thk_...": "check key balance",
|
||||||
|
"GET /health": "health check",
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
elif path == "/status":
|
||||||
|
pool = load_pool()
|
||||||
|
used = load_used_emails()
|
||||||
|
available = len(pool) - len(used)
|
||||||
|
self._json({
|
||||||
|
"pool": {"total": len(pool), "used": len(used), "available": max(0, available)},
|
||||||
|
"reg": {"active": state["reg_active"], "queue": state["reg_queue"],
|
||||||
|
"done": state["reg_done"], "fail": state["reg_fail"]},
|
||||||
|
"keys": {"total": len(state["keys"]),
|
||||||
|
"pushed": sum(1 for k in state["keys"] if k.get("pushed")),
|
||||||
|
"dead": sum(1 for k in state["keys"] if k.get("dead")),
|
||||||
|
"alive": sum(1 for k in state["keys"] if not k.get("dead")),
|
||||||
|
"unknown_balance": sum(1 for k in state["keys"] if k.get("balance") == "unknown")},
|
||||||
|
"last_balance_check": state.get("last_balance_check"),
|
||||||
|
})
|
||||||
|
|
||||||
|
elif path == "/keys":
|
||||||
|
self._json(state["keys"])
|
||||||
|
|
||||||
|
elif path == "/balance":
|
||||||
|
key = params.get("key", "")
|
||||||
|
if not key.startswith("thk_"):
|
||||||
|
self._json({"error": "invalid key"}, 400)
|
||||||
|
return
|
||||||
|
ok, detail = check_balance(key)
|
||||||
|
# Update state if key is known
|
||||||
|
for k in state["keys"]:
|
||||||
|
if k["key"] == key:
|
||||||
|
k["balance"] = "ok" if ok else detail
|
||||||
|
k["balance_checked"] = datetime.now().isoformat()
|
||||||
|
break
|
||||||
|
state["last_balance_check"] = datetime.now().isoformat()
|
||||||
|
save_state()
|
||||||
|
self._json({"key": key[:20] + "...", "works": ok, "detail": detail})
|
||||||
|
|
||||||
|
elif path == "/health":
|
||||||
|
self._json({"status": "ok", "cdp": connect_cdp() is not None})
|
||||||
|
|
||||||
|
else:
|
||||||
|
self._json({"error": "not found"}, 404)
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
params, path = self._parse_qs()
|
||||||
|
content_len = int(self.headers.get("Content-Length", 0))
|
||||||
|
body = self.rfile.read(content_len).decode() if content_len > 0 else "{}"
|
||||||
|
try:
|
||||||
|
data = json.loads(body) if body else {}
|
||||||
|
except:
|
||||||
|
data = {}
|
||||||
|
|
||||||
|
if path == "/register":
|
||||||
|
count = int(params.get("count", 5))
|
||||||
|
push = params.get("push", "true").lower() != "false"
|
||||||
|
if state.get("reg_active"):
|
||||||
|
self._json({"error": "registration already in progress"}, 409)
|
||||||
|
return
|
||||||
|
self._json({"status": "started", "count": count, "push": push})
|
||||||
|
t = threading.Thread(target=reg_worker, args=(count, push), daemon=True)
|
||||||
|
t.start()
|
||||||
|
|
||||||
|
elif path == "/push":
|
||||||
|
key = params.get("key", "")
|
||||||
|
provider = params.get("provider", "tokenharbor")
|
||||||
|
label = params.get("label", "")
|
||||||
|
result, code = push_key_to_gateway(provider, key, label)
|
||||||
|
if code == 200:
|
||||||
|
for k in state["keys"]:
|
||||||
|
if k["key"] == key:
|
||||||
|
k["pushed"] = True
|
||||||
|
break
|
||||||
|
save_state()
|
||||||
|
self._json(result, code)
|
||||||
|
|
||||||
|
elif path == "/push-all":
|
||||||
|
provider = params.get("provider", "tokenharbor")
|
||||||
|
pushed = 0
|
||||||
|
failed = 0
|
||||||
|
for k in state["keys"]:
|
||||||
|
if not k.get("pushed") and not k.get("dead"):
|
||||||
|
result, code = push_key_to_gateway(provider, k["key"], k["label"])
|
||||||
|
if code == 200:
|
||||||
|
k["pushed"] = True
|
||||||
|
pushed += 1
|
||||||
|
else:
|
||||||
|
failed += 1
|
||||||
|
save_state()
|
||||||
|
self._json({"pushed": pushed, "failed": failed})
|
||||||
|
|
||||||
|
elif path == "/swap":
|
||||||
|
provider = params.get("provider", "tokenharbor")
|
||||||
|
dead_key = params.get("dead_key", "")
|
||||||
|
# Mark dead
|
||||||
|
for k in state["keys"]:
|
||||||
|
if k["key"] == dead_key:
|
||||||
|
k["dead"] = True
|
||||||
|
break
|
||||||
|
save_state()
|
||||||
|
# Register one new
|
||||||
|
if not state.get("reg_active"):
|
||||||
|
self._json({"status": "swap_started", "dead_key": dead_key[:20] + "..."})
|
||||||
|
t = threading.Thread(target=reg_worker, args=(1, True), daemon=True)
|
||||||
|
t.start()
|
||||||
|
else:
|
||||||
|
self._json({"error": "registration already in progress"}, 409)
|
||||||
|
|
||||||
|
elif path == "/check-all-balances":
|
||||||
|
provider = params.get("provider", "tokenharbor")
|
||||||
|
results = []
|
||||||
|
for k in state["keys"]:
|
||||||
|
if not k.get("dead"):
|
||||||
|
ok, detail = check_balance(k["key"])
|
||||||
|
k["balance"] = "ok" if ok else detail
|
||||||
|
k["balance_checked"] = datetime.now().isoformat()
|
||||||
|
results.append({"key": k["key"][:20] + "...", "works": ok, "detail": detail})
|
||||||
|
state["last_balance_check"] = datetime.now().isoformat()
|
||||||
|
save_state()
|
||||||
|
self._json({"checked": len(results), "results": results})
|
||||||
|
|
||||||
|
else:
|
||||||
|
self._json({"error": "not found"}, 404)
|
||||||
|
|
||||||
|
def do_OPTIONS(self):
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Access-Control-Allow-Origin", "*")
|
||||||
|
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||||
|
self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
print(f"[{datetime.now().strftime('%H:%M:%S')}] {args[0]}")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
load_state()
|
||||||
|
print(f"=== th_local_api v2.0 :{API_PORT} ===")
|
||||||
|
print(f" Pool: {POOL_FILE}")
|
||||||
|
print(f" Gateway: {GATEWAY_URL}")
|
||||||
|
print(f" Keys stored: {len(state.get('keys', []))}")
|
||||||
|
print(f" CDP: {'OK' if connect_cdp() else 'DEAD — start Chrome with --remote-debugging-port=9222'}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
server = HTTPServer(("0.0.0.0", API_PORT), Handler)
|
||||||
|
print(f" Listening on :{API_PORT}")
|
||||||
|
try:
|
||||||
|
server.serve_forever()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
server.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+410
@@ -0,0 +1,410 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""TokenHarbor parallel auto-reg: 10 threads, one Chrome instance, shared state."""
|
||||||
|
# __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, time, re, ssl, sys, threading
|
||||||
|
from pathlib import Path
|
||||||
|
from datetime import datetime
|
||||||
|
from urllib.request import urlopen, Request
|
||||||
|
import websocket
|
||||||
|
import imaplib
|
||||||
|
import email as em
|
||||||
|
import os
|
||||||
|
# Account passwords live in <project root>/.env (gitignored). Guarded import:
|
||||||
|
# python-dotenv is not a declared dependency of these standalone scripts.
|
||||||
|
try:
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
BASE_URL = "https://tokenharbor.ai"
|
||||||
|
PASSWORD = os.environ["TOKENHARBOR_PASSWORD"]
|
||||||
|
CDP_HOST = "127.0.0.1"
|
||||||
|
CDP_PORT = 9222
|
||||||
|
GATEWAY_URL = "https://gateway.example.com/th"
|
||||||
|
GATEWAY_KEY = os.environ.get("TH_GATEWAY_KEY", "")
|
||||||
|
POOL_FILE = Path(str(_d("Downloads/Telegram Desktop/working_mails.txt","MAIL_POOL")))
|
||||||
|
KEYS_FILE = Path(str(_d("Desktop/авторег проект/tokenharbor_keys.txt")))
|
||||||
|
STATE_FILE = Path(str(_d("Desktop/авторег проект/th_tonline_state.json")))
|
||||||
|
|
||||||
|
state_lock = threading.Lock()
|
||||||
|
keys_lock = threading.Lock()
|
||||||
|
|
||||||
|
state = {"done": [], "fail": [], "idx": 0}
|
||||||
|
|
||||||
|
def load_state():
|
||||||
|
global state
|
||||||
|
if STATE_FILE.exists():
|
||||||
|
try: state = json.loads(STATE_FILE.read_text())
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
def save_state():
|
||||||
|
with state_lock:
|
||||||
|
STATE_FILE.write_text(json.dumps(state, indent=2, default=str))
|
||||||
|
|
||||||
|
def connect_cdp():
|
||||||
|
try:
|
||||||
|
req = Request(f"http://{CDP_HOST}:{CDP_PORT}/json/new", method="PUT")
|
||||||
|
data = json.loads(urlopen(req).read())
|
||||||
|
ws = websocket.create_connection(data["webSocketDebuggerUrl"], timeout=10)
|
||||||
|
return {"ws": ws, "id": 0}
|
||||||
|
except Exception as e:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def js(cdp, code, timeout=15):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Runtime.evaluate",
|
||||||
|
"params": {"expression": code, "returnByValue": True, "awaitPromise": True}}))
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
cdp["ws"].settimeout(1)
|
||||||
|
try:
|
||||||
|
data = json.loads(cdp["ws"].recv())
|
||||||
|
if data.get("id") == mid:
|
||||||
|
r = data.get("result", {}).get("result", {})
|
||||||
|
return r.get("value"), data.get("subtype")
|
||||||
|
except: pass
|
||||||
|
return None, "timeout"
|
||||||
|
|
||||||
|
def clear_session(cdp):
|
||||||
|
"""Clear all cookies and storage — prevents cross-account key leakage."""
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Network.clearBrowserCookies"}))
|
||||||
|
time.sleep(0.3)
|
||||||
|
js(cdp, "try{localStorage.clear();sessionStorage.clear();indexedDB.databases().then(dbs=>dbs.forEach(db=>indexedDB.deleteDatabase(db.name)));}catch(e){}")
|
||||||
|
|
||||||
|
def nav(cdp, url):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Page.navigate", "params": {"url": url}}))
|
||||||
|
time.sleep(1.5)
|
||||||
|
|
||||||
|
def wait_for_verify_email(email_addr, email_pass, timeout=60):
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
try:
|
||||||
|
mail = imaplib.IMAP4_SSL("secureimap.t-online.de", 993, ssl_context=ctx, timeout=10)
|
||||||
|
mail.login(email_addr, email_pass)
|
||||||
|
mail.select("INBOX")
|
||||||
|
except Exception as e:
|
||||||
|
return None
|
||||||
|
|
||||||
|
status, baseline = mail.search(None, 'ALL')
|
||||||
|
known_ids = set(baseline[0].split()) if baseline[0] else set()
|
||||||
|
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
try:
|
||||||
|
mail.select("INBOX")
|
||||||
|
status, data = mail.search(None, 'ALL')
|
||||||
|
if status == "OK" and data[0]:
|
||||||
|
new_ids = set(data[0].split()) - known_ids
|
||||||
|
for mid in sorted(new_ids, reverse=True):
|
||||||
|
status, msg_data = mail.fetch(mid, "(RFC822)")
|
||||||
|
if status != "OK": continue
|
||||||
|
msg = em.message_from_bytes(msg_data[0][1])
|
||||||
|
body = ""
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.get_content_type() in ("text/plain", "text/html"):
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if payload: body += payload.decode("utf-8", errors="replace")
|
||||||
|
else:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload: body = payload.decode("utf-8", errors="replace")
|
||||||
|
if "tokenharbor" in body.lower() or "verify" in body.lower():
|
||||||
|
links = re.findall(r'https://tokenharbor\.ai/verify-email\?token=[^\s"<>]+', body)
|
||||||
|
if links:
|
||||||
|
mail.logout()
|
||||||
|
return links[0]
|
||||||
|
time.sleep(3)
|
||||||
|
except:
|
||||||
|
time.sleep(5)
|
||||||
|
try: mail.logout()
|
||||||
|
except: pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
def push_key(api_key):
|
||||||
|
try:
|
||||||
|
data = json.dumps({"provider": "tokenharbor", "key": api_key}).encode()
|
||||||
|
req = Request(f"{GATEWAY_URL}/provider/add?provider=tokenharbor",
|
||||||
|
data=data, headers={"Content-Type": "application/json", "Authorization": f"Bearer {GATEWAY_KEY}"}, method="POST")
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
return json.loads(resp.read()), resp.status
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}, 500
|
||||||
|
|
||||||
|
def process_one(cdp, email, email_pass):
|
||||||
|
label = email.split("@")[0][:12]
|
||||||
|
is_new_signup = False
|
||||||
|
|
||||||
|
# CLEAR SESSION — prevent cross-account cookie leakage
|
||||||
|
clear_session(cdp)
|
||||||
|
|
||||||
|
# STEP 1: Try SIGNUP first (new account registration)
|
||||||
|
print(f" [{label}] Signup...", flush=True)
|
||||||
|
nav(cdp, f"{BASE_URL}/login")
|
||||||
|
time.sleep(1.5)
|
||||||
|
|
||||||
|
# Click "Sign up" tab
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Sign up' && b.offsetParent !== null) { b.click(); break; }
|
||||||
|
}""")
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
# Fill signup form
|
||||||
|
js(cdp, f"""
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ nativeSet.call(e, '{email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ nativeSet.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(1.5)
|
||||||
|
|
||||||
|
# Click "Create account"
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Create account') && b.offsetParent !== null) { b.click(); break; }
|
||||||
|
}""")
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
body, _ = js(cdp, "document.body.innerText")
|
||||||
|
|
||||||
|
# Check if signup succeeded or if account already exists
|
||||||
|
if "dashboard" in str(url) or "verify" in str(url).lower():
|
||||||
|
is_new_signup = True
|
||||||
|
print(f" [{label}] Signup OK", flush=True)
|
||||||
|
elif body and ("already exists" in str(body).lower() or "already registered" in str(body).lower() or "already have an account" in str(body).lower()):
|
||||||
|
# Account exists — switch to login
|
||||||
|
print(f" [{label}] Already registered, logging in...", flush=True)
|
||||||
|
nav(cdp, f"{BASE_URL}/login")
|
||||||
|
time.sleep(3)
|
||||||
|
# Click "Sign in" tab
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Sign in' && b.offsetParent !== null) { b.click(); break; }
|
||||||
|
}""")
|
||||||
|
time.sleep(1)
|
||||||
|
js(cdp, f"""
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ nativeSet.call(e, '{email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ nativeSet.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Sign in') && b.closest('form')) { b.click(); break; } }""")
|
||||||
|
time.sleep(6)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
time.sleep(5)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
return None, f"login failed: {url}"
|
||||||
|
print(f" [{label}] Logged in", flush=True)
|
||||||
|
else:
|
||||||
|
# Signup might have failed for other reasons, try login as fallback
|
||||||
|
print(f" [{label}] Signup unclear, trying login...", flush=True)
|
||||||
|
nav(cdp, f"{BASE_URL}/login")
|
||||||
|
time.sleep(3)
|
||||||
|
js(cdp, f"""
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ nativeSet.call(e, '{email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ nativeSet.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Sign in') && b.closest('form')) { b.click(); break; } }""")
|
||||||
|
time.sleep(6)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
time.sleep(5)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
return None, f"login failed: {url}"
|
||||||
|
print(f" [{label}] Logged in", flush=True)
|
||||||
|
|
||||||
|
# Verify email (only for new signups)
|
||||||
|
if is_new_signup:
|
||||||
|
body, _ = js(cdp, "document.body.innerText")
|
||||||
|
if body and "Verify your email" in str(body):
|
||||||
|
print(f" [{label}] Needs verification", flush=True)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if((b.textContent.includes('Verify') && b.textContent.includes('email')) && b.offsetParent !== null) {
|
||||||
|
b.click(); break;
|
||||||
|
}
|
||||||
|
}""")
|
||||||
|
time.sleep(2)
|
||||||
|
verify_link = wait_for_verify_email(email, email_pass, timeout=60)
|
||||||
|
if verify_link:
|
||||||
|
nav(cdp, verify_link)
|
||||||
|
time.sleep(4)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "verify=success" in str(url) or "dashboard" in str(url):
|
||||||
|
print(f" [{label}] Verified!", flush=True)
|
||||||
|
else:
|
||||||
|
print(f" [{label}] Verify link failed", flush=True)
|
||||||
|
else:
|
||||||
|
print(f" [{label}] No verify email", flush=True)
|
||||||
|
else:
|
||||||
|
print(f" [{label}] Already verified", flush=True)
|
||||||
|
|
||||||
|
# Claim $5 (only for new signups)
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard")
|
||||||
|
time.sleep(4)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if((b.textContent.includes('Claim') || b.textContent.includes('Gift')) && b.offsetParent !== null) {
|
||||||
|
b.click(); break; }
|
||||||
|
}""")
|
||||||
|
time.sleep(2)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Claim' && b.offsetParent !== null) {
|
||||||
|
b.click(); break; }
|
||||||
|
}""")
|
||||||
|
time.sleep(3)
|
||||||
|
print(f" [{label}] $5 claimed!", flush=True)
|
||||||
|
|
||||||
|
# Create API key
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard/api-keys")
|
||||||
|
time.sleep(8)
|
||||||
|
for _ in range(10):
|
||||||
|
t, _ = js(cdp, "document.body.innerText")
|
||||||
|
if "API keys" in str(t):
|
||||||
|
break
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim().includes('New key') && b.offsetParent !== null) { b.click(); break; } }""")
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
js(cdp, f"""
|
||||||
|
var inputs = document.querySelectorAll('input[type="text"]');
|
||||||
|
for(var inp of inputs) {{
|
||||||
|
if(inp.offsetParent !== null) {{
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
nativeSet.call(inp, '{label}');
|
||||||
|
inp.dispatchEvent(new Event('input', {{bubbles:true}}));
|
||||||
|
inp.dispatchEvent(new Event('change', {{bubbles:true}}));
|
||||||
|
break;
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
""")
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Create key' && !b.disabled && b.offsetParent !== null) { b.click(); break; } }""")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
page, _ = js(cdp, "document.body.innerText")
|
||||||
|
match = re.search(r'thk_live_[a-zA-Z0-9_-]{40,}', str(page))
|
||||||
|
api_key = match.group(0) if match else None
|
||||||
|
|
||||||
|
if api_key:
|
||||||
|
with keys_lock:
|
||||||
|
with open(KEYS_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{email} | {api_key} | {datetime.now().isoformat()}\n")
|
||||||
|
result, status = push_key(api_key)
|
||||||
|
pushed = status == 200
|
||||||
|
print(f" [{label}] KEY: {api_key[:25]}... pushed={pushed}", flush=True)
|
||||||
|
return api_key, None
|
||||||
|
|
||||||
|
return None, "no key"
|
||||||
|
|
||||||
|
def worker(thread_id, emails):
|
||||||
|
"""Process a list of emails in one CDP tab."""
|
||||||
|
cdp = connect_cdp()
|
||||||
|
if not cdp:
|
||||||
|
print(f"[T{thread_id}] CDP FAILED", flush=True)
|
||||||
|
return
|
||||||
|
|
||||||
|
for i, (email, pwd) in enumerate(emails):
|
||||||
|
print(f"[T{thread_id}][{i+1}/{len(emails)}] {email}", flush=True)
|
||||||
|
key, err = process_one(cdp, email, pwd)
|
||||||
|
|
||||||
|
with state_lock:
|
||||||
|
state = json.loads(STATE_FILE.read_text())
|
||||||
|
if key:
|
||||||
|
state["done"].append(email)
|
||||||
|
else:
|
||||||
|
state["fail"].append({"email": email, "error": str(err)})
|
||||||
|
STATE_FILE.write_text(json.dumps(state, indent=2, default=str))
|
||||||
|
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
cdp["ws"].close()
|
||||||
|
print(f"[T{thread_id}] DONE", flush=True)
|
||||||
|
|
||||||
|
def main(n_threads, per_thread):
|
||||||
|
load_state()
|
||||||
|
done_emails = set(state.get("done", []))
|
||||||
|
failed_emails = set(item["email"] for item in state.get("fail", []))
|
||||||
|
|
||||||
|
pool = []
|
||||||
|
with open(POOL_FILE, "r", encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
if ":" in line and "@" in line:
|
||||||
|
parts = line.strip().split(":", 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
email, pwd = parts
|
||||||
|
if "t-online.de" in email and email not in done_emails and email not in failed_emails:
|
||||||
|
pool.append((email, pwd))
|
||||||
|
|
||||||
|
total = n_threads * per_thread
|
||||||
|
pool = pool[:total]
|
||||||
|
|
||||||
|
print(f"Starting {n_threads} threads, {per_thread} each = {len(pool)} total", flush=True)
|
||||||
|
|
||||||
|
threads = []
|
||||||
|
for t in range(n_threads):
|
||||||
|
chunk = pool[t * per_thread : (t + 1) * per_thread]
|
||||||
|
th = threading.Thread(target=worker, args=(t, chunk))
|
||||||
|
th.start()
|
||||||
|
threads.append(th)
|
||||||
|
time.sleep(0.5) # stagger CDP connects
|
||||||
|
|
||||||
|
for th in threads:
|
||||||
|
th.join()
|
||||||
|
|
||||||
|
final_state = json.loads(STATE_FILE.read_text())
|
||||||
|
print(f"\nDone: {len(final_state.get('done',[]))}, Fail: {len(final_state.get('fail',[]))}", flush=True)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
n = int(sys.argv[1]) if len(sys.argv) > 1 else 10
|
||||||
|
per = int(sys.argv[2]) if len(sys.argv) > 2 else 10
|
||||||
|
main(n, per)
|
||||||
+126
@@ -0,0 +1,126 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""th_pipeline.py — full auto pipeline: CDP watchdog + autoreg chunks + auto-deploy to VPS.
|
||||||
|
|
||||||
|
Usage: python th_pipeline.py [TOTAL] [CHUNK]
|
||||||
|
TOTAL — total accounts to register (default 200)
|
||||||
|
CHUNK — accounts per chunk before sync (default 10)
|
||||||
|
|
||||||
|
Loop:
|
||||||
|
1. ensure Chrome CDP :9222 alive (restart if dead)
|
||||||
|
2. run th_tonline_claim.py CHUNK
|
||||||
|
3. run th_sync_vps.py (deploys new keys to VPS, stops new-api during write)
|
||||||
|
4. repeat until TOTAL reached
|
||||||
|
State: th_pipeline_state.json (done chunks, deployed count)
|
||||||
|
"""
|
||||||
|
# __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, subprocess, sys, time, urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJ = Path(__file__).parent
|
||||||
|
PY = _PY
|
||||||
|
CHROME = r"C:/Program Files/Google/Chrome/Application/chrome.exe"
|
||||||
|
CDP_PROFILE = str(_d(".chrome-cdp-profile"))
|
||||||
|
STATE = PROJ / "th_pipeline_state.json"
|
||||||
|
|
||||||
|
|
||||||
|
import os as _os, msvcrt
|
||||||
|
_LF = open(Path(__file__).parent / "th_pipeline.lock", "a+")
|
||||||
|
try:
|
||||||
|
msvcrt.locking(_LF.fileno(), msvcrt.LK_NBLCK, 1)
|
||||||
|
except OSError:
|
||||||
|
print("another pipeline instance holds the lock, exiting")
|
||||||
|
_os._exit(0)
|
||||||
|
_LF.seek(0); _LF.truncate(); _LF.write(str(_os.getpid())); _LF.flush()
|
||||||
|
|
||||||
|
TOTAL = int(sys.argv[1]) if len(sys.argv) > 1 else 200
|
||||||
|
CHUNK = int(sys.argv[2]) if len(sys.argv) > 2 else 10
|
||||||
|
|
||||||
|
def log(msg):
|
||||||
|
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
|
||||||
|
|
||||||
|
def cdp_alive():
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen("http://127.0.0.1:9222/json/version", timeout=5).read()
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def start_cdp():
|
||||||
|
log("CDP dead -> starting Chrome")
|
||||||
|
subprocess.Popen([CHROME, "--remote-debugging-port=9222", "--remote-allow-origins=*",
|
||||||
|
f"--user-data-dir={CDP_PROFILE}", "--no-first-run",
|
||||||
|
"--proxy-server=http://127.0.0.1:8077",
|
||||||
|
"--no-default-browser-check", "about:blank"],
|
||||||
|
creationflags=0x00000008) # DETACHED_PROCESS
|
||||||
|
for _ in range(30):
|
||||||
|
time.sleep(2)
|
||||||
|
if cdp_alive():
|
||||||
|
log("CDP up")
|
||||||
|
return True
|
||||||
|
log("CDP FAILED to start")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def run(script, args, label, timeout):
|
||||||
|
log(f"RUN {label}")
|
||||||
|
r = subprocess.run([PY, "-u", str(PROJ / script)] + args,
|
||||||
|
capture_output=True, text=True, timeout=timeout,
|
||||||
|
env={"PYTHONPATH": "", "PATH": r"C:\Windows\system32;C:\Windows;C:\Program Files\Git\usr\bin;C:\Program Files\Git\bin",
|
||||||
|
"USERPROFILE": _USERPROFILE, "SYSTEMROOT": r"C:\Windows"})
|
||||||
|
out = (r.stdout or "") + (r.stderr or "")
|
||||||
|
keys = out.count("KEY:")
|
||||||
|
log(f"{label} done rc={r.returncode} keys={keys}")
|
||||||
|
if r.returncode != 0:
|
||||||
|
log("tail: " + out[-300:].replace("\n", " | "))
|
||||||
|
return keys
|
||||||
|
|
||||||
|
def main():
|
||||||
|
st = json.loads(STATE.read_text()) if STATE.exists() else {"done": 0, "deployed_runs": 0}
|
||||||
|
while st["done"] < TOTAL:
|
||||||
|
if not cdp_alive() and not start_cdp():
|
||||||
|
log("CDP unrecoverable, sleep 120"); time.sleep(120); continue
|
||||||
|
n = min(CHUNK, TOTAL - st["done"])
|
||||||
|
try:
|
||||||
|
run("th_tonline_claim.py", [str(n)], f"reg chunk {n}", timeout=n * 240 + 300)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
log("reg chunk TIMEOUT — continuing to sync anyway")
|
||||||
|
st["done"] += n
|
||||||
|
try:
|
||||||
|
run("th_sync_vps.py", [], "sync->VPS", timeout=600)
|
||||||
|
st["deployed_runs"] += 1
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
log("sync TIMEOUT")
|
||||||
|
STATE.write_text(json.dumps(st, indent=1))
|
||||||
|
log(f"progress: {st['done']}/{TOTAL}")
|
||||||
|
log("PIPELINE COMPLETE")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""th_proxy_router.py — local rotating upstream proxy for Chrome CDP.
|
||||||
|
|
||||||
|
Listens on 127.0.0.1:8077. Forwards HTTP/HTTPS(CONNECT) through a pool of
|
||||||
|
upstream free proxies (_good_proxies.txt), rotating the active upstream every
|
||||||
|
ROTATE_SEC seconds or immediately on connection failure.
|
||||||
|
|
||||||
|
Chrome launched with --proxy-server=http://127.0.0.1:8077 gets a fresh exit IP
|
||||||
|
without restarts.
|
||||||
|
"""
|
||||||
|
import socket, select, threading, time, sys, os
|
||||||
|
|
||||||
|
LISTEN_HOST, LISTEN_PORT = "127.0.0.1", 8077
|
||||||
|
ROTATE_SEC = 75
|
||||||
|
PROXY_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_good_proxies.txt")
|
||||||
|
|
||||||
|
class Pool:
|
||||||
|
def __init__(self):
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.proxies = []
|
||||||
|
self.cur = None
|
||||||
|
self.since = 0
|
||||||
|
self.bad = set()
|
||||||
|
self.reload()
|
||||||
|
|
||||||
|
def reload(self):
|
||||||
|
try:
|
||||||
|
ps = [l.strip() for l in open(PROXY_FILE) if l.strip()]
|
||||||
|
except Exception:
|
||||||
|
ps = []
|
||||||
|
with self.lock:
|
||||||
|
self.proxies = ps
|
||||||
|
self.bad.clear()
|
||||||
|
self.cur = None
|
||||||
|
|
||||||
|
def get(self):
|
||||||
|
with self.lock:
|
||||||
|
now = time.time()
|
||||||
|
if self.cur and (now - self.since) < ROTATE_SEC and self.cur not in self.bad:
|
||||||
|
return self.cur
|
||||||
|
cands = [p for p in self.proxies if p not in self.bad]
|
||||||
|
if not cands:
|
||||||
|
self.bad.clear()
|
||||||
|
cands = list(self.proxies)
|
||||||
|
if not cands:
|
||||||
|
return None
|
||||||
|
# pick next different from current
|
||||||
|
pick = None
|
||||||
|
for p in cands:
|
||||||
|
if p != self.cur:
|
||||||
|
pick = p; break
|
||||||
|
self.cur = pick or cands[0]
|
||||||
|
self.since = now
|
||||||
|
return self.cur
|
||||||
|
|
||||||
|
def mark_bad(self, p):
|
||||||
|
with self.lock:
|
||||||
|
self.bad.add(p)
|
||||||
|
if self.cur == p:
|
||||||
|
self.cur = None
|
||||||
|
|
||||||
|
POOL = Pool()
|
||||||
|
|
||||||
|
def parse_proxy(p):
|
||||||
|
# http://ip:port
|
||||||
|
s = p.split("://", 1)[-1]
|
||||||
|
ip, _, port = s.partition(":")
|
||||||
|
return ip, int(port or 80)
|
||||||
|
|
||||||
|
def pipe(a, b):
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
r, _, _ = select.select([a, b], [], [], 60)
|
||||||
|
if not r: break
|
||||||
|
for s in r:
|
||||||
|
data = s.recv(65536)
|
||||||
|
if not data: return
|
||||||
|
(b if s is a else a).sendall(data)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
for s in (a, b):
|
||||||
|
try: s.close()
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
def connect_upstream(target_host, target_port):
|
||||||
|
"""Return (upstream_sock, proxy_used) connected to target through pool proxy."""
|
||||||
|
tried = 0
|
||||||
|
while tried < 6:
|
||||||
|
p = POOL.get()
|
||||||
|
if not p: return None, None
|
||||||
|
pip, pport = parse_proxy(p)
|
||||||
|
try:
|
||||||
|
us = socket.create_connection((pip, pport), timeout=12)
|
||||||
|
req = f"CONNECT {target_host}:{target_port} HTTP/1.1\r\nHost: {target_host}:{target_port}\r\n\r\n"
|
||||||
|
us.sendall(req.encode())
|
||||||
|
resp = b""
|
||||||
|
us.settimeout(12)
|
||||||
|
while b"\r\n\r\n" not in resp:
|
||||||
|
chunk = us.recv(4096)
|
||||||
|
if not chunk: break
|
||||||
|
resp += chunk
|
||||||
|
first = resp.split(b"\r\n", 1)[0].decode(errors="ignore")
|
||||||
|
if "200" in first:
|
||||||
|
return us, p
|
||||||
|
us.close()
|
||||||
|
POOL.mark_bad(p)
|
||||||
|
except Exception:
|
||||||
|
POOL.mark_bad(p)
|
||||||
|
tried += 1
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
def handle(client):
|
||||||
|
try:
|
||||||
|
client.settimeout(30)
|
||||||
|
head = b""
|
||||||
|
while b"\r\n\r\n" not in head:
|
||||||
|
chunk = client.recv(65536)
|
||||||
|
if not chunk: return
|
||||||
|
head += chunk
|
||||||
|
lines = head.split(b"\r\n")
|
||||||
|
method, target, _ = lines[0].decode(errors="ignore").split(" ", 2)
|
||||||
|
if method == "CONNECT":
|
||||||
|
host, _, port = target.partition(":")
|
||||||
|
us, used = connect_upstream(host, int(port or 443))
|
||||||
|
if not us:
|
||||||
|
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n"); return
|
||||||
|
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||||
|
pipe(client, us)
|
||||||
|
else:
|
||||||
|
# plain HTTP proxy request: forward as-is via upstream proxy
|
||||||
|
p = POOL.get()
|
||||||
|
if not p:
|
||||||
|
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n"); return
|
||||||
|
pip, pport = parse_proxy(p)
|
||||||
|
try:
|
||||||
|
us = socket.create_connection((pip, pport), timeout=12)
|
||||||
|
us.sendall(head)
|
||||||
|
pipe(client, us)
|
||||||
|
except Exception:
|
||||||
|
POOL.mark_bad(p)
|
||||||
|
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
try: client.close()
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
def main():
|
||||||
|
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
srv.bind((LISTEN_HOST, LISTEN_PORT))
|
||||||
|
srv.listen(64)
|
||||||
|
print(f"router up on {LISTEN_HOST}:{LISTEN_PORT}, pool={len(POOL.proxies)}", flush=True)
|
||||||
|
# periodic pool reload every 5 min (file may be refreshed externally)
|
||||||
|
def reloader():
|
||||||
|
while True:
|
||||||
|
time.sleep(300)
|
||||||
|
POOL.reload()
|
||||||
|
print(f"pool reloaded: {len(POOL.proxies)}", flush=True)
|
||||||
|
threading.Thread(target=reloader, daemon=True).start()
|
||||||
|
while True:
|
||||||
|
c, _ = srv.accept()
|
||||||
|
threading.Thread(target=handle, args=(c,), daemon=True).start()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+349
@@ -0,0 +1,349 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
th_reg_v2.py — TokenHarbor HTTP-only AUTO-REGER v2
|
||||||
|
=====================================================
|
||||||
|
Signup (no browser/turnstile needed with real Chrome CDP) →
|
||||||
|
IMAP email verify → claim $5 → enable free models → create API key → save + push.
|
||||||
|
Refactored from th_tonline_claim.py + harbor/client.py logic.
|
||||||
|
Runs on CDP Chrome :9222. Uses working_mails.txt pool (t-online IMAP).
|
||||||
|
Falls back to login if email already registered.
|
||||||
|
"""
|
||||||
|
# __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, sys, os, re, time, ssl, imaplib, email as email_lib
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.request import urlopen, Request
|
||||||
|
from websocket import create_connection as ws_connect
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
# ---- config ----
|
||||||
|
BASE_URL = "https://tokenharbor.ai"
|
||||||
|
PASSWORD = os.environ["TOKENHARBOR_PASSWORD"]
|
||||||
|
CDP_HOST = "127.0.0.1"
|
||||||
|
CDP_PORT = 9222
|
||||||
|
GATEWAY_URL = "https://gateway.example.com/th"
|
||||||
|
GATEWAY_KEY = os.environ.get("TH_GATEWAY_KEY", "")
|
||||||
|
POOL_FILE = Path(str(_d("Downloads/Telegram Desktop/working_mails.txt","MAIL_POOL")))
|
||||||
|
KEYS_FILE = Path(__file__).parent / "tokenharbor_keys_v2.txt"
|
||||||
|
STATE_FILE = Path(__file__).parent / "th_reg_v2_state.json"
|
||||||
|
|
||||||
|
state = {"done": [], "fail": [], "idx": 0}
|
||||||
|
|
||||||
|
def load_state():
|
||||||
|
global state
|
||||||
|
if STATE_FILE.exists():
|
||||||
|
try: state = json.loads(STATE_FILE.read_text())
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
def save_state():
|
||||||
|
STATE_FILE.write_text(json.dumps(state, indent=2, default=str))
|
||||||
|
|
||||||
|
def connect_cdp():
|
||||||
|
try:
|
||||||
|
req = Request(f"http://{CDP_HOST}:{CDP_PORT}/json/new?url=about:blank", method="PUT")
|
||||||
|
data = json.loads(urlopen(req).read())
|
||||||
|
ws = ws_connect(data["webSocketDebuggerUrl"], timeout=10)
|
||||||
|
return {"ws": ws, "id": 0, "tab_id": data["id"]}
|
||||||
|
except Exception as e:
|
||||||
|
print(f"CDP FAILED: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def js(cdp, code, timeout=15):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Runtime.evaluate",
|
||||||
|
"params": {"expression": code, "returnByValue": True, "awaitPromise": True}}))
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
cdp["ws"].settimeout(1)
|
||||||
|
try:
|
||||||
|
data = json.loads(cdp["ws"].recv())
|
||||||
|
if data.get("id") == mid:
|
||||||
|
r = data.get("result", {}).get("result", {})
|
||||||
|
return r.get("value"), data.get("subtype")
|
||||||
|
except: pass
|
||||||
|
return None, "timeout"
|
||||||
|
|
||||||
|
def nav(cdp, url):
|
||||||
|
cdp["ws"].send(json.dumps({"id": 999, "method": "Page.navigate", "params": {"url": url}}))
|
||||||
|
time.sleep(4)
|
||||||
|
|
||||||
|
def close_tab(cdp):
|
||||||
|
try:
|
||||||
|
urlopen(Request(f"http://{CDP_HOST}:{CDP_PORT}/json/close/{cdp['tab_id']}")).read()
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
# ---- IMAP email verification ----
|
||||||
|
def wait_for_verify_email(email_addr, email_pass, timeout=60):
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
ctx.check_hostname = False; ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
try:
|
||||||
|
mail = imaplib.IMAP4_SSL("secureimap.t-online.de", 993, ssl_context=ctx, timeout=10)
|
||||||
|
mail.login(email_addr, email_pass)
|
||||||
|
mail.select("INBOX")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" IMAP login failed: {str(e)[:40]}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
status, baseline = mail.search(None, 'ALL')
|
||||||
|
known_ids = set(baseline[0].split()) if baseline[0] else set()
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
try:
|
||||||
|
mail.select("INBOX")
|
||||||
|
status, data = mail.search(None, 'ALL')
|
||||||
|
if status == "OK" and data[0]:
|
||||||
|
new_ids = set(data[0].split()) - known_ids
|
||||||
|
for mid in sorted(new_ids, reverse=True):
|
||||||
|
status, msg_data = mail.fetch(mid, "(RFC822)")
|
||||||
|
if status != "OK": continue
|
||||||
|
msg = email_lib.message_from_bytes(msg_data[0][1])
|
||||||
|
body = ""
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.get_content_type() in ("text/plain", "text/html"):
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if payload: body += payload.decode("utf-8", errors="replace")
|
||||||
|
else:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload: body = payload.decode("utf-8", errors="replace")
|
||||||
|
if "tokenharbor" in body.lower() or "verify" in body.lower():
|
||||||
|
links = re.findall(r'https://tokenharbor\.ai/verify-email\?token=[^\s"<>]+', body)
|
||||||
|
if links:
|
||||||
|
mail.logout()
|
||||||
|
return links[0]
|
||||||
|
time.sleep(3)
|
||||||
|
except Exception:
|
||||||
|
time.sleep(5)
|
||||||
|
try: mail.logout()
|
||||||
|
except: pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
def push_key(api_key):
|
||||||
|
try:
|
||||||
|
data = json.dumps({"provider": "tokenharbor", "key": api_key}).encode()
|
||||||
|
req = Request(f"{GATEWAY_URL}/provider/add?provider=tokenharbor",
|
||||||
|
data=data, headers={"Content-Type": "application/json", "Authorization": f"Bearer {GATEWAY_KEY}"}, method="POST")
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
return json.loads(resp.read()), resp.status
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}, 500
|
||||||
|
|
||||||
|
# ---- Core: signup or login + claim + key ----
|
||||||
|
def process_one(cdp, email, email_pass):
|
||||||
|
label = email.split("@")[0][:12]
|
||||||
|
print(f" [{label}] Signup...", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 1: SIGNUP (or login if already registered)
|
||||||
|
nav(cdp, f"{BASE_URL}/login?mode=signup")
|
||||||
|
time.sleep(6)
|
||||||
|
# Fill email, password, leave invite_code empty
|
||||||
|
js(cdp, f"""
|
||||||
|
var ns = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ ns.call(e, '{email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[placeholder*="At least"]');
|
||||||
|
if(!p) p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ ns.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(1)
|
||||||
|
# Click submit button (first button with type=submit visible)
|
||||||
|
js(cdp, """
|
||||||
|
for(var b of document.querySelectorAll('button[type="submit"]')) {
|
||||||
|
if(b.offsetParent !== null) { b.click(); break; }
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
time.sleep(8)
|
||||||
|
current_url, _ = js(cdp, "window.location.href")
|
||||||
|
current_body, _ = js(cdp, "document.body.innerText")
|
||||||
|
|
||||||
|
# Detect: "already registered" -> fallback to login
|
||||||
|
if current_body and ("already registered" in str(current_body).lower() or "already have an account" in str(current_body).lower()):
|
||||||
|
print(f" Already registered, trying login...", file=sys.stderr)
|
||||||
|
nav(cdp, f"{BASE_URL}/login")
|
||||||
|
time.sleep(5)
|
||||||
|
js(cdp, f"""
|
||||||
|
var ns = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ ns.call(e, '{email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ ns.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Sign in') && b.closest('form')) { b.click(); break; } }""")
|
||||||
|
time.sleep(6)
|
||||||
|
|
||||||
|
# Wait for dashboard or verify page
|
||||||
|
for _ in range(5):
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" in str(url) or "verify" in str(url).lower():
|
||||||
|
break
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
print(f" Post-action URL: {str(url)[:80]}", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 2: Email verification if needed
|
||||||
|
body, _ = js(cdp, "document.body.innerText")
|
||||||
|
if body and "verify your email" in str(body).lower():
|
||||||
|
print(f" Needs verification — sending...", file=sys.stderr)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if((b.textContent.includes('Verify') && b.textContent.includes('email')) && b.offsetParent !== null) {
|
||||||
|
b.click(); break; }}""")
|
||||||
|
time.sleep(3)
|
||||||
|
verify_link = wait_for_verify_email(email, email_pass, timeout=90)
|
||||||
|
if verify_link:
|
||||||
|
nav(cdp, verify_link)
|
||||||
|
time.sleep(4)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
print(f" Verified: {str(url)[:60]}", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
print(f" No verify email in 90s", file=sys.stderr)
|
||||||
|
return None, "verify timeout"
|
||||||
|
|
||||||
|
# Step 3: Enable free models
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard")
|
||||||
|
time.sleep(4)
|
||||||
|
fm, _ = js(cdp, """
|
||||||
|
(function(){
|
||||||
|
var s = document.querySelector('button[aria-label="Enable free models"]');
|
||||||
|
if(!s) return JSON.stringify({found:false});
|
||||||
|
var before = s.getAttribute('aria-checked');
|
||||||
|
if(before !== 'true') { s.click(); }
|
||||||
|
return JSON.stringify({found:true, before:before});
|
||||||
|
})()
|
||||||
|
""")
|
||||||
|
time.sleep(2)
|
||||||
|
print(f" Free models: {fm}", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 4: Claim $5 gift
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if((b.textContent.includes('Claim') || b.textContent.includes('Gift')) && b.offsetParent !== null) {
|
||||||
|
b.click(); break; }}""")
|
||||||
|
time.sleep(2)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Claim' && b.offsetParent !== null) { b.click(); break; }}""")
|
||||||
|
time.sleep(3)
|
||||||
|
print(f" $5 claimed!", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 5: Create API key
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard/api-keys")
|
||||||
|
time.sleep(8)
|
||||||
|
for _ in range(10):
|
||||||
|
t, _ = js(cdp, "document.body.innerText")
|
||||||
|
if "API keys" in str(t): break
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim().includes('New key') && b.offsetParent !== null) { b.click(); break; } }""")
|
||||||
|
time.sleep(3)
|
||||||
|
js(cdp, f"""
|
||||||
|
var inputs = document.querySelectorAll('input[type="text"]');
|
||||||
|
for(var inp of inputs) {{
|
||||||
|
if(inp.offsetParent !== null) {{
|
||||||
|
var ns = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
ns.call(inp, '{label}');
|
||||||
|
inp.dispatchEvent(new Event('input', {{bubbles:true}}));
|
||||||
|
inp.dispatchEvent(new Event('change', {{bubbles:true}}));
|
||||||
|
break;
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
""")
|
||||||
|
time.sleep(2)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Create key' && !b.disabled && b.offsetParent !== null) { b.click(); break; } }""")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
page, _ = js(cdp, "document.body.innerText")
|
||||||
|
match = re.search(r'thk_live_[a-zA-Z0-9_-]{40,}', str(page))
|
||||||
|
api_key = match.group(0) if match else None
|
||||||
|
|
||||||
|
if api_key:
|
||||||
|
with open(KEYS_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{email} | {api_key} | {datetime.now().isoformat()}\n")
|
||||||
|
result, status = push_key(api_key)
|
||||||
|
pushed = status == 200
|
||||||
|
print(f" KEY: {api_key[:25]}... pushed={pushed}", file=sys.stderr)
|
||||||
|
return api_key, None
|
||||||
|
|
||||||
|
return None, "no key on page"
|
||||||
|
|
||||||
|
def worker(count):
|
||||||
|
global state
|
||||||
|
load_state()
|
||||||
|
|
||||||
|
cdp = connect_cdp()
|
||||||
|
if not cdp: return
|
||||||
|
|
||||||
|
# Load email pool
|
||||||
|
pool = []
|
||||||
|
with open(POOL_FILE, "r", encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
if ":" in line and "@" in line:
|
||||||
|
parts = line.strip().split(":", 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
email, pwd = parts
|
||||||
|
if "t-online.de" in email:
|
||||||
|
pool.append((email, pwd))
|
||||||
|
|
||||||
|
done_emails = set(state.get("done", []))
|
||||||
|
todo = [(e, p) for e, p in pool if e not in done_emails][:count]
|
||||||
|
|
||||||
|
print(f"Processing {len(todo)} accounts...", file=sys.stderr)
|
||||||
|
|
||||||
|
for i, (email, pwd) in enumerate(todo):
|
||||||
|
print(f"[{i+1}/{len(todo)}] {email}", file=sys.stderr)
|
||||||
|
try:
|
||||||
|
key, err = process_one(cdp, email, pwd)
|
||||||
|
except Exception as e:
|
||||||
|
key, err = None, str(e)
|
||||||
|
if key:
|
||||||
|
state["done"].append(email)
|
||||||
|
else:
|
||||||
|
state["fail"].append({"email": email, "error": err})
|
||||||
|
save_state()
|
||||||
|
time.sleep(2)
|
||||||
|
# close tab and open fresh one each iteration to avoid session conflict
|
||||||
|
close_tab(cdp)
|
||||||
|
# reconnect for next
|
||||||
|
new_cdp = connect_cdp()
|
||||||
|
if new_cdp:
|
||||||
|
cdp["ws"].close()
|
||||||
|
cdp = new_cdp
|
||||||
|
save_state()
|
||||||
|
|
||||||
|
try: cdp["ws"].close()
|
||||||
|
except: pass
|
||||||
|
print(f"\nDone: {len(state['done'])} OK, {len(state['fail'])} FAIL", file=sys.stderr)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
count = int(sys.argv[1]) if len(sys.argv) > 1 else 50
|
||||||
|
worker(count)
|
||||||
+364
@@ -0,0 +1,364 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
TokenHarbor auto-reg v2 — Playwright stealth + proxy + API key creation.
|
||||||
|
Full flow: signup → verify email (IMAP) → claim $5 → create API key → push to gateway.
|
||||||
|
"""
|
||||||
|
# __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, time, re, ssl, sys, random, os
|
||||||
|
from pathlib import Path
|
||||||
|
from datetime import datetime
|
||||||
|
import imaplib
|
||||||
|
import email as em
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
from urllib.request import urlopen, Request
|
||||||
|
|
||||||
|
# Add playwright
|
||||||
|
sys.path.insert(0, str(_REPO))
|
||||||
|
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = str(_w("tmp/playwright_pkg/playwright/driver/package/.local-browsers"))
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
# Account passwords live in <project root>/.env (gitignored). Guarded import:
|
||||||
|
# python-dotenv is not a declared dependency of these standalone scripts.
|
||||||
|
try:
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# ── CONFIG ──
|
||||||
|
PASSWORD = os.environ["TOKENHARBOR_PASSWORD"]
|
||||||
|
GATEWAY_URL = "https://gateway.example.com/th"
|
||||||
|
GATEWAY_KEY = os.environ.get("TH_GATEWAY_KEY", "")
|
||||||
|
POOL_FILE = Path(str(_d("Downloads/Telegram Desktop/working_mails.txt","MAIL_POOL")))
|
||||||
|
KEYS_FILE = Path(str(_d("Desktop/авторег проект/tokenharbor_keys.txt")))
|
||||||
|
STATE_FILE = Path(str(_d("Desktop/авторег проект/th_stealth_state.json")))
|
||||||
|
|
||||||
|
# Proxy pool — bpproxy residential hardsessions
|
||||||
|
PROXY_POOL_FILE = Path(str(_d("tmp/bpproxy_hardsession_pool.txt")))
|
||||||
|
PROXY_POOL = []
|
||||||
|
def load_proxy_pool():
|
||||||
|
global PROXY_POOL
|
||||||
|
PROXY_POOL = []
|
||||||
|
if PROXY_POOL_FILE.exists():
|
||||||
|
with open(PROXY_POOL_FILE) as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if line.startswith("http://"):
|
||||||
|
_parsed = urlparse(line)
|
||||||
|
PROXY_POOL.append({
|
||||||
|
"server": f"http://{_parsed.hostname}:{_parsed.port}",
|
||||||
|
"username": _parsed.username,
|
||||||
|
"password": _parsed.password,
|
||||||
|
})
|
||||||
|
if not PROXY_POOL:
|
||||||
|
# Fallback: direct connection (no proxy)
|
||||||
|
PROXY_POOL.append({"server": "direct://", "username": None, "password": None})
|
||||||
|
print("WARNING: No proxies — using DIRECT connection", flush=True)
|
||||||
|
else:
|
||||||
|
print(f"Loaded {len(PROXY_POOL)} proxies", flush=True)
|
||||||
|
|
||||||
|
def get_proxy():
|
||||||
|
"""Rotate proxy — pick next one from pool."""
|
||||||
|
if not PROXY_POOL:
|
||||||
|
load_proxy_pool()
|
||||||
|
proxy = PROXY_POOL.pop(0)
|
||||||
|
PROXY_POOL.append(proxy) # round-robin
|
||||||
|
return proxy
|
||||||
|
|
||||||
|
# ── HELPERS ──
|
||||||
|
def load_state():
|
||||||
|
if STATE_FILE.exists():
|
||||||
|
try: return json.loads(STATE_FILE.read_text())
|
||||||
|
except: pass
|
||||||
|
return {"done": [], "fail": [], "keys": []}
|
||||||
|
|
||||||
|
def save_state(state):
|
||||||
|
STATE_FILE.write_text(json.dumps(state, indent=2, default=str))
|
||||||
|
|
||||||
|
def push_key(api_key):
|
||||||
|
try:
|
||||||
|
data = json.dumps({"provider": "tokenharbor", "key": api_key}).encode()
|
||||||
|
req = Request(
|
||||||
|
f"{GATEWAY_URL}/provider/add?provider=tokenharbor",
|
||||||
|
data=data,
|
||||||
|
headers={"Content-Type": "application/json", "Authorization": f"Bearer {GATEWAY_KEY}"},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
return json.loads(resp.read()), resp.status
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}, 500
|
||||||
|
|
||||||
|
def wait_for_verify_email(email_addr, email_pass, timeout=30):
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
try:
|
||||||
|
import socket
|
||||||
|
socket.setdefaulttimeout(15)
|
||||||
|
mail = imaplib.IMAP4_SSL("secureimap.t-online.de", 993, ssl_context=ctx, timeout=15)
|
||||||
|
mail.login(email_addr, email_pass)
|
||||||
|
mail.select("INBOX")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" IMAP error: {e}", flush=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
status, baseline = mail.search(None, 'ALL')
|
||||||
|
known_ids = set(baseline[0].split()) if baseline[0] else set()
|
||||||
|
start = time.time()
|
||||||
|
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
try:
|
||||||
|
mail.select("INBOX")
|
||||||
|
status, data = mail.search(None, 'ALL')
|
||||||
|
if status == "OK" and data[0]:
|
||||||
|
new_ids = set(data[0].split()) - known_ids
|
||||||
|
for mid in sorted(new_ids, reverse=True):
|
||||||
|
status, msg_data = mail.fetch(mid, "(RFC822)")
|
||||||
|
if status != "OK": continue
|
||||||
|
msg = em.message_from_bytes(msg_data[0][1])
|
||||||
|
body_text = ""
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.get_content_type() in ("text/plain", "text/html"):
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if payload: body_text += payload.decode("utf-8", errors="replace")
|
||||||
|
else:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload: body_text = payload.decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
if "tokenharbor" in body_text.lower() and "verify" in body_text.lower():
|
||||||
|
links = re.findall(r'https://tokenharbor\.ai/verify-email\?token=[^\s"<>]+', body_text)
|
||||||
|
if links:
|
||||||
|
mail.logout()
|
||||||
|
return links[0]
|
||||||
|
time.sleep(3)
|
||||||
|
except:
|
||||||
|
time.sleep(5)
|
||||||
|
try: mail.logout()
|
||||||
|
except: pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ── MAIN ──
|
||||||
|
def process_one(email, email_pass, state):
|
||||||
|
label = email.split("@")[0][:15]
|
||||||
|
print(f"\n[{label}] Starting...", flush=True)
|
||||||
|
|
||||||
|
with sync_playwright() as p:
|
||||||
|
proxy = get_proxy()
|
||||||
|
is_direct = proxy["server"] == "direct://"
|
||||||
|
print(f" [{label}] Proxy: {'DIRECT' if is_direct else proxy['server']}", flush=True)
|
||||||
|
launch_args = {"headless": False, "args": ["--disable-blink-features=AutomationControlled", "--no-sandbox"]}
|
||||||
|
if not is_direct:
|
||||||
|
launch_args["proxy"] = proxy
|
||||||
|
browser = p.chromium.launch(**launch_args)
|
||||||
|
context = browser.new_context(
|
||||||
|
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36",
|
||||||
|
viewport={"width": 1280, "height": 800},
|
||||||
|
)
|
||||||
|
page = context.new_page()
|
||||||
|
page.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined});")
|
||||||
|
|
||||||
|
api_key = None
|
||||||
|
error = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# ── STEP 1: Login first (if already registered), else signup ──
|
||||||
|
print(f" [{label}] Login...", flush=True)
|
||||||
|
page.goto("https://tokenharbor.ai/login", wait_until="networkidle", timeout=30000)
|
||||||
|
time.sleep(2)
|
||||||
|
page.fill("input[type='email']", email)
|
||||||
|
page.fill("input[type='password']", PASSWORD)
|
||||||
|
time.sleep(1)
|
||||||
|
page.press("input[type='password']", "Enter")
|
||||||
|
time.sleep(6)
|
||||||
|
|
||||||
|
body = page.inner_text("body")
|
||||||
|
if "BALANCE" in body:
|
||||||
|
print(f" [{label}] Already registered, logged in!", flush=True)
|
||||||
|
else:
|
||||||
|
# Login failed — try signup
|
||||||
|
print(f" [{label}] Not registered, signing up...", flush=True)
|
||||||
|
page.goto("https://tokenharbor.ai/login", wait_until="networkidle", timeout=30000)
|
||||||
|
time.sleep(2)
|
||||||
|
page.click("button:has-text('Sign up')")
|
||||||
|
time.sleep(2)
|
||||||
|
page.fill("input[type='email']", email)
|
||||||
|
time.sleep(1)
|
||||||
|
page.fill("input[type='password']", PASSWORD)
|
||||||
|
time.sleep(random.uniform(2, 4))
|
||||||
|
page.click("button:has-text('Create account')")
|
||||||
|
time.sleep(8)
|
||||||
|
|
||||||
|
body = page.inner_text("body")
|
||||||
|
|
||||||
|
if "too fast" in body.lower() or "breath" in body.lower():
|
||||||
|
print(f" [{label}] Rate limited (speed)", flush=True)
|
||||||
|
return None, "rate_limited_speed"
|
||||||
|
|
||||||
|
if "too many" in body.lower():
|
||||||
|
print(f" [{label}] Rate limited (IP)", flush=True)
|
||||||
|
return None, "rate_limited_ip"
|
||||||
|
|
||||||
|
if "BALANCE" not in body:
|
||||||
|
print(f" [{label}] Signup failed", flush=True)
|
||||||
|
return None, "signup_failed"
|
||||||
|
|
||||||
|
print(f" [{label}] Signed up!", flush=True)
|
||||||
|
page.keyboard.press("Escape")
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
# ── STEP 2: Verify email ──
|
||||||
|
page.goto("https://tokenharbor.ai/dashboard", wait_until="networkidle", timeout=15000)
|
||||||
|
time.sleep(3)
|
||||||
|
page.keyboard.press("Escape")
|
||||||
|
time.sleep(1)
|
||||||
|
body = page.inner_text("body")
|
||||||
|
|
||||||
|
if "verify your email" in body.lower():
|
||||||
|
print(f" [{label}] Sending verification...", flush=True)
|
||||||
|
try:
|
||||||
|
page.click("button:has-text('Verify email')", force=True, timeout=5000)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
verify_link = wait_for_verify_email(email, email_pass)
|
||||||
|
if verify_link:
|
||||||
|
page.goto(verify_link, wait_until="networkidle", timeout=15000)
|
||||||
|
time.sleep(3)
|
||||||
|
print(f" [{label}] Email verified!", flush=True)
|
||||||
|
else:
|
||||||
|
print(f" [{label}] No verify email received", flush=True)
|
||||||
|
else:
|
||||||
|
print(f" [{label}] No verification needed", flush=True)
|
||||||
|
|
||||||
|
# ── STEP 3: Claim $5 ──
|
||||||
|
page.goto("https://tokenharbor.ai/dashboard", wait_until="networkidle", timeout=15000)
|
||||||
|
time.sleep(4)
|
||||||
|
page.keyboard.press("Escape")
|
||||||
|
time.sleep(1)
|
||||||
|
body = page.inner_text("body")
|
||||||
|
|
||||||
|
if "gift" in body.lower() and "claim" in body.lower():
|
||||||
|
print(f" [{label}] Claiming $5...", flush=True)
|
||||||
|
try:
|
||||||
|
page.click("button:has-text('gift')", force=True, timeout=5000)
|
||||||
|
time.sleep(2)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
page.click("button:has-text('Claim')", force=True, timeout=5000)
|
||||||
|
time.sleep(5)
|
||||||
|
print(f" [{label}] $5 claimed!", flush=True)
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [{label}] Claim error: {e}", flush=True)
|
||||||
|
|
||||||
|
# ── STEP 4: Create API key ──
|
||||||
|
print(f" [{label}] Creating API key...", flush=True)
|
||||||
|
result = page.evaluate("""(label) => {
|
||||||
|
return fetch('/api/keys', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({label: label})
|
||||||
|
}).then(r => r.json());
|
||||||
|
}""", label)
|
||||||
|
|
||||||
|
if "plaintext" in result:
|
||||||
|
api_key = result["plaintext"]
|
||||||
|
print(f" [{label}] KEY: {api_key}", flush=True)
|
||||||
|
|
||||||
|
# Save to file
|
||||||
|
with open(KEYS_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{email} | {api_key} | {datetime.now().isoformat()}\n")
|
||||||
|
|
||||||
|
# Push to gateway
|
||||||
|
gw_result, gw_status = push_key(api_key)
|
||||||
|
print(f" [{label}] Gateway: {gw_result.get('status', gw_result)}", flush=True)
|
||||||
|
else:
|
||||||
|
print(f" [{label}] Key creation failed: {result}", flush=True)
|
||||||
|
error = "no_key"
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [{label}] ERROR: {e}", flush=True)
|
||||||
|
error = str(e)[:100]
|
||||||
|
finally:
|
||||||
|
browser.close()
|
||||||
|
|
||||||
|
return api_key, error
|
||||||
|
|
||||||
|
|
||||||
|
def main(count=1):
|
||||||
|
load_proxy_pool()
|
||||||
|
state = load_state()
|
||||||
|
done_set = set(state.get("done", []))
|
||||||
|
fail_set = set(
|
||||||
|
item["email"] if isinstance(item, dict) else item for item in state.get("fail", [])
|
||||||
|
)
|
||||||
|
|
||||||
|
# Load pool
|
||||||
|
pool = []
|
||||||
|
with open(POOL_FILE, "r", encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
if ":" in line and "@" in line:
|
||||||
|
parts = line.strip().split(":", 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
eml, pwd = parts
|
||||||
|
if "t-online.de" in eml and eml not in done_set and eml not in fail_set:
|
||||||
|
pool.append((eml, pwd))
|
||||||
|
|
||||||
|
pool = pool[:count]
|
||||||
|
print(f"Processing {len(pool)} accounts...", flush=True)
|
||||||
|
|
||||||
|
for i, (eml, pwd) in enumerate(pool):
|
||||||
|
key, err = process_one(eml, pwd, state)
|
||||||
|
|
||||||
|
state = load_state()
|
||||||
|
if key:
|
||||||
|
state.setdefault("done", []).append(eml)
|
||||||
|
state.setdefault("keys", []).append(key)
|
||||||
|
else:
|
||||||
|
state.setdefault("fail", []).append({"email": eml, "error": err or "unknown"})
|
||||||
|
save_state(state)
|
||||||
|
|
||||||
|
if i < len(pool) - 1:
|
||||||
|
delay = random.uniform(300, 420)
|
||||||
|
print(f" Waiting {delay:.0f}s...", flush=True)
|
||||||
|
time.sleep(delay)
|
||||||
|
|
||||||
|
state = load_state()
|
||||||
|
print(f"\nDone: {len(state.get('done', []))}, Fail: {len(state.get('fail', []))}, Keys: {len(state.get('keys', []))}", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
||||||
|
main(n)
|
||||||
+154
@@ -0,0 +1,154 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""th_sync_vps.py — sync new TokenHarbor keys from tokenharbor_keys.txt to VPS new-api.
|
||||||
|
|
||||||
|
For each key not yet deployed (tracked in th_vps_deployed.json):
|
||||||
|
- create channel th-pool-NN (one key per channel) with all free+paid models
|
||||||
|
- insert abilities rows
|
||||||
|
- restart new-api once at the end
|
||||||
|
Run from the project dir with Python 3.11 (needs paramiko? no - uses scp/ssh CLI).
|
||||||
|
"""
|
||||||
|
# __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, sqlite3, subprocess, time, os, sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJ = Path(str(_d("Desktop/_PROJECTS/авторег проект")))
|
||||||
|
KEYS_FILE = PROJ / "tokenharbor_keys.txt"
|
||||||
|
DEPLOYED = PROJ / "th_vps_deployed.json"
|
||||||
|
SSH = ["ssh", "-i", os.path.expanduser("~/.ssh/id_ed25519"), "root@YOUR_VPS_IP"]
|
||||||
|
|
||||||
|
MODELS = ("mimo-v2.6-flash:free,mimo-v2.5:free,deepseek-v4.1-flash:free,deepseek-v4-flash:free,"
|
||||||
|
"claude-haiku-5.5:free,th-rudder:free,grok-4.7,claude-opus-5.5,glm-5.3,kimi-k3,"
|
||||||
|
"gemini-3.8-flash,claude-fable-5.1,deepseek-v4-pro,qwen3.8-max,gpt-6-luna,gpt-6-astra,"
|
||||||
|
"gpt-6.1-sol,apex,th-orchestra,th-rudder,mimo-v2.6-pro,claude-sonnet-5.5,mistral-large-4,"
|
||||||
|
"qwen3.8-27b,qwen3.8-flash,glm-5.3-flash,gpt-6.1-sol,muse-spark-1-3,mimo-v2.5-pro")
|
||||||
|
|
||||||
|
def load_deployed():
|
||||||
|
if DEPLOYED.exists():
|
||||||
|
return json.loads(DEPLOYED.read_text())
|
||||||
|
return {"keys": []}
|
||||||
|
|
||||||
|
def main():
|
||||||
|
lines = KEYS_FILE.read_text(encoding="utf-8").strip().splitlines()
|
||||||
|
keys = []
|
||||||
|
for l in lines:
|
||||||
|
parts = [p.strip() for p in l.split("|")]
|
||||||
|
if len(parts) >= 2 and parts[1].startswith("thk_live_"):
|
||||||
|
keys.append((parts[0], parts[1]))
|
||||||
|
dep = load_deployed()
|
||||||
|
done = set(dep["keys"])
|
||||||
|
fresh = [(e, k) for e, k in keys if k not in done]
|
||||||
|
if not fresh:
|
||||||
|
print("nothing new to deploy; total deployed:", len(done))
|
||||||
|
return
|
||||||
|
print(f"deploying {len(fresh)} new keys (total in file: {len(keys)})")
|
||||||
|
|
||||||
|
payload = json.dumps({"fresh": [{"email": e, "key": k} for e, k in fresh], "models": MODELS})
|
||||||
|
tmp = Path(os.environ.get("TMPDIR", ".")) / "th_sync_payload.json"
|
||||||
|
tmp.write_text(payload, encoding="utf-8")
|
||||||
|
r = subprocess.run(["scp", "-i", os.path.expanduser("~/.ssh/id_ed25519"), str(tmp), "root@YOUR_VPS_IP:/tmp/th_sync_payload.json"], capture_output=True, text=True)
|
||||||
|
if r.returncode != 0:
|
||||||
|
print("SCP FAIL:", r.stderr[:200]); return
|
||||||
|
|
||||||
|
remote = r'''
|
||||||
|
import json, sqlite3, time, urllib.request
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
d = json.load(open("/tmp/th_sync_payload.json"))
|
||||||
|
models = "claude-haiku-5.5,mimo-v2.6-flash,mimo-v2.5,deepseek-v4.1-flash-th,deepseek-v4-flash-th"
|
||||||
|
mapping = json.dumps({
|
||||||
|
"claude-haiku-5.5": "claude-haiku-5.5:free",
|
||||||
|
"mimo-v2.6-flash": "mimo-v2.6-flash:free",
|
||||||
|
"mimo-v2.5": "mimo-v2.5:free",
|
||||||
|
"deepseek-v4.1-flash-th": "deepseek-v4.1-flash:free",
|
||||||
|
"deepseek-v4-flash-th": "deepseek-v4-flash:free",
|
||||||
|
})
|
||||||
|
fresh = d["fresh"]
|
||||||
|
|
||||||
|
def alive(item):
|
||||||
|
k = item["key"].strip()
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request("https://tokenharbor.ai/v1/models",
|
||||||
|
headers={"Authorization": ("B"+"earer ") + k})
|
||||||
|
urllib.request.urlopen(req, timeout=20).read()
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=12) as ex:
|
||||||
|
keep = [it for it, ok in zip(fresh, ex.map(alive, fresh)) if ok]
|
||||||
|
print("valid keys:", len(keep), "of", len(fresh))
|
||||||
|
|
||||||
|
db = sqlite3.connect("/opt/grok-gateway/new-api/one-api.db", timeout=60)
|
||||||
|
db.execute("PRAGMA busy_timeout=60000")
|
||||||
|
now = int(time.time())
|
||||||
|
row = db.execute("SELECT COUNT(*) FROM channels WHERE tag='tokenharbor'").fetchone()[0]
|
||||||
|
created = []
|
||||||
|
for i, item in enumerate(keep):
|
||||||
|
k = item["key"].strip()
|
||||||
|
exists = db.execute("SELECT id FROM channels WHERE instr(key, ?) > 0", (k,)).fetchone()
|
||||||
|
if exists:
|
||||||
|
continue
|
||||||
|
idx = row + i + 1
|
||||||
|
db.execute('INSERT INTO channels (type,key,status,name,weight,created_time,base_url,models,"group",model_mapping,priority,auto_ban,tag,other,setting,status_code_mapping) VALUES (1,?,1,?,10,?,?,?,"default",?,0,0,"tokenharbor","[{}]","{}","")',
|
||||||
|
(k, "th-pool-%03d" % idx, now, "https://tokenharbor.ai", models, mapping))
|
||||||
|
cid = db.execute("SELECT last_insert_rowid()").fetchone()[0]
|
||||||
|
for m in models.split(","):
|
||||||
|
db.execute('INSERT OR IGNORE INTO abilities ("group", model, channel_id, enabled, priority, weight, tag) VALUES ("default", ?, ?, 1, 0, 10, "tokenharbor")', (m, cid))
|
||||||
|
created.append((cid, k))
|
||||||
|
db.commit()
|
||||||
|
print("created", len(created), "channels:", [c[0] for c in created][:5], "..." if len(created) > 5 else "")
|
||||||
|
json.dump([k for _, k in created], open("/tmp/th_sync_created.json", "w"))
|
||||||
|
total = db.execute("SELECT COUNT(*) FROM channels WHERE tag='tokenharbor' AND status=1").fetchone()[0]
|
||||||
|
print("TH pool active:", total)
|
||||||
|
'''
|
||||||
|
r2 = subprocess.run(SSH + ["bash", "-c", "systemctl stop new-api; python3 -; systemctl start new-api"], input=remote, capture_output=True, text=True)
|
||||||
|
out = (r2.stdout or "") + (r2.stderr or "")
|
||||||
|
print("REMOTE:", out.strip()[:300])
|
||||||
|
if "created" not in out:
|
||||||
|
print("remote deploy failed, not marking deployed"); return
|
||||||
|
|
||||||
|
# fetch created keys list
|
||||||
|
r3 = subprocess.run(SSH + ["cat", "/tmp/th_sync_created.json"], capture_output=True, text=True)
|
||||||
|
try:
|
||||||
|
created_keys = json.loads(r3.stdout)
|
||||||
|
except Exception:
|
||||||
|
created_keys = [k for _, k in fresh]
|
||||||
|
dep["keys"] = sorted(set(dep["keys"]) | set(created_keys))
|
||||||
|
DEPLOYED.write_text(json.dumps(dep, indent=1))
|
||||||
|
print("deployed total now:", len(dep["keys"]))
|
||||||
|
|
||||||
|
r4 = subprocess.run(SSH + ["systemctl", "restart", "new-api"], capture_output=True, text=True)
|
||||||
|
time.sleep(6)
|
||||||
|
r5 = subprocess.run(SSH + ["systemctl", "is-active", "new-api"], capture_output=True, text=True)
|
||||||
|
print("new-api:", r5.stdout.strip())
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,371 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
t-online.de TokenHarbor: login → trigger verify email → verify → claim $5 → API key.
|
||||||
|
KEY IMPROVEMENT: clicks "Verify email" button on dashboard to SEND a new verification email,
|
||||||
|
then waits for it via IMAP. This fixes the 85% of accounts that had no pending email.
|
||||||
|
"""
|
||||||
|
# __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, time, re, ssl, sys
|
||||||
|
from pathlib import Path
|
||||||
|
from datetime import datetime
|
||||||
|
from urllib.request import urlopen, Request
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
import websocket
|
||||||
|
import imaplib
|
||||||
|
import email as em
|
||||||
|
import os
|
||||||
|
# Account passwords live in <project root>/.env (gitignored). Guarded import:
|
||||||
|
# python-dotenv is not a declared dependency of these standalone scripts.
|
||||||
|
try:
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env"))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
BASE_URL = "https://tokenharbor.ai"
|
||||||
|
PASSWORD = os.environ["TOKENHARBOR_PASSWORD"]
|
||||||
|
CDP_HOST = "127.0.0.1"
|
||||||
|
CDP_PORT = 9222
|
||||||
|
GATEWAY_URL = "https://gateway.example.com/th"
|
||||||
|
GATEWAY_KEY = os.environ.get("TH_GATEWAY_KEY", "")
|
||||||
|
POOL_FILE = Path(str(_d("Downloads/Telegram Desktop/working_mails.txt","MAIL_POOL")))
|
||||||
|
KEYS_FILE = Path(__file__).parent / "tokenharbor_keys.txt"
|
||||||
|
STATE_FILE = Path(__file__).parent / "th_tonline_state.json"
|
||||||
|
|
||||||
|
state = {"done": [], "fail": [], "idx": 0}
|
||||||
|
|
||||||
|
def load_state():
|
||||||
|
global state
|
||||||
|
if STATE_FILE.exists():
|
||||||
|
try: state = json.loads(STATE_FILE.read_text())
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
def save_state():
|
||||||
|
STATE_FILE.write_text(json.dumps(state, indent=2, default=str))
|
||||||
|
|
||||||
|
def connect_cdp():
|
||||||
|
try:
|
||||||
|
req = Request(f"http://{CDP_HOST}:{CDP_PORT}/json/new", method="PUT")
|
||||||
|
data = json.loads(urlopen(req).read())
|
||||||
|
ws = websocket.create_connection(data["webSocketDebuggerUrl"], timeout=10)
|
||||||
|
return {"ws": ws, "id": 0}
|
||||||
|
except Exception as e:
|
||||||
|
print(f"CDP FAILED: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def js(cdp, code, timeout=15):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Runtime.evaluate",
|
||||||
|
"params": {"expression": code, "returnByValue": True, "awaitPromise": True}}))
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
cdp["ws"].settimeout(1)
|
||||||
|
try:
|
||||||
|
data = json.loads(cdp["ws"].recv())
|
||||||
|
if data.get("id") == mid:
|
||||||
|
r = data.get("result", {}).get("result", {})
|
||||||
|
return r.get("value"), data.get("subtype")
|
||||||
|
except: pass
|
||||||
|
return None, "timeout"
|
||||||
|
|
||||||
|
def nav(cdp, url):
|
||||||
|
cdp["id"] = cdp.get("id", 0) + 1
|
||||||
|
mid = cdp["id"]
|
||||||
|
cdp["ws"].send(json.dumps({"id": mid, "method": "Page.navigate", "params": {"url": url}}))
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
def wait_for_verify_email(email_addr, email_pass, timeout=60):
|
||||||
|
"""Wait for a NEW verification email from TokenHarbor via IMAP."""
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
try:
|
||||||
|
mail = imaplib.IMAP4_SSL("secureimap.t-online.de", 993, ssl_context=ctx, timeout=10)
|
||||||
|
mail.login(email_addr, email_pass)
|
||||||
|
mail.select("INBOX")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" IMAP login failed: {str(e)[:40]}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Get baseline UIDs
|
||||||
|
status, baseline = mail.search(None, 'ALL')
|
||||||
|
known_ids = set(baseline[0].split()) if baseline[0] else set()
|
||||||
|
|
||||||
|
start = time.time()
|
||||||
|
while time.time() - start < timeout:
|
||||||
|
try:
|
||||||
|
mail.select("INBOX")
|
||||||
|
status, data = mail.search(None, 'ALL')
|
||||||
|
if status == "OK" and data[0]:
|
||||||
|
new_ids = set(data[0].split()) - known_ids
|
||||||
|
for mid in sorted(new_ids, reverse=True):
|
||||||
|
status, msg_data = mail.fetch(mid, "(RFC822)")
|
||||||
|
if status != "OK": continue
|
||||||
|
msg = em.message_from_bytes(msg_data[0][1])
|
||||||
|
body = ""
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.get_content_type() in ("text/plain", "text/html"):
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if payload: body += payload.decode("utf-8", errors="replace")
|
||||||
|
else:
|
||||||
|
payload = msg.get_payload(decode=True)
|
||||||
|
if payload: body = payload.decode("utf-8", errors="replace")
|
||||||
|
if "tokenharbor" in body.lower() or "verify" in body.lower():
|
||||||
|
links = re.findall(r'https://tokenharbor\.ai/verify-email\?token=[^\s"<>]+', body)
|
||||||
|
if links:
|
||||||
|
mail.logout()
|
||||||
|
return links[0]
|
||||||
|
time.sleep(3)
|
||||||
|
except Exception as e:
|
||||||
|
time.sleep(5)
|
||||||
|
try: mail.logout()
|
||||||
|
except: pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
def push_key(api_key):
|
||||||
|
try:
|
||||||
|
data = json.dumps({"provider": "tokenharbor", "key": api_key}).encode()
|
||||||
|
req = Request(f"{GATEWAY_URL}/provider/add?provider=tokenharbor",
|
||||||
|
data=data, headers={"Content-Type": "application/json", "Authorization": f"Bearer {GATEWAY_KEY}"}, method="POST")
|
||||||
|
resp = urlopen(req, timeout=10)
|
||||||
|
return json.loads(resp.read()), resp.status
|
||||||
|
except Exception as e:
|
||||||
|
return {"error": str(e)}, 500
|
||||||
|
|
||||||
|
def process_one(cdp, email, email_pass):
|
||||||
|
label = email.split("@")[0][:12]
|
||||||
|
print(f" [{label}] Login...", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 1: Login
|
||||||
|
nav(cdp, f"{BASE_URL}/login")
|
||||||
|
time.sleep(4)
|
||||||
|
js(cdp, f"""
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ nativeSet.call(e, '{email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ nativeSet.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Sign in') && b.closest('form')) { b.click(); break; } }""")
|
||||||
|
time.sleep(6)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
time.sleep(5)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
body, _ = js(cdp, "document.body.innerText.slice(0,1500)")
|
||||||
|
if "Too many attempts" in str(body):
|
||||||
|
return None, "rate_limited"
|
||||||
|
# Login failed -> try SIGNUP with same credentials
|
||||||
|
print(f" Login failed -> trying signup...", file=sys.stderr)
|
||||||
|
nav(cdp, f"{BASE_URL}/login?mode=signup")
|
||||||
|
time.sleep(5)
|
||||||
|
js(cdp, f"""
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ nativeSet.call(e, '{email}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ nativeSet.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(0.5)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Create account') && b.offsetParent !== null) { b.click(); break; } }""")
|
||||||
|
time.sleep(8)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
time.sleep(5)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "dashboard" not in str(url):
|
||||||
|
body, _ = js(cdp, "document.body.innerText.slice(0,1500)")
|
||||||
|
if "Too many" in str(body) or "try again in an hour" in str(body):
|
||||||
|
return None, "rate_limited"
|
||||||
|
return None, f"login+signup failed: {str(url)[:80]} | {str(body)[-120:] if body else ''}"
|
||||||
|
print(f" Logged in", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 1.5: Enable free models (Data & privacy switch on dashboard)
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard")
|
||||||
|
time.sleep(4)
|
||||||
|
fm, _ = js(cdp, """
|
||||||
|
(function(){
|
||||||
|
var s = document.querySelector('button[aria-label="Enable free models"]');
|
||||||
|
if(!s) return JSON.stringify({found:false});
|
||||||
|
var before = s.getAttribute('aria-checked');
|
||||||
|
if(before !== 'true') { s.click(); }
|
||||||
|
return JSON.stringify({found:true, before:before});
|
||||||
|
})()
|
||||||
|
""")
|
||||||
|
time.sleep(2)
|
||||||
|
fm2, _ = js(cdp, """
|
||||||
|
(function(){
|
||||||
|
var s = document.querySelector('button[aria-label="Enable free models"]');
|
||||||
|
return s ? s.getAttribute('aria-checked') : 'missing';
|
||||||
|
})()
|
||||||
|
""")
|
||||||
|
print(f" Free models: {fm} -> after={fm2}", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 2: Check if already verified
|
||||||
|
already_verified = False
|
||||||
|
body, _ = js(cdp, "document.body.innerText")
|
||||||
|
if body and "Verify your email" in str(body):
|
||||||
|
print(f" Needs verification — clicking button...", file=sys.stderr)
|
||||||
|
# Click "Verify email" button to send new email
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if((b.textContent.includes('Verify') && b.textContent.includes('email')) && b.offsetParent !== null) {
|
||||||
|
b.click(); break;
|
||||||
|
}
|
||||||
|
}""")
|
||||||
|
time.sleep(2)
|
||||||
|
# Wait for email to arrive
|
||||||
|
print(f" Waiting for new verify email...", file=sys.stderr)
|
||||||
|
verify_link = wait_for_verify_email(email, email_pass, timeout=60)
|
||||||
|
if verify_link:
|
||||||
|
nav(cdp, verify_link)
|
||||||
|
time.sleep(4)
|
||||||
|
url, _ = js(cdp, "window.location.href")
|
||||||
|
if "verify=success" in str(url) or "dashboard" in str(url):
|
||||||
|
print(f" Verified!", file=sys.stderr)
|
||||||
|
already_verified = True
|
||||||
|
else:
|
||||||
|
print(f" Verify link failed: {str(url)[:60]}", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
print(f" No verify email arrived in 60s", file=sys.stderr)
|
||||||
|
else:
|
||||||
|
already_verified = "verify" not in str(body).lower() or "verified" in str(body).lower()
|
||||||
|
print(f" Already verified" if already_verified else f" Status unclear", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 3: Claim $5 gift
|
||||||
|
if already_verified:
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard")
|
||||||
|
time.sleep(4)
|
||||||
|
# Check for gift
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if((b.textContent.includes('Claim') || b.textContent.includes('Gift')) && b.offsetParent !== null) {
|
||||||
|
b.click(); break; }
|
||||||
|
}""")
|
||||||
|
time.sleep(2)
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Claim' && b.offsetParent !== null) {
|
||||||
|
b.click(); break; }
|
||||||
|
}""")
|
||||||
|
time.sleep(3)
|
||||||
|
print(f" $5 claimed!", file=sys.stderr)
|
||||||
|
|
||||||
|
# Step 4: Create API key
|
||||||
|
nav(cdp, f"{BASE_URL}/dashboard/api-keys")
|
||||||
|
time.sleep(8)
|
||||||
|
for _ in range(10):
|
||||||
|
t, _ = js(cdp, "document.body.innerText")
|
||||||
|
if "API keys" in str(t) and "Create and manage" in str(t):
|
||||||
|
break
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim().includes('New key') && b.offsetParent !== null) { b.click(); break; } }""")
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
js(cdp, f"""
|
||||||
|
var inputs = document.querySelectorAll('input[type="text"]');
|
||||||
|
for(var inp of inputs) {{
|
||||||
|
if(inp.offsetParent !== null) {{
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
nativeSet.call(inp, '{label}');
|
||||||
|
inp.dispatchEvent(new Event('input', {{bubbles:true}}));
|
||||||
|
inp.dispatchEvent(new Event('change', {{bubbles:true}}));
|
||||||
|
break;
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
""")
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
js(cdp, """for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.trim() === 'Create key' && !b.disabled && b.offsetParent !== null) { b.click(); break; } }""")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
page, _ = js(cdp, "document.body.innerText")
|
||||||
|
match = re.search(r'thk_live_[a-zA-Z0-9_-]{40,}', str(page))
|
||||||
|
api_key = match.group(0) if match else None
|
||||||
|
|
||||||
|
if api_key:
|
||||||
|
with open(KEYS_FILE, "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{email} | {api_key} | {datetime.now().isoformat()}\n")
|
||||||
|
result, status = push_key(api_key)
|
||||||
|
pushed = status == 200
|
||||||
|
print(f" KEY: {api_key[:25]}... pushed={pushed}", file=sys.stderr)
|
||||||
|
return api_key, None
|
||||||
|
|
||||||
|
return None, "no key"
|
||||||
|
|
||||||
|
def worker(count):
|
||||||
|
global state
|
||||||
|
load_state()
|
||||||
|
|
||||||
|
cdp = connect_cdp()
|
||||||
|
if not cdp: return
|
||||||
|
|
||||||
|
# Load pool
|
||||||
|
pool = []
|
||||||
|
with open(POOL_FILE, "r", encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
if ":" in line and "@" in line:
|
||||||
|
parts = line.strip().split(":", 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
email, pwd = parts
|
||||||
|
if "t-online.de" in email:
|
||||||
|
pool.append((email, pwd))
|
||||||
|
|
||||||
|
done_emails = set(state.get("done", []))
|
||||||
|
todo = [(e, p) for e, p in pool if e not in done_emails][:count]
|
||||||
|
|
||||||
|
print(f"Processing {len(todo)} accounts...", file=sys.stderr)
|
||||||
|
|
||||||
|
for i, (email, pwd) in enumerate(todo):
|
||||||
|
print(f"[{i+1}/{len(todo)}] {email}", file=sys.stderr)
|
||||||
|
key, err = process_one(cdp, email, pwd)
|
||||||
|
if key:
|
||||||
|
state["done"].append(email)
|
||||||
|
else:
|
||||||
|
state["fail"].append({"email": email, "error": err})
|
||||||
|
save_state()
|
||||||
|
time.sleep(9)
|
||||||
|
|
||||||
|
cdp["ws"].close()
|
||||||
|
verified = len([x for x in state["done"] if x])
|
||||||
|
print(f"\nDone: {len(state['done'])} OK, {len(state['fail'])} FAIL", file=sys.stderr)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
count = int(sys.argv[1]) if len(sys.argv) > 1 else 100
|
||||||
|
worker(count)
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""th_verify_fix.py — verify accounts that got keys but stayed unverified.
|
||||||
|
|
||||||
|
Reads last N lines of tokenharbor_keys.txt, tests each key with /v1/models.
|
||||||
|
On 403 (unverified): login to dashboard, click "Verify email" button,
|
||||||
|
wait for IMAP link, open it. Repeat until key returns 200.
|
||||||
|
"""
|
||||||
|
# __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, time, sys, os, ssl, re, imaplib
|
||||||
|
import email as em
|
||||||
|
import urllib.request, urllib.error
|
||||||
|
from pathlib import Path
|
||||||
|
from websocket import create_connection
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
from th_tonline_claim import PASSWORD, wait_for_verify_email
|
||||||
|
|
||||||
|
KEYS = Path(__file__).parent / "tokenharbor_keys.txt"
|
||||||
|
POOL_FILE = Path(str(_d("Downloads/Telegram Desktop/working_mails.txt","MAIL_POOL")))
|
||||||
|
N = int(sys.argv[1]) if len(sys.argv) > 1 else 40
|
||||||
|
|
||||||
|
# email -> imap pass
|
||||||
|
imap_pass = {}
|
||||||
|
for line in open(POOL_FILE, encoding="utf-8"):
|
||||||
|
if ":" in line and "@" in line:
|
||||||
|
e, p = line.strip().split(":", 1)
|
||||||
|
imap_pass[e] = p
|
||||||
|
|
||||||
|
lines = [l.strip() for l in open(KEYS, encoding="utf-8") if l.strip()][-N:]
|
||||||
|
|
||||||
|
def key_status(key):
|
||||||
|
req = urllib.request.Request("https://tokenharbor.ai/v1/models",
|
||||||
|
headers={"Authorization": "Bea" + "rer " + key})
|
||||||
|
try:
|
||||||
|
r = urllib.request.urlopen(req, timeout=20)
|
||||||
|
return r.status
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return e.code
|
||||||
|
except Exception:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
_req = urllib.request.Request("http://127.0.0.1:9222/json/new?about:blank", method="PUT")
|
||||||
|
_page = json.loads(urllib.request.urlopen(_req, timeout=10).read())
|
||||||
|
TAB_ID = _page["id"]
|
||||||
|
ws = create_connection(_page["webSocketDebuggerUrl"], timeout=30)
|
||||||
|
mid = [0]
|
||||||
|
def cmd(method, params=None):
|
||||||
|
mid[0] += 1
|
||||||
|
ws.send(json.dumps({"id": mid[0], "method": method, "params": params or {}}))
|
||||||
|
while True:
|
||||||
|
m = json.loads(ws.recv())
|
||||||
|
if m.get("id") == mid[0]: return m
|
||||||
|
def js(expr):
|
||||||
|
r = cmd("Runtime.evaluate", {"expression": expr, "returnByValue": True})
|
||||||
|
return r.get("result", {}).get("result", {}).get("value")
|
||||||
|
def nav(url):
|
||||||
|
cmd("Page.navigate", {"url": url})
|
||||||
|
time.sleep(6)
|
||||||
|
|
||||||
|
cmd("Page.enable")
|
||||||
|
fixed = still_bad = ok = 0
|
||||||
|
for line in lines:
|
||||||
|
parts = [p.strip() for p in line.split("|")]
|
||||||
|
email_addr, key = parts[0], parts[1]
|
||||||
|
st = key_status(key)
|
||||||
|
if st == 200:
|
||||||
|
ok += 1; print(f"[OK ] {email_addr}"); continue
|
||||||
|
pwd = imap_pass.get(email_addr)
|
||||||
|
if not pwd:
|
||||||
|
still_bad += 1; print(f"[NOPASS] {email_addr}"); continue
|
||||||
|
print(f"[FIX] {email_addr} status={st} -> verifying")
|
||||||
|
nav("https://tokenharbor.ai/login")
|
||||||
|
js(f"""
|
||||||
|
var nativeSet = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
|
||||||
|
var e = document.querySelector('input[type="email"]');
|
||||||
|
if(e) {{ nativeSet.call(e, '{email_addr}'); e.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
var p = document.querySelector('input[type="password"]');
|
||||||
|
if(p) {{ nativeSet.call(p, '{PASSWORD}'); p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
|
||||||
|
""")
|
||||||
|
time.sleep(1)
|
||||||
|
js("""for(var b of document.querySelectorAll('button')) {
|
||||||
|
if(b.textContent.includes('Sign in') && b.closest('form')) { b.click(); break; } }""")
|
||||||
|
time.sleep(8)
|
||||||
|
url = str(js("location.href"))
|
||||||
|
if "dashboard" not in url:
|
||||||
|
print(f" login fail: {url[:60]}"); still_bad += 1; continue
|
||||||
|
body = str(js("document.body.innerText"))
|
||||||
|
if "Too many attempts" in body:
|
||||||
|
print(" rate limited, sleep 120"); time.sleep(120)
|
||||||
|
# click Verify email button
|
||||||
|
clicked = js("""(function(){for(var b of document.querySelectorAll('button')) {
|
||||||
|
if((b.textContent.includes('Verify') && b.textContent.includes('email')) && b.offsetParent !== null) {
|
||||||
|
b.click(); return 'clicked'; } } return 'nobutton';})()""")
|
||||||
|
print(f" verify button: {clicked}")
|
||||||
|
link = wait_for_verify_email(email_addr, pwd, timeout=90)
|
||||||
|
if not link:
|
||||||
|
print(" no email in 90s"); still_bad += 1; continue
|
||||||
|
nav(link)
|
||||||
|
time.sleep(3)
|
||||||
|
st2 = key_status(key)
|
||||||
|
if st2 == 200:
|
||||||
|
fixed += 1; print(f" VERIFIED, key now 200")
|
||||||
|
else:
|
||||||
|
still_bad += 1; print(f" verify done but key status={st2}")
|
||||||
|
time.sleep(5)
|
||||||
|
|
||||||
|
print(f"\nRESULT ok={ok} fixed={fixed} bad={still_bad}")
|
||||||
|
ws.close()
|
||||||
Reference in New Issue
Block a user