"""QwenWork autoreg / login over plain HTTP (no browser). Flow: 1. Aliyun Captcha v3 solved via 2captcha (AlibabaTaskProxyless) -> captcha_token JSON string 2. POST /auth/email-codes {email, purpose, captcha_token} 3. read 6-digit code from the mailbox (IMAP) 4. POST /auth/local/register {email, code, notification:false} (or /auth/local/login) 5. JWT arrives as cookie `token` Usage: python farm.py user+1@gmail.com --register python farm.py user+1@gmail.com --login Env: QW_2CAP path to file with 2captcha key (default ~/.2cap_key) QW_OUT path to accounts jsonl (default ./accounts.jsonl) QW_GMAIL mailbox login QW_GMAIL_PASS mailbox app password QW_IMAP_HOST default imap.gmail.com QW_BASE default https://qwenwork.ai """ import json import os import re import sys import time import imaplib import email as emaillib import email.utils import http.cookiejar import urllib.request import urllib.error BASE = os.environ.get("QW_BASE", "https://qwenwork.ai") KEY_FILE = os.environ.get("QW_2CAP", os.path.expanduser("~/.2cap_key")) OUT = os.environ.get("QW_OUT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "accounts.jsonl")) USED = os.path.join(os.path.dirname(os.path.abspath(__file__)), "used_codes.txt") GMAIL_USER = os.environ.get("QW_GMAIL", "") GMAIL_APP = os.environ.get("QW_GMAIL_PASS", "") IMAP_HOST = os.environ.get("QW_IMAP_HOST", "imap.gmail.com") UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36") SCENE, PREFIX, REGION = "l47rwlyt", "13n1x6", "ga" CAPTCHA_LIB = "https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js?t=2035" # ---------------------------------------------------------------- captcha def solve_captcha(): key = open(KEY_FILE).read().strip() task = { "type": "AlibabaTaskProxyless", "websiteUrl": BASE + "/biz/signin", "sceneId": SCENE, "prefix": PREFIX, "region": REGION, "apiGetLib": CAPTCHA_LIB, "userAgent": UA, } req = urllib.request.Request( "https://api.2captcha.com/createTask", data=json.dumps({"clientKey": key, "task": task}).encode(), headers={"Content-Type": "application/json"}, ) with urllib.request.urlopen(req, timeout=40) as r: d = json.loads(r.read().decode()) if d.get("errorId"): raise RuntimeError("createTask: %s" % d) tid = d["taskId"] t0 = time.time() while time.time() - t0 < 300: time.sleep(5) req = urllib.request.Request( "https://api.2captcha.com/getTaskResult", data=json.dumps({"clientKey": key, "taskId": tid}).encode(), headers={"Content-Type": "application/json"}, ) with urllib.request.urlopen(req, timeout=40) as r: s = json.loads(r.read().decode()) if s.get("errorId"): raise RuntimeError("getTaskResult: %s" % s) if s.get("status") == "ready": # server expects the WHOLE solution object as a JSON *string* return json.dumps(s["solution"], ensure_ascii=False) raise RuntimeError("captcha timeout") # ---------------------------------------------------------------- mailbox def _used(): if not os.path.exists(USED): return set() return {l.strip() for l in open(USED, encoding="utf-8") if l.strip()} def _mark(code): with open(USED, "a", encoding="utf-8") as f: f.write(code + "\n") def mail_code(t_start, tries=24, delay=5): """Newest unused 6-digit code from a qwenwork mail received after t_start.""" used = _used() for _ in range(tries): time.sleep(delay) try: m = imaplib.IMAP4_SSL(IMAP_HOST, 993) except Exception: continue try: m.login(GMAIL_USER, GMAIL_APP) m.select("INBOX") typ, data = m.search(None, "SINCE", time.strftime("%d-%b-%Y")) ids = (data[0] or b"").split()[-30:] for i in reversed(ids): typ, d = m.fetch(i, "(RFC822)") if typ != "OK" or not d or not d[0]: continue msg = emaillib.message_from_bytes(d[0][1]) try: dt = email.utils.parsedate_to_datetime(msg.get("Date")) if dt.timestamp() < t_start - 60: continue except Exception: pass head = (msg.get("From", "") + " " + msg.get("Subject", "")).lower() body = "" if msg.is_multipart(): 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 else: try: body = msg.get_payload(decode=True).decode( msg.get_content_charset() or "utf-8", "replace") except Exception: pass if "qwenwork" not in head and "qwenwork" not in body.lower(): continue for code in re.findall(r"\b(\d{6})\b", msg.get("Subject", "") + " " + body): if code in used: continue _mark(code) return code except Exception: pass finally: try: m.logout() except Exception: pass return None # ---------------------------------------------------------------- main def main(): if len(sys.argv) < 2: print(__doc__) return addr = sys.argv[1] mode = "register" if "--register" in sys.argv else "login" cj = http.cookiejar.CookieJar() op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) def api(method, path, body=None): data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request( BASE + path, data=data, method=method, headers={ "Content-Type": "application/json", "Origin": BASE, "Referer": BASE + "/biz/signin", "User-Agent": UA, "X-Client-Source": "web", "X-Mule-Language": "en", }, ) try: with op.open(req, timeout=45) as r: return r.status, r.read().decode() except urllib.error.HTTPError as e: return e.code, e.read().decode() t_start = time.time() tok = solve_captcha() print("[1] captcha ok", len(tok), "chars", flush=True) st, body = api("POST", "/auth/email-codes", { "email": addr, "purpose": "login" if mode == "login" else "registration", "captcha_token": tok, }) print("[2] email-codes", st, body[:180], flush=True) if st != 200: return code = mail_code(t_start) if not code: print("[3] no code in mail", flush=True) return print("[3] code", code, flush=True) if mode == "register": st, body = api("POST", "/auth/local/register", {"email": addr, "code": code, "notification": False}) else: st, body = api("POST", "/auth/local/login", {"email": addr, "code": code}) print("[4]", mode, st, body[:260], flush=True) jwt = next((c.value for c in cj if c.name == "token"), None) print("[5] jwt_len", len(jwt or ""), flush=True) rec = {"email": addr, "jwt": jwt, "mode": mode, "ts": time.time()} with open(OUT, "a", encoding="utf-8") as f: f.write(json.dumps(rec, ensure_ascii=False) + "\n") if jwt: st, q = api("GET", "/user/v2/quota") print("[6] quota", st, q[:120], flush=True) st, b = api("GET", "/user/v2/registration-benefits") print("[7] benefits", st, b[:200], flush=True) if __name__ == "__main__": main()