recovered snapshot from suspended aaronjaworski710 (history unavailable)

This commit is contained in:
reform
2026-10-23 20:04:11 +03:00
commit d747024308
25 changed files with 2464 additions and 0 deletions
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""connect_bonus_scanner.py — сканирует JWT-пул на connect-бонус когорту.
Механика (реверс 10.10.2026):
- chat_platform_connect_bonus_credits назначается СЕРВЕРОМ при создании
воркспейса (A/B-когорта). Коннект Slack/Discord сам по себе кредиты НЕ даёт
(проверено: has_slack=true, bonus=0).
- Этот скрипт пробегает accounts.jsonl и печатает bonus/has_slack/starter
по каждому акку. Акк с bonus>0 = попал в бонус-когорту: там коннект
Discord/Teams бота даёт кредиты без карты -> фармить свежими регами.
Usage:
python tools/connect_bonus_scanner.py [--accounts tools/accounts.jsonl]
Auth: query-param ?jwt=*** (Bearer/cookies могут отдавать 500 при нестабильном
auth-слое Viktor; query-jwt работает стабильно — см. CREDITS.md).
"""
import argparse
import json
import sys
import urllib.error
import urllib.parse
import urllib.request
API = "https://api.viktor.com"
UA = {"User-Agent": "Mozilla/5.0", "Origin": "https://app.viktor.com",
"Referer": "https://app.viktor.com/"}
def get(path: str, jwt: str, timeout: int = 25):
url = f"{API}{path}" + ("&" if "?" in path else "?") + "jwt=" + urllib.parse.quote(jwt)
req = urllib.request.Request(url, headers=UA)
try:
resp = urllib.request.urlopen(req, timeout=timeout)
return resp.status, json.loads(resp.read() or b"null")
except urllib.error.HTTPError as e:
return e.code, None
except Exception as e:
return -1, {"error": str(e)[:80]}
def scan_account(rec: dict) -> dict:
jwt = rec.get("jwt")
if not jwt:
return {"email": rec.get("email"), "skip": "no jwt"}
out = {"email": rec.get("email"), "src": rec.get("src")}
s, gs = get("/api/coworker/getting-started-status", jwt)
out["gs_http"] = s
if s == 200 and isinstance(gs, dict):
out["bonus"] = gs.get("chat_platform_connect_bonus_credits", 0)
out["has_slack"] = gs.get("has_slack")
out["starter_credits"] = gs.get("starter_credit_amount")
out["card_required"] = gs.get("starter_card_required")
out["integrations"] = gs.get("connected_integration_count")
# partner offer — бесплатный месяц до $500 (нужна карта: $1 hold -> void)
s2, pf = get_preflight(jwt)
out["partner_http"] = s2
if s2 == 200 and isinstance(pf, dict):
out["partner_eligible"] = pf.get("eligible")
out["due_today_cents"] = pf.get("due_today_cents")
return out
def get_preflight(jwt: str):
body = json.dumps({"package": "credits_40000", "billing_interval": "month",
"partner_offer": "claude_startups"}).encode()
url = f"{API}/api/coworker/partner-offers/preflight?jwt=" + urllib.parse.quote(jwt)
req = urllib.request.Request(url, data=body, method="POST",
headers={**UA, "Content-Type": "application/json"})
try:
resp = urllib.request.urlopen(req, timeout=25)
return resp.status, json.loads(resp.read())
except urllib.error.HTTPError as e:
return e.code, None
except Exception:
return -1, None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--accounts", default="tools/accounts.jsonl")
args = ap.parse_args()
try:
recs = [json.loads(l) for l in open(args.accounts, encoding="utf-8") if l.strip()]
except FileNotFoundError:
print(f"no accounts file: {args.accounts}", file=sys.stderr)
return 2
hits = 0
for rec in recs:
r = scan_account(rec)
flag = ""
if r.get("bonus", 0) and r["bonus"] > 0:
flag = " <<< BONUS COHORT"
hits += 1
print(json.dumps(r, ensure_ascii=False) + flag)
print(f"scanned={len(recs)} bonus_hits={hits}")
return 0
if __name__ == "__main__":
sys.exit(main())
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""credits_probe.py — проверить кредит-статус всех JWT в пуле.
Usage:
python tools/credits_probe.py [accounts.jsonl]
Читает пул (по строке JSON, поле jwt), для каждого акка:
GET /api/coworker/getting-started-status → starter_credit_amount, starter_card_required,
chat_platform_connect_bonus_credits
GET /api/coworker/subscription → план (null = free)
Печатает таблицу + пишет credits_report.json рядом с пулом.
"""
import json, os, sys, time, urllib.request, urllib.error
API = "https://api.viktor.com"
HERE = os.path.dirname(os.path.abspath(__file__))
POOL = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "accounts.jsonl")
REPORT = os.path.join(os.path.dirname(POOL), "credits_report.json")
def get(path, jwt):
req = urllib.request.Request(API + path, headers={
"User-Agent": "Mozilla/5.0", "Authorization": "Bearer " + jwt,
"Origin": "https://app.viktor.com", "Referer": "https://app.viktor.com/"})
try:
r = urllib.request.urlopen(req, timeout=30)
return r.status, json.loads(r.read() or b"null")
except urllib.error.HTTPError as e:
return e.code, e.read()[:120].decode(errors="replace")
except Exception as e:
return -1, str(e)[:120]
def main():
rows = []
with open(POOL, encoding="utf-8") as f:
accs = [json.loads(l) for l in f if l.strip()]
for a in accs:
jwt = a.get("jwt") or ""
if not jwt:
continue
email = a.get("email", "?")
s1, gs = get("/api/coworker/getting-started-status", jwt)
s2, sub = get("/api/coworker/subscription", jwt)
row = {"email": email, "gs_http": s1, "sub_http": s2,
"subscription": sub if s2 == 200 else None}
if s1 == 200 and isinstance(gs, dict):
row.update({
"starter_credit_amount": gs.get("starter_credit_amount"),
"starter_card_required": gs.get("starter_card_required"),
"connect_bonus": gs.get("chat_platform_connect_bonus_credits"),
"has_sent_first_task": gs.get("has_sent_first_task"),
})
rows.append(row)
print(json.dumps(row, ensure_ascii=False))
time.sleep(1.0) # не злить rate-limit
with open(REPORT, "w", encoding="utf-8") as f:
json.dump(rows, f, ensure_ascii=False, indent=1)
n_unlockable = sum(1 for r in rows if r.get("starter_credit_amount"))
print(f"\ntotal={len(rows)} starter_credit_available={n_unlockable} report={REPORT}")
if __name__ == "__main__":
main()
+33
View File
@@ -0,0 +1,33 @@
"""email-code door probe — proves the door is login-only.
POST /api/auth/email-code/request always returns 200 {"ok":true}, but for an
address without an account the server mails "No Viktor account for this address"
instead of a 6-digit code. Run with a fresh alias to reproduce.
"""
import json, random, string, urllib.request, sys
API = "https://api.viktor.com/api/auth/email-code/request"
def probe(email):
body = json.dumps({
"email": email,
"redirect_url": None,
"intent": "signup",
"invite_id": None,
"verisoul_session_id": None,
"posthog_distinct_id": None,
}).encode()
req = urllib.request.Request(API, data=body, headers={
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Origin": "https://app.viktor.com",
"Referer": "https://app.viktor.com/signup",
})
r = urllib.request.urlopen(req, timeout=30)
return r.status, r.read().decode()
if __name__ == "__main__":
email = sys.argv[1] if len(sys.argv) > 1 else "probe" + "".join(random.choices(string.digits, k=6)) + "@example.com"
print("email:", email)
print(probe(email))
print("check the mailbox: expect 'No Viktor account for this address'")
+22
View File
@@ -0,0 +1,22 @@
"""Static endpoint extractor for minified JS bundles (Vite/rolldown SPA)."""
import re, glob, json, sys
from collections import defaultdict
def extract(asset_dir):
pat_api = re.compile(r'[`"\'](/api/[a-zA-Z0-9_\-/${}.]+)[`"\']')
pat_oauth = re.compile(r'[`"\'](/oauth/[a-zA-Z0-9_\-/${}.]+)[`"\']')
pat_auth = re.compile(r'[`"\'](/auth/[a-zA-Z0-9_\-/${}.]+)[`"\']')
fullurls = re.compile(r'https://api\.[a-z0-9.\-]+([a-zA-Z0-9_\-/${}.]+)')
eps = defaultdict(set)
for f in glob.glob(f"{asset_dir}/*.js"):
s = open(f, encoding="utf-8", errors="replace").read()
for pat in (pat_api, pat_oauth, pat_auth, fullurls):
for m in pat.findall(s):
eps[re.sub(r'\$\{[^}]*\}', ':id', m).rstrip('/')].add(f.split("/")[-1].split("\\")[-1])
return {k: sorted(v)[:3] for k, v in sorted(eps.items())}
if __name__ == "__main__":
d = sys.argv[1] if len(sys.argv) > 1 else "assets"
out = extract(d)
print(json.dumps(out, indent=1))
print(f"\n{len(out)} endpoints", file=sys.stderr)
+105
View File
@@ -0,0 +1,105 @@
"""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())
+131
View File
@@ -0,0 +1,131 @@
# -*- coding: utf-8 -*-
"""
Viktor connected-tools reward looter (1000 credits / workspace, one-time).
PROVEN 2026-10-10:
GET /api/integration/coworker_github/connect?app_url=...&github_flow=install&jwt=***
-> 307 https://github.com/apps/viktor-com/installations/new?state=...
GitHub: login pooled account -> follow chain to /apps/viktor-com/installations/new/permissions
-> POST /apps/viktor-com/installations (hidden fields + install_target=all)
-> 200 HTML with meta-refresh url=https://api.viktor.com/api/integration/coworker_github/callback?code=..&installation_id=..&state=..
(meta-refresh! urllib/requests do NOT follow it - extract url= manually)
GET callback (no redirects) -> 307 app.viktor.com
GET /api/integration/github/installations?jwt=*** -> {"connected":true,"installation_count":N}
POST /api/coworker/grant-connected-tools-reward?jwt=*** -> {"granted_credits":1000,
"connected_tools_count":1,"reward_credits_balance":1000}
Notes:
- Reward is ONE-TIME 1000 credits per workspace (2nd+ tool -> granted_credits:0).
- Idempotent: re-POST returns 0, balance unchanged.
- Auth: query-param ?jwt=*** (Bearer/cookie currently 500 on some endpoints).
- reward_credits_balance counts into total remaining credits (total-remaining-credits.js:
credits_balance + previous + top_up + reward).
- In-house MCP apps (baremetrics/openrouter/... grant=api_key) -> 403
"In-house connect is not enabled for this workspace" (feature-gated).
- Other connect ids: coworker_bitbucket, coworker_msteams, coworker_discord,
coworker_github_cli, coworker_text2im (401 via query-jwt on this workspace).
Usage:
python3 tools/gh_tools_reward.py --jwt <JWT> --accounts gh_accounts.json [--n 1]
gh_accounts.json: [{"login","email","password","totp"}, ...]
Requires: requests, pyotp
"""
import argparse, json, re, time, urllib.parse
import requests, pyotp
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"}
API = "https://api.viktor.com"
def qj(jwt):
return "?" + "jwt=" + urllib.parse.quote(jwt)
def hidden_fields(html):
fields = {}
for m in re.finditer(r'<input[^>]*type="hidden"[^>]*>', html):
nm = re.search(r'name="([^"]+)"', m.group(0))
vl = re.search(r'value="([^"]*)"', m.group(0))
if nm:
fields[nm.group(1)] = vl.group(1) if vl else ""
return fields
def gh_login(acc):
s = requests.Session()
s.headers.update(UA)
r = s.get("https://github.com/login", timeout=30)
f = hidden_fields(r.text)
f.update({"login": acc["email"], "password": acc["password"],
"webauthn-conditional": "undefined", "javascript-support": "enabled",
"webauthn-support": "supported", "webauthn-iuvpaa-support": "unknown",
"webauthn-iuv": "false", "commit": "Sign in",
"timestamp": str(int(time.time() * 1000))})
r = s.post("https://github.com/session", data=f, allow_redirects=False, timeout=30)
loc = r.headers.get("Location", "")
if "two-factor" in loc:
if not loc.startswith("http"):
loc = "https://github.com" + loc
r2 = s.get(loc, timeout=30)
f2 = hidden_fields(r2.text)
f2["app_otp"] = pyotp.TOTP(acc["totp"]).now()
s.post("https://github.com/sessions/two-factor", data=f2, allow_redirects=True, timeout=30)
return s
def install_viktor_app(s, jwt):
r = requests.get(API + "/api/integration/coworker_github/connect"
"?app_url=https%3A%2F%2Fapp.viktor.com&github_flow=install" + "&" + qj(jwt).lstrip("?"),
headers=UA, allow_redirects=False, timeout=30)
cur = r.headers.get("Location", "")
if "github.com" not in cur:
return None, "connect %s" % r.status_code
rr = None
for _ in range(4):
rr = s.get(cur, timeout=30, allow_redirects=False)
if rr.status_code in (301, 302, 307, 308):
nx = rr.headers.get("Location")
if not nx.startswith("http"):
nx = "https://github.com" + nx
cur = nx
continue
break
m = re.search(r'<form[^>]*action="/apps/viktor-com/installations"[^>]*>(.*?)</form>', rr.text, re.S)
if not m:
return None, "no install form (%s)" % rr.url[:80]
f = hidden_fields(m.group(0))
f["install_target"] = "all"
r2 = s.post("https://github.com/apps/viktor-com/installations", data=f, allow_redirects=False, timeout=30)
cb = re.search(r'url=(https://api\.viktor\.com[^"]+)', r2.text)
if not cb:
return None, "no callback (len=%d)" % len(r2.text)
cburl = cb.group(1).replace("&amp;", "&")
rc = requests.get(cburl, headers=UA, allow_redirects=False, timeout=30)
return cburl, "callback %s" % rc.status_code
def claim(jwt):
r = requests.post(API + "/api/coworker/grant-connected-tools-reward" + qj(jwt),
json={}, headers=UA, timeout=30)
return r.status_code, r.json()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--jwt", required=True)
ap.add_argument("--accounts", required=True)
ap.add_argument("--n", type=int, default=1)
a = ap.parse_args()
accs = json.load(open(a.accounts, encoding="utf-8"))
for acc in accs[: a.n]:
s = gh_login(acc)
cb, msg = install_viktor_app(s, a.jwt)
print(acc["login"], "install:", msg)
if cb:
time.sleep(3)
print(acc["login"], "grant:", claim(a.jwt))
time.sleep(3)
if __name__ == "__main__":
main()
+84
View File
@@ -0,0 +1,84 @@
from patchright.sync_api import sync_playwright
import os, json, shutil, base64, time
EMAIL = json.load(open("viktor_gws_user.json"))["email"]
secret = open("_gv.txt").read().strip()
PDIR = os.environ.get("PROFILE_DIR", "browser_profile")
shutil.rmtree(PDIR, ignore_errors=True)
URL = "https://api.viktor.com/oauth/google/login?app_url=https%3A%2F%2Fapp.viktor.com&simple_flow=true&user_type=ai_coworker&intent=signup"
def dump_buttons(page, tag):
try:
btns = page.eval_on_selector_all("button, [role=button], c-wiz button", "els=>els.map(e=>(e.innerText||e.getAttribute('aria-label')||'').trim()).filter(x=>x)")
print(f"[{tag}] BUTTONS:", btns[:15])
except Exception as e:
print("btn dump err", str(e)[:60])
with sync_playwright() as p:
ctx = p.chromium.launch_persistent_context(PDIR, headless=False, no_viewport=True, channel="chromium")
page = ctx.new_page()
page.goto(URL, timeout=90000)
page.wait_for_timeout(7000)
# step 1: email
ident = page.locator("input[type=email], input[name=identifier]").first
ident.type(EMAIL, delay=50); page.wait_for_timeout(1200)
page.evaluate("document.querySelector('#identifierNext button')?.click()")
page.wait_for_timeout(8000)
print("after email:", page.url[:100])
# step 2: password
pwf = page.locator("input[type=password], input[name=Passwd]").first
if pwf.is_visible(timeout=10000):
pwf.type(secret, delay=50); page.wait_for_timeout(1200)
page.evaluate("document.querySelector('#passwordNext button')?.click()")
page.wait_for_timeout(10000)
print("after pw:", page.url[:120])
# step 3: handle workspace ToS / consent loops (up to 6 rounds)
for i in range(6):
url = page.url
if "viktor.com" in url and "google" not in url and "signin" not in url:
print("REACHED VIKTOR:", url[:150]); break
dump_buttons(page, f"round{i}")
body = page.inner_text("body")[:200].replace("\n"," | ")
clicked = False
for t in ["Понятно", "I understand", "Understood", "Accept", "Continue", "Allow", "Далее", "Принять", "Я понимаю", "Продолжить", "Разрешить"]:
try:
el = page.locator(f"button:has-text('{t}')").first
if el.is_visible(timeout=1500):
el.click(); page.wait_for_timeout(5000); print(f"round{i} clicked '{t}' -> {page.url[:90]}"); clicked=True; break
except Exception:
pass
if not clicked:
print(f"round{i} nothing to click; body:", body); break
if page.url == url and i > 0:
print("stuck at", url[:100]); break
page.wait_for_timeout(4000)
print("FINAL URL:", page.url[:200])
print("FINAL BODY:", page.inner_text("body")[:500].replace("\n", " | "))
# verify session via app
page.goto("https://app.viktor.com/web-chat?thread=ghF347dQjKCFXyfPiJ9Rzy", wait_until="domcontentloaded", timeout=90000)
page.wait_for_timeout(9000)
print("APP URL:", page.url[:200])
print("APP BODY:", page.inner_text("body")[:700].replace("\n", " | "))
cookies = ctx.cookies()
vk = {c["name"]: c["value"] for c in cookies if "viktor" in c.get("domain", "")}
json.dump({"email": EMAIL, "cookies": cookies, "app_url": page.url}, open("viktor_final_session.json", "w"))
sess = vk.get("session", "")
is_anon = "anon" in vk.get("anon_session_id", "")
print("HAS session cookie:", bool(sess), "| anon?:", is_anon)
# try decode as JWT-like (3 parts)
if sess.count(".") == 2:
for idx in (0, 1):
try:
pl = sess.split(".")[idx]; pl += "=" * (-len(pl) % 4)
dec = base64.urlsafe_b64decode(pl).decode(errors="replace")
print(f"session part{idx}:", dec[:250])
except Exception:
pass
page.screenshot(path="viktor_final2.png")
ctx.close()
+574
View File
@@ -0,0 +1,574 @@
"""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 <IMAP host>: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("&amp;", "&") 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())
+139
View File
@@ -0,0 +1,139 @@
import os
"""Slack createnew workspace via patchright + free solver sidecar (:8877) recaptcha token injection."""
from patchright.sync_api import sync_playwright
import json, random, string, os, time, imaplib, email as emaillib, re, urllib.request
BASE = json.load(open(os.path.expanduser("~/Desktop/_SCRIPTS/gmail_pool.json")))
owner = BASE["email"]; app_pw = BASE["app_password"]
local = owner.split("@")[0]; dom = owner.split("@")[1]
alias = "vk" + "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
EMAIL = f"{local}+{alias}@{dom}"
open("slack_email4.txt", "w").write(EMAIL)
print("EMAIL:", EMAIL)
SOLVER = "http://127.0.0.1:8877/solve"
URL = "https://slack.com/get-started#/createnew"
PDIR = os.environ.get("PROFILE_DIR", "browser_profile")
def solve_recaptcha(sitekey, page_url):
body = json.dumps({"type": "recaptcha", "version": "v2", "sitekey": sitekey, "url": page_url}).encode()
req = urllib.request.Request(SOLVER, data=body, headers={"Content-Type": "application/json"})
r = json.loads(urllib.request.urlopen(req, timeout=300).read())
return r
def inject_token(page, token):
page.evaluate("""(tok) => {
const el = document.getElementById('g-recaptcha-response');
if (el) { el.innerHTML = tok; el.value = tok; }
if (window.___grecaptcha_cfg) {
const clients = window.___grecaptcha_cfg.clients;
const walk = (o) => {
for (const k in o) {
const v = o[k];
if (v && typeof v === 'object') { walk(v); }
else if (typeof v === 'function' && k.toLowerCase().includes('callback')) { try { v(tok); } catch(e){} }
}
};
try { walk(clients); } catch(e){}
}
if (window.grecaptcha && window.grecaptcha.getResponse) {
window.grecaptcha.getResponse = () => tok;
}
}""", token)
def get_code(wait=120):
t0 = time.time()
while time.time() - t0 < wait:
try:
M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
M.login(owner, app_pw); M.select("INBOX")
typ, data = M.search(None, f'(FROM "slack")')
for i in data[0].split()[-6:]:
typ, msgd = M.fetch(i, "(RFC822)")
msg = emaillib.message_from_bytes(msgd[0][1])
to = msg.get("To", "")
if alias not in to and EMAIL not in to: 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")
m = re.search(r"\b(\d{6})\b", body)
if m:
M.logout(); return m.group(1)
M.logout()
except Exception as e:
print("imap err", str(e)[:60])
time.sleep(6)
return None
with sync_playwright() as p:
ctx = p.chromium.launch_persistent_context(PDIR, headless=False, no_viewport=True, channel="chromium")
page = ctx.new_page()
page.goto(URL, timeout=90000)
page.wait_for_timeout(8000)
print("URL1:", page.url[:120])
inp = page.locator("input[type=email], input[name=email]").first
if not inp.is_visible(timeout=10000):
print("NO INPUT:", page.inner_text("body")[:250].replace("\n", " | "))
ctx.close(); raise SystemExit
inp.type(EMAIL, delay=50); page.wait_for_timeout(1200)
page.locator("button[type=submit]").first.click()
page.wait_for_timeout(10000)
print("URL2:", page.url[:140])
body2 = page.inner_text("body")[:400].replace("\n", " | ")
print("BODY2:", body2)
# find recaptcha sitekey on page
sitekey = page.evaluate("""() => {
const f = [...document.querySelectorAll('iframe')].map(i=>i.src).filter(s=>s.includes('recaptcha'));
const m = f.length ? f[0].match(/k=([A-Za-z0-9_\\-]+)/) : null;
return m ? m[1] : null;
}""")
print("SITEKEY:", sitekey)
if sitekey:
print("solving recaptcha via sidecar...")
res = solve_recaptcha(sitekey, page.url)
print("solver status:", res.get("status"), "| token len:", len(res.get("token") or ""))
tok = res.get("token")
if tok:
inject_token(page, tok)
# re-click submit
page.wait_for_timeout(2000)
try:
page.locator("button[type=submit]").first.click()
except Exception: pass
page.wait_for_timeout(12000)
print("URL3:", page.url[:140])
print("BODY3:", page.inner_text("body")[:400].replace("\n", " | "))
code = get_code(120)
print("CODE:", code)
if code:
cinp = page.locator("input[type=text]").first
if cinp.is_visible(timeout=8000):
cinp.type(code, delay=80); page.wait_for_timeout(1500)
page.locator("button[type=submit]").first.click()
page.wait_for_timeout(14000)
print("URL4:", page.url[:160])
print("BODY4:", page.inner_text("body")[:500].replace("\n", " | "))
# workspace naming step
for label, val in [("workspace", "ViktorTeam"), ("full name", "Viktor User"), ("name", "Viktor User")]:
try:
f = page.locator(f"input[placeholder*='{label}' i], input[name*='{label.split()[0]}' i]").first
if f.is_visible(timeout=2000): f.type(val, delay=40); page.wait_for_timeout(800)
except Exception: pass
try:
page.locator("button[type=submit]").first.click(); page.wait_for_timeout(10000)
except Exception: pass
print("URL5:", page.url[:160])
print("BODY5:", page.inner_text("body")[:500].replace("\n", " | "))
cookies = ctx.cookies()
json.dump({"email": EMAIL, "cookies": cookies, "url": page.url}, open("slack_ws_result.json", "w"))
page.screenshot(path="slack_ws.png")
ctx.close()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""starter_unlock.py — запросить starter-credit сессию (16 000 кредитов) для JWT.
Usage:
python tools/starter_unlock.py <JWT> [return_to]
python tools/starter_unlock.py --pool accounts.jsonl [email]
Печатает checkout URL (pay.viktor.com). Дальше: открыть URL, добавить карту
(VCC, $0 verification-charge) → outcome станет "unlocked", кредиты зачислятся.
Проверка после: GET /api/coworker/getting-started-status (credits_probe.py).
"""
import json, os, sys, urllib.request, urllib.error
API = "https://api.viktor.com"
def unlock(jwt, return_to="onboarding"):
req = urllib.request.Request(API + "/api/coworker/starter-credit-unlock-session",
method="POST", data=json.dumps({"return_to": return_to}).encode(),
headers={"User-Agent": "Mozilla/5.0", "Authorization": "Bearer " + jwt,
"Origin": "https://app.viktor.com", "Referer": "https://app.viktor.com/",
"Content-Type": "application/json"})
try:
r = urllib.request.urlopen(req, timeout=30)
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
return e.code, e.read()[:300].decode(errors="replace")
def main():
args = sys.argv[1:]
if not args:
print(__doc__); sys.exit(1)
if args[0] == "--pool":
pool = args[1] if len(args) > 1 else os.path.join(os.path.dirname(os.path.abspath(__file__)), "accounts.jsonl")
want = args[2] if len(args) > 2 else None
jwt = None
with open(pool, encoding="utf-8") as f:
for l in f:
if not l.strip():
continue
a = json.loads(l)
if want is None or a.get("email") == want:
jwt = a.get("jwt")
if jwt:
print("using:", a.get("email"))
break
if not jwt:
print("no jwt found in pool"); sys.exit(1)
return_to = "onboarding"
else:
jwt = args[0]
return_to = args[1] if len(args) > 1 else "onboarding"
s, b = unlock(jwt, return_to)
print("HTTP", s)
print(json.dumps(b, ensure_ascii=False, indent=1) if isinstance(b, dict) else b)
if isinstance(b, dict) and b.get("outcome") == "redirect":
print("\nCHECKOUT URL (открыть в браузере, добавить VCC):")
print(b["destination"])
elif isinstance(b, dict) and b.get("outcome") == "unlocked":
print("\nALREADY UNLOCKED, credits:", b.get("credits"))
if __name__ == "__main__":
main()