recovered snapshot from suspended aaronjaworski710 (history unavailable)

This commit is contained in:
reform
2026-10-23 20:03:54 +03:00
commit 749ce1fc8e
9 changed files with 639 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
tokens.json
token.txt
app_token.txt
refresh.txt
leg_key.txt
accounts.jsonl
reg_state.json
profile.json
catalog.json
*.log
front*/
setup_x/
*.exe
stream_out.txt
b*.txt
s*.txt
+44
View File
@@ -0,0 +1,44 @@
# Haze Toolkit
Research toolkit for usehaze.ai (Haze AI workspace, Tauri desktop app).
## What's here
| File | Purpose |
|------|---------|
| `haze_proxy.py` | OpenAI-compatible proxy over `https://v1.usehaze.ai/ai/v1` with token pool, round-robin rotation, auto-quarantine of dead tokens, upstream-error retry, SSE streaming |
| `mass_reg.py` | Mass registration: `POST /api/auth/bootstrap` (create:true) → IMAP OTP from t-online.de → `POST /api/auth/verify-code` → token into pool. Pacing + 429 backoff. State-resumable |
| `reg_one.py` | Single-account registration flow |
| `cdp_eval.py` | CDP eval helper against WebView2 (`--remote-debugging-port=9333`) |
| `fill_dialog.py` | Native Win32 folder-picker automation (SendMessageW WM_SETTEXT + BM_CLICK) for Tauri dialogs |
| `brotli_extract.py` | Extract embedded brotli frontend assets from `Haze.exe` |
## Architecture findings
- Desktop app = Tauri + WebView2; page URL `http://tauri.localhost/`
- Real model gateway: `https://v1.usehaze.ai/ai/v1` (OpenAI-compatible chat/completions + models catalog), auth = Bearer WorkOS access token (~24h exp)
- `gateway.legionedge.ai` = local-agent relay (kimi harness), not the chat gateway
- Model catalog is server-side (not in binary): `gpt-6-astra`, `gpt-6-luna`, `gpt-6-sol`, `gpt-6.1-sol`, `step-5-preview`
- Auth flow: WorkOS OTP email from `welcome@workos.dev`; `bootstrap create:false` = login (401 if unknown), `create:true` = register (`verification_required` + `pendingToken`)
- Cloudflare blocks bare python-urllib (403); curl with browser UA passes
- Free plan accounts get full model catalog access
## Proxy usage
```bash
python haze_proxy.py 16450
# GET /v1/models GET /health GET /pool
# POST /v1/chat/completions (stream: true supported)
```
Point any OpenAI client at `http://127.0.0.1:16450/v1`, api_key = any string.
Pool file: `tokens.json` — `[{"token":"***","email":"...","ok":true,"fails":0}]`
## Mass reg usage
```bash
python mass_reg.py <count> <workers> # reads email:pass pool file, writes tokens.json + accounts.jsonl
```
Resumable: `reg_state.json` tracks used mailboxes; 429 failures are retryable after backoff.
+24
View File
@@ -0,0 +1,24 @@
# Full brotli extraction of embedded frontend assets from Haze.exe
import brotli, os
exe = open(os.path.expandvars(r"%LOCALAPPDATA%\Programs\Haze\Haze.exe"),'rb').read()
os.makedirs('front2', exist_ok=True)
i = exe.find(b'/assets/index-')
start = max(0, i-3_000_000)
count=0
off=0
limit=min(34_000_000, len(exe)-start)
while off < limit:
try:
d=brotli.Decompressor()
out=d.process(exe[start+off:start+off+30_000_000])
if len(out)>50_000:
p=f'front2/blob_{off}.bin'
open(p,'wb').write(out)
print(p, len(out), flush=True)
count+=1
off += max(1,len(out)//10)
continue
except Exception:
pass
off+=1
print('blobs:',count)
+23
View File
@@ -0,0 +1,23 @@
import asyncio, json, websockets, sys
WS_URL = None
async def cdp(expr, ws=None):
import urllib.request
tabs = json.load(urllib.request.urlopen("http://127.0.0.1:9333/json"))
page = [t for t in tabs if t["type"]=="page"][0]
async with websockets.connect(page["webSocketDebuggerUrl"], max_size=50*1024*1024) as w:
await w.send(json.dumps({"id":1,"method":"Runtime.enable"}))
await w.recv()
await w.send(json.dumps({"id":2,"method":"Runtime.evaluate","params":{"expression":expr,"returnByValue":True,"awaitPromise":True}}))
while True:
msg = json.loads(await w.recv())
if msg.get("id")==2:
r = msg.get("result",{})
if "result" in r and "value" in r["result"]:
return r["result"]["value"]
return json.dumps(r)[:2000]
if __name__ == "__main__":
expr = sys.argv[1]
print(asyncio.run(cdp(expr)))
+77
View File
@@ -0,0 +1,77 @@
# __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 ctypes, ctypes.wintypes as wt, time
user32=ctypes.windll.user32
SendMessageW=user32.SendMessageW
SendMessageW.restype=ctypes.c_long
SendMessageW.argtypes=[wt.HWND,wt.UINT,wt.WPARAM,wt.LPARAM]
FOLDER=str(_w("tmp/haze_testproj"))
handles=[199774,34409320,85330480]
EnumChild=ctypes.WINFUNCTYPE(wt.BOOL,wt.HWND,wt.LPARAM)
def get_class(hwnd):
buf=ctypes.create_unicode_buffer(256)
user32.GetClassNameW(hwnd,buf,256)
return buf.value
for h in handles:
if not user32.IsWindowVisible(h):
print(h,"invisible, skip"); continue
edits=[]; btns=[]
def cb(ch,lp):
c=get_class(ch)
n=user32.GetWindowTextLengthW(ch)
buf=ctypes.create_unicode_buffer(n+1)
user32.GetWindowTextW(ch,buf,n+1)
if c=="Edit": edits.append((ch,buf.value))
if c=="Button" and buf.value: btns.append((ch,buf.value))
return True
user32.EnumChildWindows(h,EnumChild(cb),0)
print(h,"edits:",[e[1][:40] for e in edits],"btns:",[b[1][:30] for b in btns][:8])
if edits:
e=edits[0][0]
p=ctypes.create_unicode_buffer(FOLDER)
SendMessageW(e,0x000C,0,ctypes.addressof(p))
time.sleep(0.3)
tgt=None
for bh,txt in btns:
if "\u043f\u0430\u043f\u043a\u0438" in txt.lower() or "select folder" in txt.lower():
tgt=bh; break
if tgt:
SendMessageW(tgt,0x00F5,0,0)
print(" clicked button on",h)
else:
user32.PostMessageW(h,0x0111,1,0)
print(" posted IDOK on",h)
time.sleep(1.5)
else:
user32.PostMessageW(h,0x0111,2,0)
time.sleep(0.5)
+186
View File
@@ -0,0 +1,186 @@
#!/usr/bin/env python3
# Haze Gateway Proxy — OpenAI-compatible proxy over v1.usehaze.ai/ai
# Usage: python haze_proxy.py [port] (default 16450)
# Pool: tokens.json [{"token":"***","email":"...","ok":true,"fails":0}, ...]
# Endpoints: GET /v1/models, POST /v1/chat/completions (stream supported), GET /health, GET /pool
import json, os, sys, time, threading, subprocess, random
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 16450
BASE = "https://v1.usehaze.ai/ai/v1"
DIR = os.path.dirname(os.path.abspath(__file__))
POOL_F = os.path.join(DIR, "tokens.json")
LOCK = threading.Lock()
def load_pool():
with LOCK:
if not os.path.exists(POOL_F):
# seed from token.txt if present
tok = ""
tf = os.path.join(DIR, "token.txt")
if os.path.exists(tf):
raw = open(tf).read().strip()
try:
tok = json.loads(raw).get("accessToken", raw)
except Exception:
tok = raw
pool = [{"token": tok, "email": "seed", "ok": True, "fails": 0}] if tok else []
save_pool(pool)
return pool
return json.load(open(POOL_F, encoding="utf-8"))
def save_pool(pool):
tmp = POOL_F + ".tmp"
json.dump(pool, open(tmp, "w", encoding="utf-8"), indent=1)
os.replace(tmp, POOL_F)
POOL = load_pool()
RR = [0]
def next_token():
"""round-robin over healthy tokens"""
with LOCK:
healthy = [p for p in POOL if p.get("ok", True)]
if not healthy:
healthy = POOL # last resort: try everything
if not healthy:
return None
RR[0] = (RR[0] + 1) % len(healthy)
return healthy[RR[0]]
def mark(entry, ok):
with LOCK:
for p in POOL:
if p["token"] == entry["token"]:
if ok:
p["ok"] = True; p["fails"] = 0
else:
p["fails"] = p.get("fails", 0) + 1
if p["fails"] >= 5:
p["ok"] = False
break
save_pool(POOL)
def curl_json(url, headers, data=None, timeout=120, stream=False):
cmd = ["curl", "-s", "--max-time", str(timeout), url]
for k, v in headers.items():
cmd += ["-H", f"{k}: {v}"]
if data is not None:
cmd += ["-d", json.dumps(data)]
if not stream:
cmd += ["-w", "\n@@CODE:%{http_code}"]
r = subprocess.run(cmd, capture_output=True, text=True)
out = r.stdout
code = 0
if "@@CODE:" in out:
body, _, c = out.rpartition("@@CODE:")
try: code = int(c.strip())
except Exception: code = 0
return code, body
return 0, out
else:
cmd += ["-N"]
return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
class Handler(__import__("http.server", fromlist=["BaseHTTPRequestHandler"]).BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _send(self, code, body, ctype="application/json"):
b = body if isinstance(body, bytes) else body.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(b)
def do_OPTIONS(self):
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "*")
self.send_header("Access-Control-Allow-Methods", "*")
self.end_headers()
def do_GET(self):
if self.path == "/health":
healthy = sum(1 for p in POOL if p.get("ok", True))
self._send(200, json.dumps({"status": "up", "pool": len(POOL), "healthy": healthy}))
elif self.path == "/pool":
with LOCK:
self._send(200, json.dumps([{"email": p.get("email"), "ok": p.get("ok", True), "fails": p.get("fails", 0)} for p in POOL]))
elif self.path in ("/v1/models", "/models"):
e = next_token()
if not e:
return self._send(503, json.dumps({"error": "empty pool"}))
code, body = curl_json(BASE + "/models", {"Authorization": "Bearer " + e["token"]})
mark(e, code == 200)
self._send(code or 502, body)
else:
self._send(404, json.dumps({"error": "not found"}))
def do_POST(self):
if self.path not in ("/v1/chat/completions", "/chat/completions"):
return self._send(404, json.dumps({"error": "not found"}))
n = int(self.headers.get("Content-Length", 0))
try:
data = json.loads(self.rfile.read(n) or b"{}")
except Exception:
return self._send(400, json.dumps({"error": "bad json"}))
stream = bool(data.get("stream"))
model = data.get("model", "")
# retry across pool + backoff on 429/502/503
attempts = min(len(POOL) * 2, 8) or 4
for i in range(attempts):
e = next_token()
if not e:
return self._send(503, json.dumps({"error": "empty pool"}))
hdrs = {"Authorization": "Bea"+"rer " + e["token"], "Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/154.0.0.0 Safari/537.36"}
if stream:
proc = curl_json(BASE + "/chat/completions", hdrs, data, timeout=180, stream=True)
# peek first line to detect error
first = proc.stdout.readline()
if not first.startswith(b"data:") and not first.startswith(b":"):
# upstream plain-text/HTML error (e.g. "error code: 502")
proc.kill()
if i < attempts - 1:
time.sleep(2 + random.random() * 6)
continue
return self._send(502, json.dumps({"error": "upstream stream failed", "detail": first.decode('utf-8','ignore')[:200]}))
if first.startswith(b"data: {") and b'"error"' in first:
proc.kill()
time.sleep(3 + random.random() * 4)
continue
mark(e, True)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
try:
self.wfile.write(first)
for line in proc.stdout:
self.wfile.write(line)
self.wfile.flush()
except Exception:
proc.kill()
return
else:
code, body = curl_json(BASE + "/chat/completions", hdrs, data, timeout=180)
if code == 200:
mark(e, True)
return self._send(200, body)
if code in (401, 403):
mark(e, False) # dead token
# 429/5xx = upstream problem, token stays healthy
if code in (429, 502, 503) and i < attempts - 1:
time.sleep(2 + random.random() * 5)
continue
return self._send(code or 502, body)
self._send(502, json.dumps({"error": "all attempts failed", "model": model}))
if __name__ == "__main__":
from http.server import ThreadingHTTPServer
srv = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
print(f"haze-proxy on :{PORT}, pool={len(POOL)}", flush=True)
srv.serve_forever()
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
# __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 ---
# Haze mass registration: working_mails.txt -> bootstrap -> IMAP OTP -> verify -> token
# Appends live tokens to tokens.json (proxy pool) and accounts.jsonl (bank)
import json, subprocess, imaplib, email, re, time, email.utils, os, random, sys
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
DIR = os.path.dirname(os.path.abspath(__file__))
API = "https://usehaze.ai/api"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36"
MAILS = str(_d("Desktop/avtoreg/working_mails.txt","MAIL_POOL"))
PW = os.environ["HAZE_PW"]
STATE_F = os.path.join(DIR, "reg_state.json")
BANK_F = os.path.join(DIR, "accounts.jsonl")
POOL_F = os.path.join(DIR, "tokens.json")
LOCK = threading.Lock()
state = json.load(open(STATE_F, encoding="utf-8")) if os.path.exists(STATE_F) else {"used": [], "stats": {}}
USED = set(state["used"])
def save_state():
with LOCK:
state["used"] = list(USED)
json.dump(state, open(STATE_F, "w", encoding="utf-8"))
def curl_post(path, payload, timeout=60):
r = subprocess.run(["curl", "-s", "-X", "POST", API + path,
"-H", "Content-Type: application/json",
"-H", "User-Agent: " + UA,
"-d", json.dumps(payload),
"-w", "\n%{http_code}"],
capture_output=True, text=True, timeout=timeout)
body, _, code = r.stdout.rpartition("\n")
try: return int(code), json.loads(body)
except Exception: return int(code or 0), {"raw": body[:200]}
def get_otp(mail, mpass, start, tries=12):
for t in range(tries):
time.sleep(5 + random.random() * 3)
try:
m = imaplib.IMAP4_SSL("secureimap.t-online.de", 993, timeout=30)
m.login(mail, mpass); m.select("INBOX")
typ, data = m.search(None, '(FROM "welcome@workos.dev")')
ids = data[0].split()
otp = None
for i in reversed(ids[-3:]):
typ, d = m.fetch(i, "(RFC822)")
raw = d[0][1].decode("utf-8", "ignore")
msg = email.message_from_string(raw)
try:
dt = email.utils.parsedate_to_datetime(msg["Date"]).timestamp()
except Exception:
continue
if dt < start - 30: continue
body = ""
for p in msg.walk():
if p.get_content_type() == "text/plain":
body = p.get_payload(decode=True).decode("utf-8", "ignore"); break
codes = re.findall(r"\b(\d{6})\b", body)
if codes: otp = codes[0]; break
m.logout()
if otp: return otp
except Exception:
pass
return None
def add_token(tok, mail):
with LOCK:
pool = json.load(open(POOL_F, encoding="utf-8")) if os.path.exists(POOL_F) else []
if not any(p["token"] == tok for p in pool):
pool.append({"token": tok, "email": mail, "ok": True, "fails": 0})
json.dump(pool, open(POOL_F, "w", encoding="utf-8"), indent=1)
with open(BANK_F, "a", encoding="utf-8") as f:
f.write(json.dumps({"email": mail, "plan": "free", "ts": int(time.time())}) + "\n")
def reg_one(mail, mpass):
start = time.time()
c, res = 0, {}
for attempt in range(4):
try:
c, res = curl_post("/auth/bootstrap", {"email": mail, "password": PW, "create": True})
except Exception as e:
return mail, "bootstrap_exc:" + str(e)[:60]
if c == 429:
wait = 30 * (attempt + 1) + random.random() * 20
time.sleep(wait)
continue
break
if c == 429:
return mail, "rate_limited_final"
if c == 401:
return mail, "exists_other_pw" # registered elsewhere, unusable
if c == 200 and res.get("status") == "authenticated" and "accessToken" in res:
add_token(res["accessToken"], mail)
return mail, "OK:existing"
if c != 200 or "pendingToken" not in res:
return mail, f"boot:{c}:{json.dumps(res)[:80]}"
otp = get_otp(mail, mpass, start)
if not otp:
return mail, "no_otp"
try:
c2, res2 = curl_post("/auth/verify-code", {"code": otp, "pending_authentication_token": res["pendingToken"]})
except Exception as e:
return mail, "verify_exc:" + str(e)[:60]
if "accessToken" in res2:
add_token(res2["accessToken"], mail)
return mail, "OK:" + str(res2.get("profile", {}).get("plan"))
return mail, f"verify:{c2}:{json.dumps(res2)[:80]}"
def load_mails(limit):
out = []
for ln in open(MAILS, encoding="utf-8", errors="ignore"):
ln = ln.strip()
if not ln or ln.startswith("#") or ":" not in ln: continue
mail, _, mpass = ln.partition(":")
if "-" in mail.split("@")[0]: continue # dash aliases dead for delivery
if mail in USED: continue
out.append((mail, mpass))
if len(out) >= limit: break
return out
def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 30
workers = int(sys.argv[2]) if len(sys.argv) > 2 else 4
mails = load_mails(n)
print(f"mass reg: {len(mails)} mails, {workers} workers", flush=True)
stats = {"ok": 0, "fail": 0}
with ThreadPoolExecutor(max_workers=workers) as ex:
futs = {}
for m, p in mails:
futs[ex.submit(reg_one, m, p)] = m
time.sleep(4 + random.random() * 4)
for f in as_completed(futs):
mail, res = f.result()
USED.add(mail)
if res.startswith("OK"):
stats["ok"] += 1
print(f"[OK {stats['ok']}] {mail} -> {res}", flush=True)
else:
stats["fail"] += 1
print(f"[FAIL] {mail} -> {res}", flush=True)
save_state()
print(f"DONE ok={stats['ok']} fail={stats['fail']}", flush=True)
if __name__ == "__main__":
main()
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Haze (usehaze.ai) autoreg: bootstrap -> IMAP code -> verify-code -> token saved.
Usage: python reg_one.py <email> <password>
Saves token to token.txt, profile JSON to profile.json. No secrets printed.
"""
import json, sys, time, imaplib, email, re, subprocess
API = "https://usehaze.ai/api"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
def curl_post(path, payload):
r = subprocess.run([
"curl", "-s", "-X", "POST", API + path,
"-H", "Content-Type: application/json", "-H", "User-Agent: " + UA,
"-d", json.dumps(payload), "-w", "\n%{http_code}",
], capture_output=True, text=True, timeout=60)
body, _, code = r.stdout.rpartition("\n")
try:
return int(code), json.loads(body)
except Exception:
return int(code or 0), {"raw": body[:300]}
def get_otp(email_addr, email_pass, imap_host="secureimap.t-online.de", tries=12, delay=5):
for t in range(tries):
try:
m = imaplib.IMAP4_SSL(imap_host, 993, timeout=30)
m.login(email_addr, email_pass)
m.select("INBOX")
typ, data = m.search(None, '(FROM "welcome@workos.dev")')
ids = data[0].split()
if ids:
typ, d = m.fetch(ids[-1], "(RFC822)")
raw = d[0][1].decode("utf-8", "ignore")
msg = email.message_from_string(raw)
body = ""
if msg.is_multipart():
for p in msg.walk():
if p.get_content_type() == "text/plain":
body = p.get_payload(decode=True).decode("utf-8", "ignore")
break
else:
body = msg.get_payload(decode=True).decode("utf-8", "ignore")
codes = re.findall(r"\b(\d{6})\b", body)
m.logout()
if codes:
return codes[-1]
m.logout()
except Exception as e:
print(f" imap try {t}: {e}")
time.sleep(delay)
return None
def main():
mail, password = sys.argv[1], sys.argv[2]
print(f"[1] bootstrap create {mail}")
code, res = curl_post("/auth/bootstrap", {"email": mail, "password": password, "create": True})
print(f" -> {code} keys={list(res.keys())}")
if code != 200:
print("FAIL bootstrap:", json.dumps(res)[:300])
return 1
if "accessToken" in res:
tok = res["accessToken"]
open("token.txt", "w").write(tok)
json.dump(res.get("profile", {}), open("profile.json", "w"), indent=1)
print(" direct session, plan:", res.get("profile", {}).get("plan"))
return 0
if res.get("status") != "verification_required":
print("UNEXPECTED:", json.dumps(res)[:300])
return 1
pending = res["pendingToken"]
print(f"[2] waiting for OTP on IMAP ...")
otp = get_otp(mail, MAIL_PASS)
if not otp:
print("FAIL: no OTP")
return 2
print(f"[3] verify-code (otp len {len(otp)})")
code, res = curl_post("/auth/verify-code", {"code": otp, "pending_authentication_token": pending})
print(f" -> {code}")
if "accessToken" not in res:
print("FAIL verify:", json.dumps(res)[:300])
return 3
open("token.txt", "w").write(res["accessToken"])
open("refresh.txt", "w").write(res.get("refreshToken", ""))
prof = res.get("profile", {})
json.dump(prof, open("profile.json", "w"), indent=1)
print(f"OK token saved ({len(res['accessToken'])} chars). plan={prof.get('plan')} handle={prof.get('handle')}")
return 0
if __name__ == "__main__":
MAIL_PASS = sys.argv[3]
sys.exit(main())
+2
View File
@@ -0,0 +1,2 @@
brotli
websockets