context.dev autoreg: agent claim flow, chrome CDP signup, bank shim
This commit is contained in:
Executable
+351
@@ -0,0 +1,351 @@
|
||||
#!/usr/bin/env python
|
||||
"""Context.dev farm v2: robust chrome lifecycle + tRPC redeem + email verify retries.
|
||||
|
||||
Usage: ctx_farm2.py <start_idx> <count>
|
||||
"""
|
||||
import json, os, sys, time, re, random, string, subprocess, imaplib, email
|
||||
import requests
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = os.path.dirname(os.path.abspath(__file__))
|
||||
START, COUNT = int(sys.argv[1]), int(sys.argv[2])
|
||||
PROMO = "SPOOKY10K"
|
||||
CDP = os.environ.get("CTX_CDP", "http://127.0.0.1:9223")
|
||||
PROXY_URL = os.environ.get("CTX_PROXY", "")
|
||||
PXY = {"http": PROXY_URL, "https": PROXY_URL} if PROXY_URL else None
|
||||
ID_PROXIES = [p for p in os.environ.get("CTX_ID_PROXIES", "").split(",") if p.strip()]
|
||||
|
||||
|
||||
def id_pxy():
|
||||
"""identity runs on a rotating pool (datacenter IPv6 is fine - no captcha there)."""
|
||||
if ID_PROXIES:
|
||||
p = random.choice(ID_PROXIES).strip()
|
||||
return {"http": p, "https": p}
|
||||
return PXY
|
||||
NAMES = ["Nikita Refor", "Alex Grobman", "Dan Vorobets", "Max Koval", "Yuri Larin", "Oleg Sydor", "Kirill Bolt"]
|
||||
G = json.load(open(r"gmail_env.json"))
|
||||
|
||||
|
||||
def log(*a):
|
||||
print(*a, flush=True)
|
||||
|
||||
|
||||
def cdp_ok():
|
||||
try:
|
||||
return requests.get(CDP + "/json/version", timeout=3).status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def ensure_chrome():
|
||||
if cdp_ok():
|
||||
return True
|
||||
subprocess.run([sys.executable, os.path.join(BASE, "chrome_up.py")], check=False)
|
||||
for _ in range(20):
|
||||
if cdp_ok():
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def identity(mail, tag):
|
||||
r = requests.post("https://www.context.dev/agent/identity", json={
|
||||
"type": "service_auth", "login_hint": mail,
|
||||
"api_key_name": "hermes-%s" % tag, "client_name": "Hermes"}, timeout=60, proxies=id_pxy())
|
||||
try:
|
||||
return r.status_code, r.json()
|
||||
except Exception:
|
||||
return r.status_code, {}
|
||||
|
||||
|
||||
def txt(pg, n=260):
|
||||
try:
|
||||
return re.sub(r"\s+", " ", pg.inner_text("body"))[:n]
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def click_btn(pg, rx, exact_first=True):
|
||||
js = """(() => {const bs=[...document.querySelectorAll('button')];
|
||||
let x=bs.find(e=>new RegExp(%s,'i').test(e.innerText||''));
|
||||
if(!x) return null; const r=x.getBoundingClientRect();
|
||||
return JSON.stringify({x:r.x+r.width/2,y:r.y+r.height/2,t:(x.innerText||'').trim()})})()""" % json.dumps(rx)
|
||||
b = pg.evaluate(js)
|
||||
if not b:
|
||||
return False
|
||||
c = json.loads(b)
|
||||
try:
|
||||
pg.mouse.move(c["x"], c["y"], steps=8); time.sleep(0.2)
|
||||
pg.mouse.click(c["x"], c["y"])
|
||||
except Exception:
|
||||
pg.evaluate("""(() => {const bs=[...document.querySelectorAll('button')];
|
||||
const x=bs.find(e=>new RegExp(%s,'i').test(e.innerText||'')); if(x)x.click();})()""" % json.dumps(rx))
|
||||
return True
|
||||
|
||||
|
||||
def go(pg, url, **kw):
|
||||
"""goto with retries - the mobile egress drops TLS now and then."""
|
||||
kw.setdefault("timeout", 90000)
|
||||
kw.setdefault("wait_until", "domcontentloaded")
|
||||
last = None
|
||||
for i in range(4):
|
||||
try:
|
||||
return pg.goto(url, **kw)
|
||||
except Exception as e:
|
||||
last = e
|
||||
log(" goto retry %d: %s" % (i + 1, str(e)[:70]))
|
||||
time.sleep(5)
|
||||
if pg.is_closed():
|
||||
raise
|
||||
raise last
|
||||
|
||||
|
||||
def find_code_input(pg):
|
||||
return pg.evaluate("""(() => {const els=[...document.querySelectorAll('input')].filter(e=>e.offsetWidth||e.offsetHeight);
|
||||
let c=els.find(e=>/code|otp|verif/i.test((e.id||'')+(e.name||'')+(e.placeholder||'')+(e.getAttribute('aria-label')||'')));
|
||||
if(!c && els.length===1 && els[0].maxLength>3 && els[0].maxLength<=8) c=els[0];
|
||||
if(!c) return null; c.focus(); return c.id||'x'})()""")
|
||||
|
||||
|
||||
def clear_session(pg):
|
||||
# keep Google/reCAPTCHA cookies (they carry trust score), drop only app session
|
||||
try:
|
||||
for c in pg.context.cookies():
|
||||
if str(c.get("name", "")).startswith("BrandDev"):
|
||||
pg.context.clear_cookies(name=c["name"])
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pg.evaluate("""async ()=>{try{localStorage.clear();sessionStorage.clear()}catch(e){}
|
||||
try{const dbs=await indexedDB.databases();for(const d of dbs){if(/firebase/i.test(d.name||'')){try{indexedDB.deleteDatabase(d.name)}catch(e){}}}}catch(e){}}""")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def get_verify_link(alias, timeout=200, not_before=0):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
try:
|
||||
m = imaplib.IMAP4_SSL("imap.gmail.com")
|
||||
m.login(G["gm"], G["gp"].strip())
|
||||
m.select("INBOX")
|
||||
typ, data = m.search(None, "ALL")
|
||||
for i in reversed(data[0].split()[-15:]):
|
||||
typ, d = m.fetch(i, "(RFC822)")
|
||||
msg = email.message_from_bytes(d[0][1])
|
||||
if alias.lower() not in msg.get("To", "").lower():
|
||||
continue
|
||||
subj = str(email.header.make_header(email.header.decode_header(msg.get("Subject", ""))))
|
||||
if "Verify your email" not in subj:
|
||||
continue
|
||||
body = ""
|
||||
for part in msg.walk():
|
||||
if part.get_content_type() in ("text/plain", "text/html"):
|
||||
try:
|
||||
body += part.get_payload(decode=True).decode(part.get_content_charset() or "utf-8", "replace")
|
||||
except Exception:
|
||||
pass
|
||||
ls = re.findall(r"https://www\.context\.dev/verify-email\?[^\s\"'<>]+", body)
|
||||
if ls:
|
||||
m.logout()
|
||||
return ls[0].replace("&", "&")
|
||||
m.logout()
|
||||
except Exception as e:
|
||||
log(" imap:", str(e)[:70])
|
||||
time.sleep(10)
|
||||
return ""
|
||||
|
||||
|
||||
def api_credits(key):
|
||||
try:
|
||||
r = requests.get("https://api.context.dev/v1/org/logs",
|
||||
headers={"Authorization": "Bearer " + key}, timeout=60)
|
||||
return r.json().get("key_metadata", {}).get("credits_remaining")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def redeem_trpc(pg, promo, org_hint=None):
|
||||
"""Redeem via tRPC (needs organization_id + code)."""
|
||||
js = """async ([code, org]) => {
|
||||
if (!org) {
|
||||
try {
|
||||
const r0 = await fetch('/api/trpc/organization.get?batch=1&input=' + encodeURIComponent(JSON.stringify({"0":{"json":null}})));
|
||||
const t0 = await r0.text();
|
||||
const m = t0.match(/"id"\\s*:\\s*"([0-9a-f-]{36})"/);
|
||||
if (m) org = m[1];
|
||||
} catch(e) {}
|
||||
}
|
||||
const body = {"0":{"json":{"code":code,"organization_id":org}}};
|
||||
const r = await fetch('/api/trpc/organization.redeemCreditPackage?batch=1', {
|
||||
method:'POST', headers:{'content-type':'application/json'}, body: JSON.stringify(body)});
|
||||
const t = await r.text();
|
||||
return JSON.stringify({org:org, status:r.status, body:t.slice(0,400)});
|
||||
}"""
|
||||
try:
|
||||
out = pg.evaluate(js, [promo, org_hint])
|
||||
log(" redeem api:", str(out)[:280])
|
||||
if '"credits_added"' in str(out):
|
||||
return True
|
||||
except Exception as e:
|
||||
log(" redeem err:", str(e)[:100])
|
||||
return False
|
||||
|
||||
|
||||
def run_one(pg, mail, tag):
|
||||
code, ident = identity(mail, tag)
|
||||
log("[%s] identity %s" % (tag, code))
|
||||
if code != 200 or "claim" not in ident:
|
||||
log(" fail:", json.dumps(ident)[:200])
|
||||
return None
|
||||
vuri, ucode, ct = ident["claim"]["verification_uri"], ident["claim"]["user_code"], ident["claim_token"]
|
||||
pw = "Kq7" + "".join(random.choice(string.ascii_letters + string.digits) for _ in range(9)) + "!2"
|
||||
json.dump({"email": mail, "tag": tag, "pw": pw, "claim_token": ct, "vuri": vuri, "user_code": ucode,
|
||||
"offer": ident.get("offer"), "created": time.time()},
|
||||
open(os.path.join(BASE, "acct_%s.json" % tag), "w"), indent=1)
|
||||
log(" VURI", vuri)
|
||||
log(" CODE", ucode)
|
||||
|
||||
go(pg, "https://www.context.dev/claim", wait_until="domcontentloaded", timeout=90000)
|
||||
time.sleep(3)
|
||||
clear_session(pg)
|
||||
go(pg, vuri, wait_until="domcontentloaded", timeout=90000)
|
||||
time.sleep(7)
|
||||
t = txt(pg, 200)
|
||||
log(" page:", t[:100])
|
||||
if "We use cookies" in t or "cookie" in t[:90].lower():
|
||||
for rx in (r"^accept", r"^reject", r"^continue", r"^got it", r"^allow", r"^ok"):
|
||||
if click_btn(pg, rx):
|
||||
log(" consent:", rx)
|
||||
break
|
||||
time.sleep(3)
|
||||
t = txt(pg, 220)
|
||||
log(" page2:", t[:90])
|
||||
|
||||
if "Full name" in t or "Create account" in t:
|
||||
need = pg.evaluate("""(() => {const e=document.querySelector('input[name=username]')||document.querySelector('input[type=email]');
|
||||
if(!e) return 'none'; if(e.value && e.value.trim()) return 'ok'; e.readOnly=false; e.focus(); return 'need'})()""")
|
||||
if need == "need":
|
||||
pg.keyboard.type(mail, delay=45); time.sleep(0.7)
|
||||
pg.evaluate("""(() => {const e=document.querySelector('input[name=username]')||document.querySelector('input[type=email]');
|
||||
if(e && e.value !== %s){const s=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set; s.call(e,%s); e.dispatchEvent(new Event('input',{bubbles:true}))}})()""" % (json.dumps(mail), json.dumps(mail)))
|
||||
log(" email field:", need)
|
||||
pg.focus("#name"); pg.keyboard.type(random.choice(NAMES), delay=55)
|
||||
pg.focus("#password"); pg.keyboard.type(pw, delay=55)
|
||||
pg.evaluate("(()=>{const c=document.querySelector('input[type=checkbox]'); if(!c.checked)c.click()})()")
|
||||
time.sleep(4)
|
||||
if not click_btn(pg, r"^create account"):
|
||||
log(" no signup button")
|
||||
return None
|
||||
for _ in range(35):
|
||||
time.sleep(4)
|
||||
t = txt(pg, 220)
|
||||
if "Confirm agent setup" in t or "Setup code" in t:
|
||||
break
|
||||
if "couldn't verify" in t or "Security check failed" in t:
|
||||
log(" recaptcha rejected")
|
||||
return None
|
||||
if "Confirm agent setup" not in t and "Setup code" not in t:
|
||||
log(" no code screen:", t[:130])
|
||||
return None
|
||||
elif "Confirm agent setup" not in t:
|
||||
log(" unexpected page")
|
||||
return None
|
||||
|
||||
if find_code_input(pg):
|
||||
pg.keyboard.type(ucode, delay=90); time.sleep(1)
|
||||
click_btn(pg, r"confirm setup|^confirm$|continue")
|
||||
time.sleep(7)
|
||||
log(" after code:", txt(pg, 130)[:110])
|
||||
|
||||
# verify email
|
||||
if "Check your inbox" in txt(pg, 260) or "verification link" in txt(pg, 260):
|
||||
link = get_verify_link(mail)
|
||||
if not link:
|
||||
log(" NO link")
|
||||
return None
|
||||
go(pg, link, wait_until="domcontentloaded", timeout=90000); time.sleep(5)
|
||||
click_btn(pg, r"verify email address|verify email")
|
||||
time.sleep(9)
|
||||
go(pg, vuri, wait_until="domcontentloaded", timeout=90000); time.sleep(5)
|
||||
t = txt(pg, 220)
|
||||
if "I've verified my email" in t:
|
||||
click_btn(pg, r"verified my email"); time.sleep(8)
|
||||
elif find_code_input(pg):
|
||||
pg.keyboard.type(ucode, delay=90); time.sleep(1)
|
||||
click_btn(pg, r"confirm setup|^confirm$|continue"); time.sleep(7)
|
||||
log(" post-verify:", txt(pg, 140)[:110])
|
||||
|
||||
# redeem
|
||||
org = None
|
||||
m = re.search(r"/o/([0-9a-f-]{36})", pg.url)
|
||||
if m:
|
||||
org = m.group(1)
|
||||
go(pg, "https://www.context.dev/dashboard/redeem-credits", wait_until="domcontentloaded", timeout=60000)
|
||||
time.sleep(6)
|
||||
if "Check your inbox" in txt(pg, 300):
|
||||
log(" redeem blocked: email not verified")
|
||||
else:
|
||||
redeem_trpc(pg, PROMO, org)
|
||||
time.sleep(3)
|
||||
|
||||
r = requests.post("https://www.context.dev/oauth2/token",
|
||||
data={"grant_type": "urn:workos:agent-auth:grant-type:claim", "claim_token": ct}, timeout=60, proxies=PXY)
|
||||
d = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
|
||||
if "access_token" not in d:
|
||||
log(" TOKEN FAIL", r.status_code, json.dumps(d)[:150])
|
||||
return None
|
||||
key = d["access_token"]
|
||||
cr = api_credits(key)
|
||||
entry = {"email": mail, "tag": tag, "key": key, "ts": time.time(),
|
||||
"gift": d.get("signup_gift_credits"), "credits": cr}
|
||||
with open(os.path.join(BASE, os.environ.get("CTX_BANK", "bank.jsonl")), "a") as f:
|
||||
f.write(json.dumps(entry) + "\n")
|
||||
log(" KEY OK len %d gift=%s credits=%s" % (len(key), d.get("signup_gift_credits"), cr))
|
||||
return entry
|
||||
|
||||
|
||||
def main():
|
||||
ok = 0
|
||||
for idx in range(START, START + COUNT):
|
||||
mail, tag = "baradok609+ctx%d@gmail.com" % idx, "ctx%d" % idx
|
||||
log("\n=== %s ===" % mail)
|
||||
if not ensure_chrome():
|
||||
log(" chrome down"); continue
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
br = p.chromium.connect_over_cdp(CDP)
|
||||
ctx = br.contexts[0]
|
||||
pg = ctx.new_page()
|
||||
e = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
if pg.is_closed():
|
||||
pg = ctx.new_page()
|
||||
e = run_one(pg, mail, tag)
|
||||
except Exception as ex:
|
||||
log(" exc:", str(ex)[:120])
|
||||
e = None
|
||||
try:
|
||||
pg = ctx.new_page()
|
||||
except Exception:
|
||||
pass
|
||||
if e:
|
||||
break
|
||||
log(" retry %d/3 in 25s" % (attempt + 1))
|
||||
time.sleep(25)
|
||||
log("RESULT", "OK" if e else "FAIL")
|
||||
if e:
|
||||
ok += 1
|
||||
try:
|
||||
pg.close()
|
||||
except Exception:
|
||||
pass
|
||||
br.close()
|
||||
except Exception as ex:
|
||||
print("EXC", str(ex)[:200], flush=True)
|
||||
time.sleep(int(os.environ.get("CTX_PAUSE", "6")))
|
||||
log("\nTOTAL OK %d / %d" % (ok, COUNT))
|
||||
|
||||
|
||||
main()
|
||||
Reference in New Issue
Block a user