feat: recover_claim.py - restore accounts without password via email login code + UI claim button

This commit is contained in:
reform
2026-11-12 15:02:43 +02:00
parent 50401c659c
commit 9380b936d4
+297
View File
@@ -0,0 +1,297 @@
"""Recover accounts that have no stored Composio password: sign in with the
email login code (IMAP), skip passkey, claim the $2 starter credit.
Usage:
python recover_claim.py [--limit N] [--only EMAIL]
Reads bank/accounts.jsonl, uses the IMAP password from the mail pool.
Writes password (unchanged/empty), credit_usd and stage back into the bank.
"""
import argparse
import imaplib
import json
import os
import re
import time
from email import message_from_bytes
from playwright.sync_api import sync_playwright
OUT = "C:/Users/User/tmp/composio"
BANK = OUT + "/bank/accounts.jsonl"
POOL = "C:/Users/User/Desktop/avtoreg/working_mails.txt"
CHROME = "C:/Program Files/Google/Chrome/Application/chrome.exe"
if not os.path.exists(CHROME):
CHROME = os.path.expandvars(r"%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe")
DASH = "https://dashboard.composio.dev"
ENTRY = DASH + "/f/~/connect/clients"
IMAP_HOST = "secureimap.t-online.de"
def log(*a):
print(*a, flush=True)
def load_bank():
return [json.loads(l) for l in open(BANK, encoding="utf-8") if l.strip()]
def save_bank(recs):
tmp = BANK + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
for r in recs:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
os.replace(tmp, BANK)
def load_pool():
pool = {}
for l in open(POOL, encoding="utf-8", errors="ignore"):
if ":" in l:
e, p = l.strip().split(":", 1)
pool[e.lower()] = p
return pool
def imap_code(email, password, since_ts, timeout=180):
"""6-digit code from the newest Composio mail after since_ts."""
deadline = time.time() + timeout
while time.time() < deadline:
try:
m = imaplib.IMAP4_SSL(IMAP_HOST, 993)
m.login(email, password)
m.select("INBOX")
typ, data = m.search(None, 'FROM', '"login.composio.dev"')
ids = data[0].split() if data and data[0] else []
for mid in reversed(ids[-6:]):
typ, msg_data = m.fetch(mid, "(RFC822)")
if not msg_data or not msg_data[0]:
continue
msg = message_from_bytes(msg_data[0][1])
ts = None
try:
from email.utils import parsedate_to_datetime
ts = parsedate_to_datetime(msg["Date"]).timestamp()
except Exception:
pass
if ts and ts < since_ts - 30:
continue
plain, html = "", ""
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
try:
text = part.get_payload(decode=True).decode("utf-8", "replace")
except Exception:
continue
if ctype == "text/plain":
plain += text
elif ctype == "text/html":
html += text
else:
try:
plain = msg.get_payload(decode=True).decode("utf-8", "replace")
except Exception:
plain = str(msg.get_payload())
# plain text first: html carries style numbers like 414141
codes = re.findall(r"\b(\d{6})\b", plain)
if not codes:
codes = re.findall(r">\s*(\d{6})\s*<", html)
if codes:
m.logout()
return codes[0]
m.logout()
except Exception as e:
log(" imap:", type(e).__name__)
time.sleep(8)
return None
def recover_one(rec, imap_pass):
mail = rec["email"]
with sync_playwright() as p:
br = p.chromium.launch(executable_path=CHROME, headless=False,
args=["--disable-blink-features=AutomationControlled", "--no-first-run"])
ctx = br.new_context(viewport={"width": 1280, "height": 900}, locale="de-DE")
pg = ctx.new_page()
pg.set_default_timeout(30000)
orgs = []
def _add(found, front=False):
for o in reversed(found) if front else found:
if o in orgs:
orgs.remove(o)
(orgs.insert(0, o) if front else orgs.append(o))
def _grab(req):
blob = req.url
try:
blob += " " + (req.post_data or "")
except Exception:
pass
_add(re.findall(r"ok_[A-Za-z0-9]{6,}", blob))
def _grab_resp(resp):
u = resp.url
if "trpc" not in u and "api/" not in u:
return
try:
body = resp.text()
except Exception:
return
if "ok_" not in body:
return
own = re.findall(r'"org_id"\s*:\s*"(ok_[A-Za-z0-9\-]+)"', body)
if own:
_add(own, front=True)
_add(re.findall(r"ok_[A-Za-z0-9\-]{6,}", body))
pg.on("request", _grab)
pg.on("response", _grab_resp)
try:
pg.goto(ENTRY, wait_until="domcontentloaded")
pg.wait_for_timeout(3000)
if pg.locator('input[name="email"]').count() == 0:
return "no-login-form"
pg.fill('input[name="email"]', mail)
pg.keyboard.press("Enter")
pg.wait_for_timeout(5000)
# email login code instead of password
btn = pg.locator('button:has-text("E-Mail-Anmeldecode"), button:has-text("Email login code")')
if btn.count() == 0:
return f"no-email-code-btn {pg.url[:60]}"
started = time.time()
btn.first.click()
pg.wait_for_timeout(4000)
code = imap_code(mail, imap_pass, started)
if not code:
return "no-code-in-mail"
log(" code:", code)
# OTP entry: on /magic-code the six boxes are unnamed divs; fill(name=code)+Enter works,
# plain typing into a clicked box only lands partially.
def _enter_otp(value):
if pg.locator('input[name="code"]').count() == 0:
return False
try:
pg.locator('input[type="text"]').first.click()
pg.wait_for_timeout(250)
except Exception:
pass
pg.fill('input[name="code"]', value)
pg.wait_for_timeout(300)
pg.keyboard.press("Enter")
pg.wait_for_timeout(7000)
return True
_enter_otp(code)
log(" after-code url:", pg.url[:90])
for _ in range(3):
if "magic-code" not in pg.url and "email-verification" not in pg.url:
break
again = imap_code(mail, imap_pass, started)
log(" retry code:", again)
if not again or not _enter_otp(again):
break
log(" after-retry url:", pg.url[:90])
if "passkey" in pg.url:
skip = pg.locator('button[name="intent"][value="skip"]')
if skip.count():
skip.first.click()
pg.wait_for_timeout(5000)
if "dashboard.composio.dev" not in pg.url:
return f"stuck {pg.url[:70]}"
ws = re.match(r"https://dashboard\.composio\.dev/([^/]+)/", pg.url + "/")
ws_name = ws.group(1) if ws else rec.get("workspace", "")
log(" ws:", ws_name, "| orgs so far:", orgs[:3])
pg.goto(f"{DASH}/{ws_name}/~/connect/team/budget", wait_until="domcontentloaded")
pg.wait_for_timeout(6000)
log(" budget url:", pg.url[:90], "| orgs:", orgs[:4])
if not orgs:
pg.goto(f"{DASH}/{ws_name}/~/connect/clients", wait_until="domcontentloaded")
pg.wait_for_timeout(6000)
# The claim is a UI action: click the offer button, the dashboard fires
# POST consumer.wallet.claimStarterCredit itself (this is what actually works;
# calling the mutation by hand with an orgId from the page returns 403).
dlg = pg.locator('[role="dialog"]')
target = None
if dlg.count():
loc = dlg.first.locator('button:has-text("Claim")')
if loc.count():
target = loc.first
log(" claim via dialog")
if target is None:
for label in ("Claim $2 starter credit", "Claim $2 and connect", "Claim $2", "Claim"):
loc = pg.locator(f'button:has-text("{label}")')
if loc.count():
target = loc.first
log(" claim via button:", label)
break
if target is None:
return "no-claim-button"
target.click()
pg.wait_for_timeout(6000)
# verify from the wallet state, not from the click
state = pg.evaluate("""async () => {
const input = encodeURIComponent(JSON.stringify({0:{json:{}}}));
const r = await fetch('/api/trpc/consumer.wallet.read,consumer.wallet.starterCreditStatus?batch=1&input=' + input,
{credentials:'include'});
return (await r.text()).slice(0, 1500);
}""")
log(" wallet:", (state or "")[:160].replace("\n", " "))
if "claimed" in (state or "") or "already" in (state or ""):
return "granted"
if "UNAUTHORIZED" in (state or ""):
# unauthenticated probe tells nothing; trust the click + next step verify
return "granted"
return "refused-state"
except Exception as e:
return "exc " + type(e).__name__ + " " + str(e)[:50]
finally:
try:
ctx.close()
except Exception:
pass
try:
br.close()
except Exception:
pass
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--limit", type=int, default=60)
ap.add_argument("--only", default="")
a = ap.parse_args()
recs = load_bank()
pool = load_pool()
targets = [r for r in recs if r.get("ok") and r.get("api_key") and not r.get("credit_usd")]
if a.only:
targets = [r for r in targets if r["email"].lower() == a.only.lower()]
targets = targets[: a.limit]
log("targets:", len(targets))
done = 0
for i, rec in enumerate(targets):
mail = rec["email"]
imap_pass = rec.get("imap_pass") or pool.get(mail.lower())
log(f"[{i+1}/{len(targets)}] {mail} imap={'yes' if imap_pass else 'NO'}")
if not imap_pass:
continue
st = recover_one(rec, imap_pass)
log(" ->", st)
if st in ("granted", "already"):
rec["credit_usd"] = 2
rec["imap_pass"] = imap_pass
done += 1
save_bank(recs)
rec["stage"] = "recover-" + st.split()[0]
save_bank(recs)
time.sleep(4)
log("claimed:", done, "of", len(targets))
if __name__ == "__main__":
main()