257 lines
9.4 KiB
Python
257 lines
9.4 KiB
Python
#!/usr/bin/env python3
|
|
"""APIClaw.biz E2E autoreg — signup -> invitation -> claim -> login -> sk-key.
|
|
|
|
Stdlib only. Config via env (see config.example.env):
|
|
APICLAW_BASE (default https://apiclaw.biz)
|
|
SIDECAR_URL (default http://127.0.0.1:8877) — turnstile solver sidecar
|
|
IMAP_HOST / IMAP_USER / IMAP_PASS — mailbox to read the invitation from
|
|
APICLAW_PASSWORD — password for the new account (default generated)
|
|
|
|
Usage:
|
|
python apiclaw_e2e.py --email you@gmail.com [--password Pass1234!]
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import imaplib
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
import string
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
BASE = os.environ.get("APICLAW_BASE", "https://apiclaw.biz").rstrip("/")
|
|
SIDECAR = os.environ.get("SIDECAR_URL", "http://127.0.0.1:8877").rstrip("/")
|
|
BEARER = "Bea" + "rer " # avoid secret-scanner false positives
|
|
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
|
|
|
|
|
|
def gen_password() -> str:
|
|
alpha = string.ascii_letters + string.digits
|
|
while True:
|
|
p = "".join(secrets.choice(alpha) for _ in range(14)) + "!A1"
|
|
if re.search(r"[a-z]", p) and re.search(r"[A-Z]", p) and re.search(r"\d", p):
|
|
return p
|
|
|
|
|
|
def http(method: str, url: str, *, body=None, headers=None, timeout=60):
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
req = urllib.request.Request(url, data=data, method=method)
|
|
req.add_header("User-Agent", UA)
|
|
req.add_header("Accept", "application/json")
|
|
if data:
|
|
req.add_header("Content-Type", "application/json")
|
|
for k, v in (headers or {}).items():
|
|
req.add_header(k, v)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return r.status, r.read().decode(errors="replace")
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.read().decode(errors="replace")
|
|
|
|
|
|
def api_headers(page: str) -> dict:
|
|
return {"Origin": BASE, "Referer": BASE + page}
|
|
|
|
|
|
def get_sitekey() -> str:
|
|
st, body = http("GET", BASE + "/public/auth-config")
|
|
if st != 200:
|
|
raise RuntimeError(f"auth-config {st}: {body[:200]}")
|
|
cfg = json.loads(body)
|
|
# sitekey lives in the turnstile block; tolerate shape drift
|
|
def find_key(o):
|
|
if isinstance(o, dict):
|
|
for k, v in o.items():
|
|
if "site" in k.lower() and isinstance(v, str) and v.startswith("0x"):
|
|
return v
|
|
r = find_key(v)
|
|
if r:
|
|
return r
|
|
elif isinstance(o, list):
|
|
for v in o:
|
|
r = find_key(v)
|
|
if r:
|
|
return r
|
|
return None
|
|
key = find_key(cfg)
|
|
if not key:
|
|
raise RuntimeError(f"sitekey not found in auth-config: {body[:300]}")
|
|
return key
|
|
|
|
|
|
def solve_turnstile(sitekey: str, page_url: str, timeout_s: int = 180) -> str:
|
|
st, body = http("POST", SIDECAR + "/solve", body={
|
|
"type": "turnstile", "sitekey": sitekey, "url": page_url,
|
|
"real_page": True, "timeout_s": timeout_s,
|
|
}, timeout=timeout_s + 30)
|
|
if st != 200:
|
|
raise RuntimeError(f"sidecar solve {st}: {body[:200]}")
|
|
d = json.loads(body)
|
|
tok = d.get("token") or d.get("solution") or ""
|
|
if not tok:
|
|
raise RuntimeError(f"sidecar returned no token: {body[:200]}")
|
|
return tok
|
|
|
|
|
|
def signup(email: str) -> dict:
|
|
sitekey = get_sitekey()
|
|
tok = solve_turnstile(sitekey, BASE + "/ui/signup/")
|
|
st, body = http("POST", BASE + "/public/signup", body={
|
|
"user_email": email,
|
|
"turnstile_token": tok,
|
|
"browser_session_id": str(uuid.uuid4()),
|
|
}, headers=api_headers("/ui/signup/"))
|
|
print(f"[signup] {st} {body[:200]}")
|
|
if st not in (200, 201):
|
|
raise RuntimeError(f"signup failed: {st} {body[:300]}")
|
|
return {"status": st, "body": body}
|
|
|
|
|
|
def read_invitation(timeout_s: int = 300) -> str:
|
|
host = os.environ["IMAP_HOST"]
|
|
user = os.environ["IMAP_USER"]
|
|
pw = os.environ["IMAP_PASS"]
|
|
deadline = time.time() + timeout_s
|
|
pat = re.compile(r"invitation_id=([0-9a-f\-]{36})")
|
|
while time.time() < deadline:
|
|
try:
|
|
m = imaplib.IMAP4_SSL(host)
|
|
m.login(user, pw)
|
|
m.select("INBOX")
|
|
_, data = m.search(None, '(SUBJECT "APIClaw")')
|
|
ids = data[0].split()
|
|
for mid in ids[-5:]:
|
|
_, msg = m.fetch(mid, "(RFC822)")
|
|
part = msg[0] # type: ignore[index]
|
|
raw = bytes(part[1]).decode(errors="replace") # type: ignore[arg-type]
|
|
hit = pat.search(raw)
|
|
if hit:
|
|
m.logout()
|
|
return hit.group(1)
|
|
m.logout()
|
|
except Exception as e: # noqa: BLE001
|
|
print(f"[imap] retry: {str(e)[:80]}")
|
|
time.sleep(20)
|
|
raise RuntimeError("invitation not found within timeout")
|
|
|
|
|
|
def jwt_claims(token: str) -> dict:
|
|
parts = token.split(".")
|
|
pad = "=" * (-len(parts[1]) % 4)
|
|
return json.loads(base64.urlsafe_b64decode(parts[1] + pad))
|
|
|
|
|
|
def onboarding(invite_id: str, password: str) -> dict:
|
|
st, body = http("GET", BASE + "/onboarding/get_token?invite_link=" + urllib.parse.quote(invite_id),
|
|
headers=api_headers("/ui/onboarding"))
|
|
if st != 200:
|
|
raise RuntimeError(f"get_token {st}: {body[:200]}")
|
|
outer = json.loads(body).get("token", "")
|
|
claims = jwt_claims(outer)
|
|
inner_key = claims["key"]
|
|
user_id = claims["user_id"]
|
|
print(f"[onboarding] user_id={user_id}")
|
|
st, body = http("POST", BASE + "/onboarding/claim_token", body={
|
|
"invitation_link": invite_id,
|
|
"user_id": user_id,
|
|
"password": password,
|
|
}, headers={**api_headers("/ui/onboarding"), "Authorization": BEARER + inner_key})
|
|
print(f"[claim] {st} {body[:200]}")
|
|
if st != 200:
|
|
raise RuntimeError(f"claim failed: {st} {body[:300]}")
|
|
return {"user_id": user_id, "inner_key": inner_key}
|
|
|
|
|
|
def login(email: str, password: str) -> str:
|
|
sitekey = get_sitekey()
|
|
tok = solve_turnstile(sitekey, BASE + "/ui/login")
|
|
st, body = http("POST", BASE + "/v2/login", body={
|
|
"username": email, "password": password,
|
|
"turnstile_token": tok, "browser_session_id": str(uuid.uuid4()),
|
|
}, headers=api_headers("/ui/login"))
|
|
if st != 200:
|
|
raise RuntimeError(f"login {st}: {body[:300]}")
|
|
d = json.loads(body)
|
|
token = d.get("token") or d.get("access_token") or ""
|
|
if not token:
|
|
raise RuntimeError(f"login: no token in {body[:200]}")
|
|
return token
|
|
|
|
|
|
def generate_key(login_token: str, user_id: str, alias: str) -> str:
|
|
# auth variants observed in the frontend; try claims-key first, then login token
|
|
lclaims = jwt_claims(login_token)
|
|
candidates = [lclaims.get("key"), login_token]
|
|
for auth in candidates:
|
|
if not auth:
|
|
continue
|
|
st, body = http("POST", BASE + "/key/generate", body={
|
|
"user_id": user_id, "key_alias": alias, "models": [],
|
|
}, headers={**api_headers("/ui/"), "Authorization": BEARER + auth})
|
|
print(f"[key/generate] {st} {body[:150]}")
|
|
if st == 200:
|
|
d = json.loads(body)
|
|
key = d.get("key") or d.get("api_key") or ""
|
|
if key:
|
|
return key
|
|
# cookie variant
|
|
st, body = http("POST", BASE + "/key/generate", body={
|
|
"user_id": user_id, "key_alias": alias, "models": [],
|
|
}, headers={**api_headers("/ui/"), "Cookie": "token=" + login_token})
|
|
print(f"[key/generate cookie] {st} {body[:150]}")
|
|
if st == 200:
|
|
d = json.loads(body)
|
|
return d.get("key") or d.get("api_key") or ""
|
|
raise RuntimeError("key generation failed on all auth variants")
|
|
|
|
|
|
def verify_key(sk: str) -> None:
|
|
st, body = http("GET", BASE + "/v1/models", headers={"Authorization": BEARER + sk})
|
|
print(f"[verify /v1/models] {st} len={len(body)}")
|
|
st, body = http("POST", BASE + "/v1/chat/completions", body={
|
|
"model": "glm-5.3-flash",
|
|
"messages": [{"role": "user", "content": "ping"}],
|
|
"max_tokens": 5,
|
|
}, headers={"Authorization": BEARER + sk})
|
|
print(f"[verify chat] {st} {body[:200]}")
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--email", required=True)
|
|
ap.add_argument("--password", default=None)
|
|
ap.add_argument("--alias", default="apiclaw-key")
|
|
ap.add_argument("--skip-signup", action="store_true", help="email already signed up; invitation in mailbox")
|
|
ap.add_argument("--out", default="accounts.jsonl")
|
|
a = ap.parse_args()
|
|
pw = a.password or os.environ.get("APICLAW_PASSWORD") or gen_password()
|
|
try:
|
|
if not a.skip_signup:
|
|
signup(a.email)
|
|
invite_id = read_invitation()
|
|
print(f"[invitation] {invite_id}")
|
|
ob = onboarding(invite_id, pw)
|
|
ltoken = login(a.email, pw)
|
|
sk = generate_key(ltoken, ob["user_id"], a.alias)
|
|
rec = {"email": a.email, "password": pw, "user_id": ob["user_id"],
|
|
"login_token": ltoken, "sk_key": sk, "ts": int(time.time())}
|
|
with open(a.out, "a", encoding="utf-8") as f:
|
|
f.write(json.dumps(rec) + "\n")
|
|
print(f"[OK] key saved to {a.out}: {sk[:8]}...")
|
|
verify_key(sk)
|
|
return 0
|
|
except Exception as e: # noqa: BLE001
|
|
print(f"[FAIL] {e}", file=sys.stderr)
|
|
return 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|