"""Slack workspace creation, ALL-IN-ONE cloakbrowser session. Proven inline path (slack_direct.log): navigate -> fill email -> submit -> click #recaptcha-anchor inside /anchor frame -> loop: detect bframe table, solve_image_challenge (mistral/qwen3-vl vision) until #g-recaptcha-response gets a token. Token lands in the LIVE page, so Slack's Continue button fires normally (no injection). Then IMAP code from :993, workspace naming, cookie harvest. Viktor OAuth done separately in slack_viktor.py. Usage: python slack_full.py [--keep] State: slack_state.json """ import json, os, sys, time, imaplib, email as emaillib, re, asyncio, urllib.request from email import header as email_header HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.environ.get("SOLVER_PATH", ".")) # captcha-solver sidecar path import logging logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s", filename=os.path.join(HERE, "slack_full.log"), filemode="w") STATE = os.path.join(HERE, "slack_state.json") MAILS = os.environ.get("SLACK_MAILS_FILE", "mails.txt") # email:password per line MAIL_STATE = os.path.join(HERE, "slack_mail_offset.json") IMAP_HOST = os.environ.get("SLACK_IMAP_HOST", "imap.example.com") SLACK_URL = "https://app.slack.com/get-started#/createnew" def next_mail(): st = {"offset": 0} if os.path.exists(MAIL_STATE): st = json.load(open(MAIL_STATE)) lines = [l.strip() for l in open(MAILS, encoding="utf-8", errors="replace") if ":" in l and "@" in l and "total" not in l] off = st["offset"] % len(lines) email_, pw = lines[off].split(":", 1) st["offset"] = off + 1 json.dump(st, open(MAIL_STATE, "w")) return email_.strip(), pw.strip() def get_code(email_, pw, wait=180): t0 = time.time() while time.time() - t0 < wait: try: M = imaplib.IMAP4_SSL(IMAP_HOST, 993) M.login(email_, pw); M.select("INBOX") typ, data = M.search(None, "UNSEEN") for i in data[0].split()[-8:]: typ, msgd = M.fetch(i, "(RFC822)") msg = emaillib.message_from_bytes(msgd[0][1]) frm = msg.get("From", "") try: frm = str(email_header.make_header(email_header.decode_header(str(frm)))) except Exception: frm = str(frm) if "slack" not in frm.lower(): continue body = "" if msg.is_multipart(): for part in msg.walk(): if part.get_content_type() == "text/plain": body += part.get_payload(decode=True).decode(errors="replace") else: body = msg.get_payload(decode=True).decode(errors="replace") # Slack code is alphanumeric with a dash, e.g. IZV-AZB (also in subject) try: subj = str(email_header.make_header( email_header.decode_header(msg.get("Subject", "")))) except Exception: subj = str(msg.get("Subject", "")) for text in (subj + "\n" + body, body): m = re.search(r"\b([A-Z0-9]{3}-[A-Z0-9]{3})\b", text) or \ re.search(r"confirmation code[:\s]*([A-Z0-9\-]{5,9})", text) or \ re.search(r"\b(\d{6})\b", text) if m: # also grab the magic confirm link from HTML part html = "" try: M2 = None for part2 in msg.walk(): if part2.get_content_type() == "text/html": html += part2.get_payload(decode=True).decode(errors="replace") lk = re.search(r'href="(https://[^"]*(?:confirm|signin|get-started|magic)[^"]*)"', html) magic = lk.group(1).replace("&", "&") if lk else "" except Exception: magic = "" M.logout(); return m.group(1), magic M.logout() except Exception as e: print("imap err:", str(e)[:60], flush=True) time.sleep(8) return None, "" async def solve_and_get_token(page, keypool, timeout_s=560): try: from recaptcha.solve import _find_frame, _bframe_has_table from recaptcha.image_solve import solve_image_challenge except ImportError as _e: raise RuntimeError( "slack_reger needs the optional 'recaptcha' vision-solver package " "(solve.py + image_solve.py). It is NOT bundled. Drop the recaptcha/ " "package next to this file (or on PYTHONPATH) to enable Slack reCAPTCHA " "solving. Original error: %s" % _e) af = await _find_frame(page, "/anchor") if af: a = af.locator("#recaptcha-anchor") if await a.count(): try: await a.click(timeout=8000); print("anchor clicked", flush=True) except Exception as e: print("anchor click err:", str(e).splitlines()[0], flush=True) async def grab_token(): # Enterprise widget may render the textarea differently; try several selectors for sel in ("#g-recaptcha-response", 'textarea[name="g-recaptcha-response"]', 'textarea[id="g-recaptcha-response"]'): try: v = await page.evaluate(f"() => document.querySelector('{sel}')?.value || ''") if v and len(v) > 100: return v except Exception: pass return "" deadline = time.monotonic() + timeout_s attempts = 0 restarts = 0 while time.monotonic() < deadline: await asyncio.sleep(2) tok = await grab_token() if tok: print("TOKEN LEN:", len(tok), flush=True) return tok if await _bframe_has_table(page) and attempts < 25: attempts += 1 try: ok = await solve_image_challenge(page, keypool) print("solve_image ok:", ok, "attempt", attempts, flush=True) except Exception as e: print("solve err:", str(e).splitlines()[0], flush=True) elif attempts >= 25: # challenge expired/escalated beyond limit -> restart the widget if restarts >= 3: print("restart limit reached", flush=True); break restarts += 1 attempts = 0 print(f"attempt limit reached -> restart {restarts}/3", flush=True) try: await page.reload(wait_until="domcontentloaded", timeout=60000) await asyncio.sleep(8) af2 = await _find_frame(page, "/anchor") if af2: a2 = af2.locator("#recaptcha-anchor") if await a2.count(): await a2.click(timeout=8000) print("anchor re-clicked", flush=True) except Exception as e: print("restart err:", str(e).splitlines()[0], flush=True) return "" async def main(): email_, pw = next_mail() print("EMAIL:", email_, flush=True) state = {"email": email_, "ts": time.time()} import cloakbrowser from recaptcha.solve import _get_keypool keypool = _get_keypool("mistral") PDIR = os.path.join(HERE, "pr_slack_full") async with await cloakbrowser.launch_async( humanize=False, headless=False) as br: page = await br.new_page() async def _on_resp(resp): u = resp.url if any(k in u for k in ("verifyCode", "confirm", "signin", "code", "check")) and "slack.com/api" in u or "get-started" in u and "api" in u: try: b = await resp.text() print(f"[NET] {resp.status} {u[:110]}\n body: {b[:300]}", flush=True) except Exception: print(f"[NET] {resp.status} {u[:110]}", flush=True) page.on("response", _on_resp) await page.goto(SLACK_URL, wait_until="domcontentloaded", timeout=60000) await asyncio.sleep(8) await page.locator("input[type=email]").first.fill(email_) await asyncio.sleep(1.5) await page.locator("button[type=submit]").first.click() await asyncio.sleep(10) print("after submit URL:", page.url, flush=True) tok = await solve_and_get_token(page, keypool) state["token_len"] = len(tok) if not tok: print("NO TOKEN — aborting", flush=True) state["stage"] = "no_token" json.dump(state, open(STATE, "w"), indent=1, default=str) return # token is in the page; click Continue to submit Slack form await asyncio.sleep(2) for sel in ["button[type=submit]", "button:has-text('Continue')", "#submit_button", "button.slack_button"]: try: b = page.locator(sel).first if await b.is_visible(timeout=2000): await b.click(timeout=5000); print("clicked", sel, flush=True); break except Exception: pass await asyncio.sleep(10) print("post-continue URL:", page.url, flush=True) print("BODY:", (await page.inner_text("body"))[:300].replace("\n"," | "), flush=True) state["stage"] = "token_submitted" await page.screenshot(path=os.path.join(HERE, "slack_full.png")) code, magic = get_code(email_, pw) print("CODE:", code, "| magic link:", (magic or "none")[:100], flush=True) state["code"] = code state["magic"] = magic # NOTE: magic-link leads to #/workspaces (join-list dead end) — skip it, # the 6-box code entry on #/confirmemail is the working path. if magic: print("magic link ignored (leads to workspaces dead-end):", magic[:70], flush=True) # ensure we are on the confirmemail page before typing the code if code and "#/confirmemail" not in page.url: try: await page.goto("https://app.slack.com/get-started#/confirmemail", wait_until="domcontentloaded", timeout=60000) await asyncio.sleep(6) print("re-navigated to confirmemail:", page.url[:120], flush=True) except Exception as e: print("renav err:", str(e).splitlines()[0], flush=True) if code and "#/confirmemail" in page.url: try: # Wait for the code input to appear (may take a moment after token submit) for sel in ["input[type=text]", "input[name=code]", "input[autocomplete=one-time-code]", "input[maxlength=6]", "input#code", "input"]: try: cinp = page.locator(sel).first await cinp.wait_for(state="visible", timeout=5000) print(f"code input found: {sel}", flush=True) break except Exception: continue else: print("no code input found; page text:", (await page.inner_text("body"))[:300], flush=True) # Slack code field = 6 separate boxes (aria="digit N of 6", maxlength=1) code_entry = code.replace("-", "").strip()[:6] print("code_entry (6 chars):", code_entry, flush=True) boxes = page.locator('input[maxlength="1"]') nbox = await boxes.count() print("code boxes found:", nbox, flush=True) if nbox >= 6: for i, ch in enumerate(code_entry[:6]): bx = boxes.nth(i) await bx.click(); await asyncio.sleep(0.12) await page.keyboard.type(ch); await asyncio.sleep(0.12) else: await cinp.click(); await asyncio.sleep(0.3) for ch in code_entry: await page.keyboard.type(ch); await asyncio.sleep(0.08) await asyncio.sleep(2) # Wait for submit button to become enabled, then click or press Enter submitted = False for bsel in ["button[type=submit]", "button:has-text('Continue')", "button:has-text('Submit')", "button:has-text('Verify')"]: try: b = page.locator(bsel).first await b.wait_for(state="visible", timeout=3000) disabled = await b.is_disabled() print(f"btn {bsel} disabled={disabled}", flush=True) if not disabled: await b.click(timeout=5000); submitted = True; break except Exception: pass if not submitted: await page.keyboard.press("Enter") print("pressed Enter as fallback", flush=True) # wait for the workspace-name form (up to 60s). URL leaving # #/confirmemail is NOT enough: SPA may land on #/createnew but # still render the email form (verification state lost). left = False for _ in range(30): await asyncio.sleep(2) if "#/confirmemail" not in page.url: bt = (await page.inner_text("body"))[:400].lower() if "enter your email" in bt: print("landed on email form — state lost", flush=True) break left = True; break # confirmCode API returns {"ok":true,"has_workspace":false} but SPA # sometimes stays put. NEVER page.goto (full reload kills verified # signup session -> drops back to email form + new captcha). # Magic-resume FIRST (signup token in path, keeps session): if not left: print("SPA stuck after ok:true — magic-resume (no hash-nav first)", flush=True) if magic: print("magic resume:", magic[:80], flush=True) await page.goto(magic, wait_until="domcontentloaded", timeout=60000) await asyncio.sleep(10) print("magic URL:", page.url[:150], flush=True) bt = (await page.inner_text("body"))[:400].lower() print("magic BODY:", bt[:250].replace("\n", " | "), flush=True) if "enter your email" not in bt: left = True elif "#/workspaces" in page.url or "#/createnew" in page.url: # dead-end list -> push hash to createnew WITHOUT reload await page.evaluate("() => { location.hash = '#/createnew'; }") await asyncio.sleep(4) bt = (await page.inner_text("body"))[:400].lower() if "enter your email" not in bt: left = True if not left: await page.evaluate("() => { location.hash = '#/createnew'; }") for _ in range(6): await asyncio.sleep(2) bt = (await page.inner_text("body"))[:400].lower() if "enter your email" not in bt: left = True; break print("post-hash left:", left, flush=True) if not left: body_txt = await page.inner_text("body") print("still on confirmemail:", body_txt[:200].replace("\n"," | "), flush=True) # retry: request a NEW code and use raw variant try: rq = page.locator("a:has-text('Request a new code'), button:has-text('Request a new code')").first if await rq.is_visible(timeout=3000): await rq.click(timeout=4000) print("requested new code", flush=True) await asyncio.sleep(6) code2, magic2 = get_code(email_, pw, wait=120) print("CODE2:", code2, "| magic2:", (magic2 or "none")[:80], flush=True) if magic2: await page.goto(magic2, wait_until="domcontentloaded", timeout=60000) await asyncio.sleep(12) print("magic2 URL:", page.url[:150], flush=True) if "#/confirmemail" not in page.url: left = True if code2 and not left: state["code2"] = code2 ce2 = code2.replace("-", "").strip()[:6] boxes2 = page.locator('input[maxlength="1"]') if await boxes2.count() >= 6: for i, ch in enumerate(ce2): bx = boxes2.nth(i) await bx.click(); await asyncio.sleep(0.12) await page.keyboard.type(ch); await asyncio.sleep(0.12) else: cinp = page.locator("input[type=text]").first await cinp.click(); await asyncio.sleep(0.3) for ch in ce2: await page.keyboard.type(ch); await asyncio.sleep(0.08) await asyncio.sleep(1.5) for _ in range(45): await asyncio.sleep(2) if "#/confirmemail" not in page.url: left = True; break print("retry left:", left, flush=True) except Exception as e2: print("retry err:", str(e2)[:80], flush=True) print("URL after code:", page.url, flush=True) print("BODY after code:", (await page.inner_text("body"))[:400].replace("\n"," | "), flush=True) # Slack post-confirm flow is multi-step: workspace name -> your name -> password import random, string wsname = "gothlab" + str(random.randint(100, 999)) passwd = "Gb!" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "9x" state["wsname"] = wsname state["password"] = passwd for step in range(10): await asyncio.sleep(3) body_txt = (await page.inner_text("body"))[:250].replace("\n", " | ") print(f"[ws step {step}] URL: {page.url[:110]} | {body_txt}", flush=True) # verified workspaces list -> "Create Another Workspace" starts # the naming flow in-SPA (no reload, session kept) if "#/workspaces" in page.url: try: cw = page.locator("a:has-text('Create Another Workspace'), button:has-text('Create Another Workspace'), a:has-text('Create a Workspace'), button:has-text('Create a Workspace')").first if await cw.is_visible(timeout=2500): await cw.click(timeout=5000) print("clicked Create Another Workspace", flush=True) await asyncio.sleep(4) print("post-caw URL:", page.url[:130], flush=True) except Exception as e: print("caw err:", str(e).splitlines()[0], flush=True) filled = False # post-verify createnew restarts at the EMAIL form -> re-enter # the (now verified) email; no captcha the second time try: ef = page.locator("input[type=email]").first if await ef.is_visible(timeout=1200): cur = await ef.input_value() if not cur: await ef.fill(email_); filled = True print("email re-entered:", email_, flush=True) except Exception: pass # password step if not filled: try: pf = page.locator("input[type=password]").first if await pf.is_visible(timeout=1500): await pf.fill(passwd); filled = True print("password filled", flush=True) except Exception: pass if not filled: for sel, val in [ ("input[placeholder*='workspace' i]", wsname), ("input[placeholder*='team' i]", wsname), ("input[name*=workspace i]", wsname), ("input[placeholder*='full name' i]", "Viktor User"), ("input[placeholder*='name' i]", "Viktor User"), ("input[name*=name i]", "Viktor User"), ("input[type=text]:visible", wsname), ]: try: f = page.locator(sel).first if await f.is_visible(timeout=1500): await f.fill(val); filled = True print("filled", sel, "=", val[:24], flush=True); break except Exception: continue # click primary continue button for bsel in ["button[type=submit]", "button:has-text('Next')", "button:has-text('Continue')", "button:has-text('Create Workspace')"]: try: b = page.locator(bsel).first if await b.is_visible(timeout=1500) and not await b.is_disabled(): await b.click(timeout=4000); print("clicked", bsel, flush=True); break except Exception: pass # success = left get-started flow entirely if "get-started" not in page.url: print("workspace flow done:", page.url[:140], flush=True) left = True; break print("URL final:", page.url, flush=True) print("BODY final:", (await page.inner_text("body"))[:400].replace("\n"," | "), flush=True) left = "get-started" not in page.url and "#/createnew" not in page.url state["stage"] = "workspace_done" if left else "code_failed" state["final_url"] = page.url # capture workspace domain (xxx.slack.com) from url or page links import re as _re m = None _m = _re.search(r"https://([a-z0-9\-]+)\.slack\.com", page.url) if _m and _m.group(1) not in ("app", "slack", "api", "status", "www", "join", "find", "go", "get-started"): m = _m if not m: links = await page.evaluate("""() => [...document.querySelectorAll('a')] .map(a=>a.href).filter(h=>/\\.slack\\.com/.test(h) && !h.includes('slack.com/get-started') && !h.includes('join.slack.com')).slice(0,10)""") print("page slack links:", links, flush=True) for l in links: m2 = _re.search(r"https://([a-z0-9\-]+)\.slack\.com", l) if m2 and m2.group(1) not in ("app", "slack", "api", "status", "www", "join", "find", "go", "get-started"): m = m2; break if m: state["workspace_url"] = m.group(1) print("WORKSPACE:", m.group(1), flush=True) else: # fallback: 'd' cookie contains team domain(s) try: cks = await page.context.cookies() for c in cks: if c["name"] == "d" and c.get("value"): print("d cookie:", c["value"][:120], flush=True) md = _re.search(r'"domain":"([a-z0-9\-]+)"', c["value"]) if md: state["workspace_url"] = md.group(1) print("WORKSPACE from cookie:", md.group(1), flush=True) except Exception as e: print("cookie ws err:", str(e)[:80], flush=True) except Exception as e: print("code submit err:", str(e).splitlines()[0], flush=True) state["cookies"] = await page.context.cookies() await page.screenshot(path=os.path.join(HERE, "slack_full_end.png")) # ==== Viktor Slack OAuth (same browser = Slack session alive) ==== if state.get("stage") == "workspace_done": try: VS = ("https://api.viktor.com/api/coworker/slack/signin" "?app_url=https%3A%2F%2Fapp.viktor.com") await page.goto(VS, wait_until="domcontentloaded", timeout=60000) await asyncio.sleep(8) print("viktor signin URL:", page.url[:160], flush=True) ws = state.get("workspace_url") # Slack may ask for the workspace URL first for _ in range(6): if "workspace-signin" not in page.url and "signin" not in page.url: break if ws: try: wi = page.locator("input[name=domain], input[placeholder*=workspace i], input#domain").first await wi.wait_for(state="visible", timeout=4000) await wi.fill(ws); await asyncio.sleep(1) await page.locator("button[type=submit], button:has-text('Continue')").first.click(timeout=5000) print("workspace url entered:", ws, flush=True) await asyncio.sleep(8) continue except Exception as e: print("ws-url fill err:", str(e).splitlines()[0], flush=True) # maybe an account/workspace chooser: click first workspace entry try: pick = page.locator("a:has-text('Find your workspaces'), button:has-text('Sign in')").first if await pick.is_visible(timeout=2000): await pick.click(timeout=4000); await asyncio.sleep(5); continue except Exception: pass break print("oauth page URL:", page.url[:180], flush=True) print("oauth page BODY:", (await page.inner_text("body"))[:200].replace("\n"," | "), flush=True) # Slack OAuth authorize (2-step: workspace select -> scope Allow) for retry in range(2): for sel in ["button#oauth_allow_button", "button[name=authorize]", "button:has-text('Allow')", "button[data-action=confirm]", "button[type=submit]", "button:has-text('Continue')"]: try: b = page.locator(sel).first if await b.is_visible(timeout=3000): await b.click(timeout=5000); print("clicked", sel, flush=True) await asyncio.sleep(4) break except Exception: pass if "#/callback" in page.url or "api.viktor.com" in page.url: break print("callback URL:", page.url[:200], flush=True) state["viktor_callback_url"] = page.url import urllib.parse as up q = dict(up.parse_qsl(up.urlparse(page.url).query)) if "exchange_token" in q: state["exchange_token"] = q["exchange_token"] state["user_id"] = q.get("user_id", "") # get JWTs jwt_url = ("https://api.viktor.com/api/auth/jwt_token" "?exchange_token=" + q["exchange_token"]) req = urllib.request.Request(jwt_url) with urllib.request.urlopen(req, timeout=30) as r: body = json.loads(r.read()) state["jwts_count"] = len(body.get("jwts") or []) state["jwt_body_keys"] = list(body.keys()) json.dump(body, open(os.path.join(HERE, "viktor_jwts.json"), "w"), indent=1) print("JWT obtained! keys:", list(body.keys()), "| jwts:", state["jwts_count"], flush=True) state["stage"] = "VIKTOR_JWT" else: print("no exchange_token in callback:", page.url[:200], flush=True) print("BODY:", (await page.inner_text("body"))[:300].replace("\n"," | "), flush=True) except Exception as e: print("viktor oauth err:", repr(e)[:200], flush=True) json.dump(state, open(STATE, "w"), indent=1, default=str) if state.get("stage") == "workspace_done" or state.get("stage") == "VIKTOR_JWT": rec = {"email": email_, "password": pw, "wsname": state.get("wsname"), "slack_password": state.get("password"), "workspace_url": state.get("workspace_url"), "stage": state.get("stage"), "exchange_token": state.get("exchange_token"), "ts": time.time()} with open(os.path.join(HERE, "accounts.jsonl"), "a", encoding="utf-8") as f: f.write(json.dumps(rec, ensure_ascii=False) + chr(10)) print("ACCOUNT SAVED:", rec["email"], rec["stage"], flush=True) if "--keep" in sys.argv: input("kept alive...") print("DONE state:", STATE, flush=True) async def run_batch(): n = 1 for i, a in enumerate(sys.argv): if a == "--batch" and i + 1 < len(sys.argv): n = int(sys.argv[i + 1]) for k in range(n): print(f"===== RUN {k+1}/{n} =====", flush=True) try: await main() except Exception as e: print("run err:", repr(e)[:200], flush=True) if k + 1 < n: await asyncio.sleep(10) asyncio.run(run_batch())