283 lines
11 KiB
Python
283 lines
11 KiB
Python
#!/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) |