562 lines
21 KiB
Python
562 lines
21 KiB
Python
#!/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() |