Files
wavespeed-autoreg/wavespeed/ws_autoreg.py
T

190 lines
7.0 KiB
Python

#!/usr/bin/env python3
"""WaveSpeed.ai account autoregistration.
Flow per account:
1. GitHub login (direct egress) + OAuth authorize
2. WaveSpeed sign-in hop: GET /center/default/github/login?cf-turnstile-response=<token>
(Turnstile solved via 2captcha, task TurnstileTaskProxyless)
3. OAuth callback -> dashboard cookies
4. Read trial balance, create API key (POST /center/default/api/v1/accesskey/create)
Result: JSONL bank with {login, balance, key, cookies, egress}, keys usable on
LLM : https://llm.wavespeed.ai/v1/chat/completions
Media : https://api.wavespeed.ai/api/v3/<model>
Config via env:
WS_TWOCAP_KEY 2captcha client key (required)
WS_PROXY egress for the WaveSpeed leg, e.g. http://user:pass@host:8888 (optional)
WS_GH_POOL path to GitHub accounts JSON (list of {login,password,totp}) (required)
WS_BANK output JSONL path (default bank.jsonl)
WS_USED used-logins file (default used_gh.txt)
"""
import json
import os
import re
import sys
import time
import uuid
import requests
import pyotp
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36")
SITE = os.environ.get("WS_TURNSTILE_SITEKEY", "0x4AAAAAADkE2yCxK2sRF0Q4")
SIGNIN = "https://wavespeed.ai/sign-in"
KEY2CAP = os.environ.get("WS_TWOCAP_KEY", "")
PROXY = os.environ.get("WS_PROXY", "")
BANK = os.environ.get("WS_BANK", "bank.jsonl")
USED = os.environ.get("WS_USED", "used_gh.txt")
POOL = os.environ.get("WS_GH_POOL", "gh_pool.json")
def proxy_map():
if not PROXY:
return {}
return {"http": PROXY, "https": PROXY}
def turnstile_token():
"""Solve Cloudflare Turnstile for the sign-in page via 2captcha."""
s = requests.Session()
r = s.post("https://api.2captcha.com/createTask", json={
"clientKey": KEY2CAP,
"task": {
"type": "TurnstileTaskProxyless",
"websiteURL": SIGNIN,
"websiteKey": SITE,
"action": "login",
"userAgent": UA,
},
}, timeout=30).json()
tid = r.get("taskId")
if not tid:
raise RuntimeError("2captcha createTask: %s" % str(r)[:200])
for _ in range(40):
time.sleep(5)
res = s.post("https://api.2captcha.com/getTaskResult",
json={"clientKey": KEY2CAP, "taskId": tid}, timeout=30).json()
if res.get("status") == "ready":
return res["solution"]["token"]
if res.get("errorId"):
raise RuntimeError("2captcha error: %s" % str(res)[:200])
raise RuntimeError("turnstile timeout")
def github_login(acc):
"""Log into GitHub. Returns (session, status)."""
gs = requests.Session()
gs.headers.update({"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"})
r = gs.get("https://github.com/login", timeout=45)
m = re.search(r'name="authenticity_token" value="([^"]+)"', r.text)
if not m:
return None, "no-csrf"
r = gs.post("https://github.com/session", data={
"authenticity_token": m.group(1),
"login": acc["login"],
"password": acc["password"],
"commit": "Sign in",
"return_to": "",
}, timeout=45, allow_redirects=True)
if "verified-device" in r.url:
return None, "verified-device"
if "two-factor" in r.url:
if not acc.get("totp"):
return None, "2fa-no-secret"
m2 = re.search(r'name="authenticity_token" value="([^"]+)"', r.text)
r = gs.post("https://github.com/sessions/two-factor", data={
"authenticity_token": m2.group(1) if m2 else "",
"otp": pyotp.TOTP(acc["totp"]).now(),
}, timeout=45, allow_redirects=True)
if "two-factor" in r.url:
return None, "2fa-fail"
if "verified-device" in r.url:
return None, "verified-device"
if "github.com/login" in r.url:
return None, "login-fail"
return gs, "ok"
def register(acc):
t0 = time.time()
out = {"gh_login": acc["login"], "ts": int(t0)}
gs, st = github_login(acc)
out["gh"] = st
if not gs:
return out
ws = requests.Session()
ws.headers.update({"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"})
px = proxy_map()
if px:
ws.proxies.update(px)
try:
out["egress"] = requests.get("https://api.ipify.org?format=json",
proxies=px, timeout=25).json().get("ip")
except Exception:
out["egress"] = "?"
tok = turnstile_token()
r = ws.get("https://wavespeed.ai/center/default/github/login",
params={"cf-turnstile-response": tok}, allow_redirects=False, timeout=60)
if r.status_code != 302:
out["err"] = "hop %s" % r.status_code
return out
r2 = gs.get(r.headers["location"], timeout=45, allow_redirects=False)
loc = r2.headers.get("location", "")
if "login/oauth/authorize" in r2.url:
m3 = re.search(r'name="authenticity_token" value="([^"]+)"', r2.text)
r2 = gs.post(r2.url, data={"authenticity_token": m3.group(1) if m3 else "",
"authorize": "1"}, timeout=45, allow_redirects=False)
loc = r2.headers.get("location", "")
if not loc.startswith("https://wavespeed.ai"):
out["err"] = "no-callback(%s)" % (loc[:50] or r2.status_code)
return out
r3 = ws.get(loc, timeout=60, allow_redirects=True)
out["landed"] = r3.url
if "dashboard" not in r3.url:
out["err"] = "landed " + r3.url[:80]
return out
d = ws.get("https://wavespeed.ai/dashboard", timeout=60)
m4 = re.search(r'Current credit balance.{0,220}?\$\s*<!-- -->([0-9.]+)', d.text, re.S)
out["balance"] = m4.group(1) if m4 else None
kr = ws.post("https://wavespeed.ai/center/default/api/v1/accesskey/create",
json={"name": "k" + uuid.uuid4().hex[:6]}, timeout=60)
try:
out["key"] = (kr.json().get("data") or {}).get("key")
except Exception:
out["key_error"] = kr.text[:120]
out["cookies"] = {c.name: c.value for c in ws.cookies if c.name.startswith("wavespeed")}
out["secs"] = round(time.time() - t0, 1)
return out
def main(n):
pool = json.load(open(POOL, encoding="utf-8"))
used = set(open(USED).read().split()) if os.path.exists(USED) else set()
todo = [a for a in pool if a["login"] not in used]
print("pool: %d todo: %d" % (len(pool), len(todo)), flush=True)
for acc in todo[:n]:
try:
out = register(acc)
except Exception as e:
out = {"gh_login": acc["login"], "error": repr(e)[:200]}
with open(BANK, "a", encoding="utf-8") as f:
f.write(json.dumps(out, ensure_ascii=False) + "\n")
with open(USED, "a") as f:
f.write(acc["login"] + "\n")
print(json.dumps({k: out.get(k) for k in
("gh_login", "balance", "key", "egress", "gh", "err")},
ensure_ascii=False), flush=True)
if __name__ == "__main__":
main(int(sys.argv[1]) if len(sys.argv) > 1 else 10)