"""Finish Viktor OAuth from saved Slack cookies. Uses state cookies, navigates signin URL, clicks through Allow pages, captures exchange_token, fetches jwt.""" import json, os, sys, time, asyncio, urllib.request, urllib.parse HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.environ.get("SOLVER_PATH", ".")) import cloakbrowser STATE = os.path.join(HERE, "slack_state.json") SIGNIN = "https://api.viktor.com/api/coworker/slack/signin?app_url=https%3A%2F%2Fapp.viktor.com" async def main(): st = json.load(open(STATE, encoding="utf-8")) async with await cloakbrowser.launch_async(headless=True) as br: page = await br.new_page() ctx = page.context await ctx.add_cookies(st["cookies"]) exchange = None jwt = None async def on_resp(resp): nonlocal exchange u = resp.url if "exchange_token" in u and not exchange: q = urllib.parse.parse_qs(urllib.parse.urlparse(u).query) if q.get("exchange_token"): exchange = q["exchange_token"][0] print("EXCHANGE TOKEN captured, len", len(exchange), flush=True) jwt_resp = {} async def on_jwt(resp): if "/api/auth/jwt_token" in resp.url: try: jwt_resp["data"] = await resp.json() jwt_resp["status"] = resp.status print("JWT RESP", resp.status, str(jwt_resp['data'])[:200], flush=True) except Exception as e: print("jwt resp read err", e, flush=True) page.on("response", lambda r: asyncio.ensure_future(on_resp(r))) page.on("response", lambda r: asyncio.ensure_future(on_jwt(r))) await page.goto(SIGNIN, wait_until="domcontentloaded", timeout=60000) for step in range(12): await asyncio.sleep(4) u = page.url body = (await page.evaluate("document.body.innerText"))[:200].replace("\n", " | ") print(f"[{step}] {u[:120]}", flush=True) print(f" BODY: {body}", flush=True) if exchange: break if "viktor.com" in u and "callback" in u: q = urllib.parse.parse_qs(urllib.parse.urlparse(u).query) if q.get("exchange_token"): exchange = q["exchange_token"][0] break # click any Allow/submit/authorize button clicked = False for sel in ["button[type=submit]", "#allow", "button:has-text('Allow')", "button:has-text('Разрешить')", "input[type=submit]"]: try: loc = page.locator(sel).first if await loc.count() > 0 and await loc.is_visible(): await loc.click(timeout=5000) print(" clicked", sel, flush=True) clicked = True break except Exception: pass if not clicked: break if jwt_resp.get("data"): st["jwt"] = jwt_resp["data"] st["stage"] = "jwt_done" jwt = jwt_resp["data"] print("JWT from intercept OK", flush=True) if exchange and not jwt: st["exchange_token"] = exchange url = "https://api.viktor.com/api/auth/jwt_token?exchange_token=" + urllib.parse.quote(exchange) try: req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) data = json.loads(urllib.request.urlopen(req, timeout=30).read()) jwt = data st["jwt"] = data print("JWT OK:", str(data)[:200], flush=True) except Exception as e: print("JWT err:", e, flush=True) else: print("NO exchange_token", flush=True) try: fresh = await page.context.cookies() st["cookies_after_oauth"] = fresh viktor_cookies = [c for c in fresh if "viktor" in c.get("domain", "")] print("viktor cookies:", [(c["name"], c["domain"]) for c in viktor_cookies], flush=True) except Exception as e: print("cookie harvest err", e, flush=True) st["stage"] = "jwt_done" if jwt else st.get("stage") json.dump(st, open(STATE, "w", encoding="utf-8")) print("SAVED", STATE, flush=True) asyncio.run(main())