recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
# viktor-autoreg
|
||||
|
||||
Reverse-engineered Viktor.com (app.viktor.com) API + autoreg tooling.
|
||||
|
||||

|
||||
|
||||
## What's inside
|
||||
|
||||
- `docs/CREDITS.md` — **how to get credits** (16K starter unlock via VCC, Gmail-door bonus, referral/partner/promo mechanics, probe scripts).
|
||||
- `docs/IDE-GUIDE.md` — **use it in Cursor/Cline/Continue/Claude Code/MCP**: full wiring guide + credits blocker note.
|
||||
- `SETUP.md` — **start here**: what to enable / change / add (mail pool, IMAP, captcha model, env vars, batch mode, pitfalls).
|
||||
- `viktor_api.md` — full API surface: 36 endpoints, auth architecture, token exchange flow, anti-bot stack (Verisoul/PostHog), all 4 signup doors mapped with server-side proofs.
|
||||
- `VERIFICATION.md` — live probe report (2026-10-08): 11/11 endpoint checks with verdicts.
|
||||
- `viktor_endpoints.json` — normalized endpoint map extracted from 380 SPA chunks.
|
||||
- `tools/extract_endpoints.py` — static endpoint extractor for minified JS bundles.
|
||||
- `tools/gws_oauth.py` — Google Workspace SA user creation + headed patchright OAuth runner (Google door; currently server-disabled for signup).
|
||||
- `dashboard.html` — visual ops dashboard: pipeline stages, file map, env config points, pitfalls, door status (screenshot: `docs/dashboard.png`).
|
||||
- `tools/slack_reger.py` — **main tool**: full Slack workspace creation flow (reCAPTCHA Enterprise v2 solved in-process via mistral classifier -> work-mail-провайдер IMAP code -> workspace naming -> Viktor Slack OAuth -> jwt_token exchange).
|
||||
- `tools/viktor_gateway.py` — **OpenAI-compatible gateway** over the Viktor web-chat JWT pool (REST `POST /threads` + WS `tok_delta` streaming reverse-engineered from the SPA; `/v1/chat/completions`, `/v1/models`, `/health`; protocol doc: `docs/GATEWAY.md`).
|
||||
- `tools/finish_viktor_oauth.py` — finish Viktor OAuth from saved Slack cookies (intercepts jwt_token in-browser; dodges 429).
|
||||
- `tools/slack_ws.py` — earlier sidecar-HTTP variant (kept for reference; sidecar queue starves under concurrent jobs).
|
||||
- `tools/email_code_probe.py` — email-code door probe (login-only proof).
|
||||
|
||||
## Signup door matrix (2026-10)
|
||||
|
||||
| Door | Endpoint | Status |
|
||||
|------|----------|--------|
|
||||
| email-code | POST /api/auth/email-code/request | LOGIN-ONLY (server mails "No Viktor account") |
|
||||
| Google | /oauth/google/login | Server-disabled (`error=signup-unavailable`) |
|
||||
| MS Teams | /oauth/microsoft/login | Requires work/school tenant |
|
||||
| Slack | /api/coworker/slack/signin | **FULL CHAIN VERIFIED 2026-10-09** — workspace created, OAuth done, JWT 200, `/api/me` 200 (see VERIFICATION.md). Free local vision solver, $0 |
|
||||
|
||||
## Token flow
|
||||
|
||||
OAuth callback -> `{exchange_token}` -> `GET /api/auth/jwt_token?exchange_token=` -> `{jwts}` -> `GET /api/coworker/post-signin-state?jwt=` -> cookie `session` (JWT).
|
||||
|
||||
## Pipeline (reger -> gateway)
|
||||
|
||||
1. `python tools/slack_reger.py --batch N` — creates Slack workspaces, harvests Viktor `exchange_token`/JWT into `accounts.jsonl`
|
||||
2. `python tools/viktor_gateway.py` — serves `:8700/v1/chat/completions` from that pool (hot reload; round-robin; auto-disable on 401)
|
||||
|
||||
## Credits status (2026-10-10)
|
||||
|
||||
Fresh workspaces = 0 credits (`402 out of credits`; auth OK). Unlock path: **16 000 starter credits** via card verification (`tools/starter_unlock.py` → pay.viktor.com checkout, $0 auth — VCC works in theory). Probe the whole pool: `tools/credits_probe.py`. Full breakdown of every credit source (starter / Gmail door / connect-bonus / referral / partner `claude_startups` / promo codes): **`docs/CREDITS.md`**.
|
||||
|
||||
## Notes
|
||||
|
||||
- Chrome cookies `v20` (App-Bound Encryption) can't be moved across profiles; only `v10` decrypts via DPAPI+AES-GCM.
|
||||
- Workspace ToS speedbump button is "Понятно"/"I understand" (localized).
|
||||
- patchright headed passes Google identifier checks; headless does not.
|
||||
- No secrets in this repo. Gmail pool, SA keys and solver configs are external.
|
||||
|
||||
Research/interop tooling for authorized testing.
|
||||
@@ -0,0 +1,93 @@
|
||||
# SETUP — где что включать / менять / добавлять
|
||||
|
||||
Один файл на все вопросы: что поправить, чтобы регер работал на ТВОЁМ окружении.
|
||||
|
||||
## 0. Требования
|
||||
|
||||
- Python 3.11 (x64)
|
||||
- `pip install cloakbrowser patchright` (cloakbrowser тянет свой Firefox/Chromium)
|
||||
- Папка captcha-solver sidecar (`cs_sidecar` из связки waguriagentic/captcha-solver + наши патчи `recaptcha/image_solve.py`) — путь задаётся env `SOLVER_PATH`
|
||||
- Живой OpenAI-совместимый vision-прокси для классификатора сетки (модель `qwen3-vl-flash` или любая vision) — ключ в keypool солвера
|
||||
|
||||
## 1. ВКЛЮЧИТЬ (запуск)
|
||||
|
||||
```bash
|
||||
# Windows (git-bash)
|
||||
export SOLVER_PATH="/путь/до/cs_sidecar"
|
||||
export SLACK_MAILS_FILE="./mails.txt"
|
||||
export SLACK_IMAP_HOST="imap.твоего-провайдера.tld"
|
||||
export VISION_BASE="http://127.0.0.1:PORT/v1" # прокси vision-модели
|
||||
|
||||
python tools/slack_reger.py # один прогон
|
||||
python tools/slack_reger.py --batch 5 # 5 акков подряд
|
||||
python tools/viktor_gateway.py # гейтвей :8700 поверх accounts.jsonl
|
||||
```
|
||||
|
||||
Состояние: `slack_state.json` (куки/stage), `slack_mail_offset.json` (offset пула), `accounts.jsonl` (готовые акки для гейтвея).
|
||||
|
||||
## 2. ПОМЕНЯТЬ (таблица настроек)
|
||||
|
||||
| Что | Где (tools/slack_reger.py) | На что менять |
|
||||
|-----|---------------------------|---------------|
|
||||
| Пул почт | env `SLACK_MAILS_FILE` / строка `MAILS =` (~23) | любой файл `email:password` построчно. Slack принимает work-домены,consumer (gmail) режет |
|
||||
| IMAP-хост | env `SLACK_IMAP_HOST` / строка `IMAP_HOST =` (~25) | IMAP-сервер твоего почтовика (SSL 993) |
|
||||
| IMAP-логин/пароль | внутри `get_code()` | пароль почты берётся из пула (вторая половина строки) |
|
||||
| Regex кода | `get_code()`: `\b([A-Z0-9]{3}-[A-Z0-9]{3})\b` | формат кода твоего провайдера. Slack шлёт `XXX-XXX` |
|
||||
| Капча-модель | вызов `solve_recaptcha_v2_realpage(classifier=...)` | `mistral` = keypool vision-ключей; можно `qwen3-vl-*` |
|
||||
| Таймаут капчи | `timeout_s=560` в том же вызове | +60с на медленный прокси |
|
||||
| Лимит раундов | `solve_image_challenge(..., max_attempts=25)` | Slack Enterprise ре-эскалирует дольше демо Google; ниже 15 не ставить |
|
||||
| Headless | `launch_async(headless=...)` | headed отладка, headless прод |
|
||||
| Offset акков | `slack_mail_offset.json` | удалить файл = начать с первой почты |
|
||||
| Имя/пароль workspace | блок workspace naming (~350): `random` генерация | свои шаблоны, пароль должен удовлетворять Slack (буквы+цифры+символ) |
|
||||
| Viktor app_url | секция OAuth: `app_url=https%3A%2F%2Fapp.viktor.com` | свой tenant/app |
|
||||
|
||||
## 3. ДОБАВИТЬ (точки расширения)
|
||||
|
||||
1. **Новый почтовый провайдер** — ① файл почт в формате `email:password` ② `SLACK_IMAP_HOST` ③ в `get_code()` поправить regex кода под формат писем провайдера.
|
||||
2. **hcaptcha / turnstile вместо reCAPTCHA** — в `cs_sidecar` уже есть решатели; заменить вызов `solve_recaptcha_v2_realpage` на `solve_hcaptcha` / `solve_turnstile` с sitekey целевой страницы.
|
||||
3. **Своя vision-модель** — keypool солвера читает `VISION_BASE`/ключ; любая OpenAI-совместимая vision (qwen3-vl, gpt-4o-mini, локальная llava) работает, если прокси отвечает на `/chat/completions` с image_url.
|
||||
4. **Массовый прогон** — `--batch N` уже есть; для параллели — несколько процессов с РАЗНЫМИ `slack_mail_offset.json` (иначе гонка за offset) или предварительная нарезка пула на N файлов.
|
||||
5. **Прокси** — cloakbrowser принимает `proxy={"server": "http://ip:port"}` в `launch_async()`; на каждый акк — новый exit IP.
|
||||
6. **JWT в базу** — секция Viktor OAuth пишет `accounts.jsonl`; гейтвей `tools/viktor_gateway.py` подхватывает hot-reload'ом каждые 60с.
|
||||
|
||||
## 4. Структура
|
||||
|
||||
```
|
||||
viktor_reg/
|
||||
├── README.md — обзор, door matrix, token flow
|
||||
├── SETUP.md — этот файл
|
||||
├── VERIFICATION.md — пруфы live-проб (октябрь 2026)
|
||||
├── dashboard.html — визуальная консоль (открыть в браузере)
|
||||
├── shot_dashboard.py — генератор скрина дашборда
|
||||
├── viktor_api.md — 36 endpoints, auth-архитектура
|
||||
├── viktor_endpoints.json — карта эндпоинтов из 380 SPA-чанков
|
||||
├── docs/
|
||||
│ ├── dashboard.png — скрин консоли
|
||||
│ ├── captcha_solved.png — пруф: image challenge решён
|
||||
│ ├── confirmemail.png — пруф: дошли до #/confirmemail
|
||||
│ └── GATEWAY.md — протокол гейтвея
|
||||
└── tools/
|
||||
├── slack_reger.py — ГЛАВНЫЙ: полный флоу Slack → Viktor
|
||||
├── viktor_gateway.py — OpenAI-compat гейтвей :8700
|
||||
├── slack_ws.py — ранний sidecar-вариант (референс)
|
||||
├── gws_oauth.py — Google-дверь (server-disabled)
|
||||
├── email_code_probe.py — проба email-code двери
|
||||
└── extract_endpoints.py — экстрактор эндпоинтов из бандлов
|
||||
```
|
||||
|
||||
## 5. СЛОМАЛОСЬ (быстрые фиксы)
|
||||
|
||||
| Симптом | Причина | Фикс |
|
||||
|---------|---------|------|
|
||||
| `NO TOKEN` после N раундов | Google зациклил challenge на этой почте | перезапуск — возьмёт следующую почту |
|
||||
| Вечное «Checking your code…» | код вбит в одно поле, а Slack ждёт 6 боксов `input[maxlength="1"]` | уже исправлено в reger; не менять селектор |
|
||||
| `ok:true` но SPA стоит | баг навигации Slack | уже исправлено: форс-навигация `#/createnew` после ok:true |
|
||||
| Код не найден в IMAP | regex `\d{6}` не матчит `XXX-XXX` | уже исправлено; под своего провайдера — свой regex |
|
||||
| Magic-link уводит в `#/workspaces` | тупик join-листа | игнорировать magic-link, только код (уже в reger) |
|
||||
| Sidecar HTTP `/solve` таймаутит | `_solve_lock` занят cron-задачами | использовать in-process solve (как в reger) |
|
||||
| `launch_async() got unexpected kwarg user_data_dir` | cloakbrowser не принимает его | параметр убран; профиль эфемерный |
|
||||
| Капча на русском/непонятном языке | локаль anchor-страницы | форсировать `hl=en` в api.js-роуте |
|
||||
|
||||
## 6. Секреты
|
||||
|
||||
В репе НЕТ секретов: пул почт, IMAP-пароли, vision-ключи, GitHub-токены — всё внешнее через env/файлы. `ghtok.txt` в рабочую директорию не коммитить (в репу не пушится).
|
||||
@@ -0,0 +1,82 @@
|
||||
# Verification Report — 2026-10-08
|
||||
|
||||
Live probe of all discovered doors (full output in this file, run from local network).
|
||||
|
||||
## Endpoint probe results
|
||||
|
||||
| # | Endpoint | Result | Verdict |
|
||||
|---|----------|--------|---------|
|
||||
| 1 | `POST /api/auth/email-code/request` | `200 {"ok":true}` | Always 200, but new address receives "No Viktor account for this address" email — **login-only door** |
|
||||
| 2 | `POST /api/auth/email-code/verify` | `200 {"ok":false,"reason":"invalid","exchange_token":null,...}` | Verify works, needs real 6-digit code from a **registered** mailbox |
|
||||
| 3 | `GET /api/auth/jwt_token` | `400 exchange_token parameter is required` | Exchange endpoint: `verify -> exchange_token -> jwt` |
|
||||
| 4 | `POST /api/auth/jwt_bypass` | `422 Field required` with empty body, `404` with `{jwt,user_id}` | Route alive but **disabled in production** (client code: `VITE_ENVIRONMENT==='production' -> bypass-disabled`) |
|
||||
| 5 | `GET /oauth/google/login` | `200` Google signin HTML | Redirect works; after full Google auth (tested with Workspace SA user) backend returns `?error=signup-unavailable` |
|
||||
| 6 | `GET /oauth/microsoft/login` | `200` Microsoft signin HTML | Requires work/school tenant; personal accounts rejected |
|
||||
| 7 | `GET /api/coworker/slack/signin` | `200` -> redirect to `slack.com/oauth/v2/authorize` | **Only live signup door**; needs own Slack workspace (createnew = work email + reCAPTCHA v2) |
|
||||
| 8 | `GET /api/coworker/workspace-info` | `401 Authorization header or jwt param is missing` | Protected, auth model confirmed |
|
||||
| 9 | `GET /api/coworker/post-signin-state?jwt=***` | `401 Token invalid Not enough segments` | JWT validation confirmed |
|
||||
| 10 | `GET app.viktor.com/web-chat?thread=...` | `200` SPA HTML | App alive |
|
||||
| 11 | `GET /docs /redoc /openapi.json /api/docs` | `404` | No public API docs |
|
||||
|
||||
## Auth flow (confirmed)
|
||||
|
||||
```
|
||||
email-code/request -> mailbox 6-digit code -> email-code/verify
|
||||
-> {ok:true, exchange_token, user_id, redirect_url}
|
||||
-> GET /api/auth/jwt_token?exchange_token=*** -> JWT
|
||||
-> /api/coworker/* with Authorization: Bearer <jwt>
|
||||
```
|
||||
|
||||
## Signup door matrix (final)
|
||||
|
||||
| Door | Status | Blocker |
|
||||
|------|--------|---------|
|
||||
| Email-code | DEAD for signup | Login-only; no account = no code |
|
||||
| Google | DEAD | Server-side `signup-unavailable` |
|
||||
| Microsoft/Teams | BLOCKED | Needs M365 work/school tenant (dev tenant = phone verification wall) |
|
||||
| Slack | **LIVE** | Own workspace required; createnew behind reCAPTCHA v2 (sitekey `6LcRpcIr...2Ze`) |
|
||||
|
||||
## Anti-bot
|
||||
|
||||
- `verisoul_session_id` + `posthog_distinct_id` accepted as `null` (non-blocking telemetry)
|
||||
- Signup doors gated by PostHog feature flags (server-side evaluation; anonymous `/flags` query returns 0 flags)
|
||||
- Slack createnew: `challenge_response:true` + reCAPTCHA v2
|
||||
|
||||
## Free captcha solver (local, in-process)
|
||||
|
||||
- reCAPTCHA Enterprise v2 on Slack createnew is **SOLVED** by the free local vision solver: cloakbrowser + grid classifier (mistral/qwen3-vl via local proxy), tokens 2297-2510 bytes captured on the live page. Evidence: `solve_image ok: True` rounds 3-12, `TOKEN LEN: 2510` (run 2026-10-08).
|
||||
- Fixed 3 solver bugs: `range(rounds)` never extended on dynamic challenge upgrade (rewrote to while-loop with `.rc-imageselect-dynamic-selected` detection), frame-object strict-mode, humanize incompatible with frame_locator.
|
||||
- Sidecar HTTP mode starves under concurrent cron jobs (`_solve_lock`) — use **in-process** import instead.
|
||||
|
||||
## Slack signup progress (2026-10-08)
|
||||
|
||||
1. createnew email submit -> reCAPTCHA Enterprise solved in-process -> Continue -> `#/confirmemail` ✓
|
||||
2. Confirmation code from mailbox via IMAP — format `XXX-XXX`, field is **6 separate boxes** (`aria="digit N of 6"`, maxlength=1) — enter without dash ✓
|
||||
3. `POST app.slack.com/api/signin.confirmCode` -> `{"ok":true,"has_workspace":false}` — **code accepted** ✓
|
||||
4. SPA sometimes stays on confirmemail after ok:true — force-navigate to `#/createnew` then multi-step workspace flow (name/password) — in `tools/slack_reger.py`
|
||||
5. After workspace: `GET /api/coworker/slack/signin?app_url=...` -> Slack OAuth allow -> `/signin/callback?exchange_token=*** -> `GET /api/auth/jwt_token?exchange_token=*** -> JWT
|
||||
|
||||
## Verdict
|
||||
|
||||
**Reverse complete (11/11 probes verified). Slack door is live and past captcha + email code (`confirmCode ok:true`). Remaining: workspace completion + OAuth callback harvest — automated in `tools/slack_reger.py`.**
|
||||
|
||||
|
||||
## FULL CHAIN VERIFIED — 2026-10-09 (green run)
|
||||
|
||||
Complete Slack -> Viktor registration executed end-to-end from a clean browser:
|
||||
|
||||
| Step | Proof |
|
||||
|------|-------|
|
||||
| reCAPTCHA v2 solved in-process | token 2340 bytes, vision grid classifier (local model), $0 |
|
||||
| IMAP code fetched | format `XXX-XXX`, entered into 6 single-char boxes (`input[maxlength=1]`) |
|
||||
| `signin.confirmCode` | `{"ok":true,...}` — code accepted by API |
|
||||
| Workspace created | `<ws>.slack.com` + team id `T0C8W24LFAL`, state `workspace_done`, 27 cookies harvested |
|
||||
| Viktor OAuth | Allow-page submit -> callback `?exchange_token=...` (22 chars) + `user_id` |
|
||||
| `GET /api/auth/jwt_token` | **HTTP 200** `{"jwts":[...]}`, JWT 1463 bytes (first attempt hit 429 rate-limit — retry OK) |
|
||||
| `GET /api/me` (Bearer JWT) | **HTTP 200** `{"id":"...","email":"...","display_name":"...","provider":"slack"}` |
|
||||
| Session cookie | `session` on `api.viktor.com` captured |
|
||||
|
||||
Notes:
|
||||
- Target web-chat thread id returned 404 on `thread-info` REST probe — thread lives in the WS web-chat context, not REST.
|
||||
- Magic-link from the Slack email leads to `#/workspaces` join-list dead end — code path only.
|
||||
- `tools/finish_viktor_oauth.py` — standalone OAuth finisher from saved cookies (intercepts `jwt_token` response in-browser to dodge API rate-limit).
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>viktor-autoreg — КОНСОЛЬ</title>
|
||||
<style>
|
||||
:root { --bg:#0d1117; --card:#161b22; --border:#30363d; --txt:#e6edf3; --dim:#8b949e;
|
||||
--grn:#3fb950; --yel:#d29922; --red:#f85149; --blu:#58a6ff; --pur:#bc8cff; --org:#ffa657; }
|
||||
* { box-sizing:border-box; margin:0; padding:0; }
|
||||
body { background:var(--bg); color:var(--txt); font:15px/1.55 "Segoe UI",Arial,sans-serif; padding:28px; width:1360px; }
|
||||
h1 { font-size:26px; margin-bottom:2px; }
|
||||
.sub { color:var(--dim); margin-bottom:24px; font-size:14px; }
|
||||
.card { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:20px; margin-bottom:18px; }
|
||||
.card h2 { font-size:19px; margin-bottom:14px; padding-bottom:8px; border-bottom:2px solid var(--border); }
|
||||
.h-start h2 { color:var(--grn); } .h-cfg h2 { color:var(--org); } .h-add h2 { color:var(--blu); }
|
||||
.h-do h2 { color:var(--pur); } .h-status h2 { color:var(--yel); } .h-fix h2 { color:var(--red); }
|
||||
.big-cmd { background:#010409; border:1px solid var(--grn); border-radius:8px; padding:16px 18px;
|
||||
font-family:Consolas,monospace; font-size:16px; color:var(--grn); margin:10px 0; white-space:pre-wrap; word-break:break-all; }
|
||||
.cmd { background:#010409; border:1px solid var(--border); border-radius:6px; padding:10px 14px;
|
||||
font-family:Consolas,monospace; font-size:13.5px; color:var(--org); margin:6px 0; white-space:pre-wrap; word-break:break-all; }
|
||||
.num { display:inline-flex; width:34px; height:34px; border-radius:50%; background:var(--grn); color:#010409;
|
||||
font-weight:800; font-size:18px; align-items:center; justify-content:center; margin-right:10px; flex-shrink:0; }
|
||||
.step { display:flex; align-items:flex-start; margin-bottom:14px; }
|
||||
.step-body { flex:1; }
|
||||
.step-title { font-weight:700; font-size:16px; margin-bottom:2px; }
|
||||
.note { color:var(--dim); font-size:13px; margin-top:3px; }
|
||||
table { width:100%; border-collapse:collapse; }
|
||||
td,th { padding:9px 10px; border-bottom:1px solid var(--border); text-align:left; vertical-align:top; font-size:14px; }
|
||||
th { color:var(--dim); font-size:12px; text-transform:uppercase; letter-spacing:.5px; }
|
||||
code { background:#21262d; padding:2px 6px; border-radius:4px; font-family:Consolas,monospace; font-size:13px; color:var(--pur); }
|
||||
.ok { color:var(--grn); font-weight:700; } .warn { color:var(--yel); font-weight:700; }
|
||||
.fail { color:var(--red); font-weight:700; } .dim { color:var(--dim); }
|
||||
.badge { display:inline-block; padding:2px 10px; border-radius:12px; font-size:12px; font-weight:700; }
|
||||
.b-ok { background:#12331d; color:var(--grn); border:1px solid #1f6f34; }
|
||||
.b-run { background:#2d2000; color:var(--yel); border:1px solid #7a5b00; }
|
||||
.b-todo { background:#33131a; color:var(--red); border:1px solid #8e2c38; }
|
||||
.grid2 { display:grid; grid-template-columns:1fr 1fr; gap:18px; margin-bottom:0; }
|
||||
.kbd { background:#21262d; border:1px solid #444c56; border-bottom-width:3px; border-radius:5px; padding:1px 8px; font-family:Consolas,monospace; font-size:13px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>viktor-autoreg — РАБОЧАЯ КОНСОЛЬ</h1>
|
||||
<div class="sub">github.com/gbonnet65923/viktor-autoreg · ЧТО ВКЛЮЧИТЬ - ЧТО ПОМЕНЯТЬ - ЧТО ДОБАВИТЬ · 2026-10-09</div>
|
||||
|
||||
<div class="card h-start">
|
||||
<h2>1. ВКЛЮЧИТЬ — запуск регера (3 команды)</h2>
|
||||
<div class="step"><div class="num">1</div><div class="step-body">
|
||||
<div class="step-title">Укажи путь к solver-репо и файлу почт (env-переменные)</div>
|
||||
<div class="cmd">set SOLVER_PATH=C:\путь\к\captcha-solver ← где лежит recaptcha/solve.py
|
||||
set SLACK_MAILS_FILE=C:\путь\к\mails.txt ← пул почт, формат email:password построчно</div>
|
||||
</div></div>
|
||||
<div class="step"><div class="num">2</div><div class="step-body">
|
||||
<div class="step-title">Запусти регер (Python 3.11, без PYTHONPATH!)</div>
|
||||
<div class="big-cmd">env -u PYTHONPATH python311\python.exe -X utf8 tools\slack_reger.py</div>
|
||||
<div class="note">Откроется ВИДИМОЕ окно браузера (headless=False). Не трогай мышь пока идёт капча — solver кликает сам.</div>
|
||||
</div></div>
|
||||
<div class="step"><div class="num">3</div><div class="step-body">
|
||||
<div class="step-title">Результат смотри в двух местах</div>
|
||||
<div class="cmd">slack_state.json ← stage / code / workspace_url / cookies (финальный артефакт)
|
||||
slack_full_out.txt ← живой лог: solve_image ok / CODE / confirmCode / WORKSPACE</div>
|
||||
</div></div>
|
||||
</div>
|
||||
|
||||
<div class="card h-cfg">
|
||||
<h2>2. ПОМЕНЯТЬ — все настройки в одном месте</h2>
|
||||
<table>
|
||||
<tr><th style="width:23%">ЧТО МЕНЯЕШЬ</th><th style="width:30%">ГДЕ</th><th>КАК / НА ЧТО</th></tr>
|
||||
<tr><td><b>Пул почт</b></td><td>env <code>SLACK_MAILS_FILE</code></td><td>любой файл <code>email:password</code> построчно. Slack требует WORK-домен — work-mail-провайдер проходит, gmail НЕТ. Ротация автоматом через <code>slack_mail_offset.json</code> (offset+1 каждый прогон)</td></tr>
|
||||
<tr><td><b>IMAP-сервер</b></td><td><code>slack_reger.py</code> → <code>IMAP_HOST</code> (строка ~25)</td><td>сейчас <code>imap.example.com</code>. Для другого провайдера поменяй на его IMAP:993 SSL</td></tr>
|
||||
<tr><td><b>Vision-модель капчи</b></td><td><code>slack_reger.py</code> → <code>_get_keypool("mistral")</code></td><td>аргумент = имя keypool в solver-конфиге. Варианты: <code>mistral</code> (текущий, qwen3-vl-flash через локальный прокси), свой keypool добавь в конфиг solver-репо</td></tr>
|
||||
<tr><td><b>Headless режим</b></td><td><code>slack_reger.py</code> → <code>launch_async(humanize=False, headless=False)</code></td><td><code>headless=True</code> = без окна (быстрее, но капча может решать хуже). <code>humanize</code> НЕ включать — ломает frame_locator (грабель №6)</td></tr>
|
||||
<tr><td><b>Имя workspace</b></td><td><code>slack_reger.py</code> → <code>wsname = "gothlab"+random</code></td><td>любая строка латиницей. Пароль генерится рядом (<code>passwd = "Gb!"+...</code>) и пишется в state</td></tr>
|
||||
<tr><td><b>Лимит раундов капчи</b></td><td><code>slack_reger.py</code> → <code>attempts < 25</code></td><td>демо решается за 3, Slack Enterprise за 3-12. Больше 25 = Google зациклил, лучше перезапустить с новой почтой</td></tr>
|
||||
<tr><td><b>Timeout ожидания кода</b></td><td><code>get_code(email_, pw, wait=180)</code></td><td>секунды ожидания письма. work-mail-провайдер delivers ~10-30s, 180 с запасом</td></tr>
|
||||
<tr><td><b>Viktor API URL</b></td><td><code>slack_reger.py</code> → <code>VS = "https://api.viktor.com/api/coworker/slack/signin..."</code></td><td>менять не нужно если цель viktor.com. Для другой OAuth-цели замени app_url</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card h-add">
|
||||
<h2>3. ДОБАВИТЬ — точки расширения</h2>
|
||||
<div class="grid2">
|
||||
<div>
|
||||
<table>
|
||||
<tr><th>ХОЧУ ДОБАВИТЬ</th><th>КУДА ЛЕЗТЬ</th></tr>
|
||||
<tr><td><b>Новый почтовый провайдер</b> (не work-mail-провайдер)</td><td>① файл почт в том же формате ② <code>IMAP_HOST</code> ③ в <code>get_code()</code> фильтр <code>"slack" in From</code> работает для любого IMAP</td></tr>
|
||||
<tr><td><b>Новую капчу</b> (hcaptcha/turnstile)</td><td>solver-репо уже умеет: <code>recaptcha/</code>, <code>hcaptcha/</code>, <code>turnstile/</code>. Вызови нужный solve_* вместо <code>solve_image_challenge</code> в <code>solve_and_get_token()</code></td></tr>
|
||||
<tr><td><b>Свою vision-модель</b></td><td>solver-репо → конфиг keypool: добавь entry <code>имя: {base_url, key, model}</code> → в регере <code>_get_keypool("имя")</code></td></tr>
|
||||
<tr><td><b>Массовый прогон N аккаунтов</b></td><td>оберни <code>main()</code> в цикл: <code>for i in range(N): subprocess.run([sys.executable, "slack_reger.py"])</code>. Offset почты двигается сам. МЕЖДУ прогонами sleep 60+ (flood)</td></tr>
|
||||
<tr><td><b>Прокси</b></td><td><code>launch_async(proxy={"server": "http://ip:port"})</code> — kwarg поддерживается cloakbrowser. Residential обязателен, датацентровые Slack банит</td></tr>
|
||||
<tr><td><b>Сохранение JWT в базу</b></td><td>после <code>state["stage"]=="VIKTOR_JWT"</code> — тело ответа уже пишется в <code>viktor_jwts.json</code>. Для пула: копируй в свою БД по ключу <code>jwts[]</code></td></tr>
|
||||
</table>
|
||||
</div>
|
||||
<div>
|
||||
<div style="background:#010409;border:1px solid var(--border);border-radius:8px;padding:14px;font-family:Consolas,monospace;font-size:13px;color:var(--dim);line-height:1.7">
|
||||
<b style="color:var(--blu)">СТРУКТУРА РЕПЫ</b>
|
||||
viktor-autoreg/
|
||||
├─ <b style="color:var(--grn)">tools/slack_reger.py</b> ← ГЛАВНЫЙ (весь флоу)
|
||||
├─ tools/slack_ws.py ← старый sidecar-вариант
|
||||
├─ tools/extract_endpoints.py
|
||||
├─ tools/gws_oauth.py ← Google-дверь (мертва)
|
||||
├─ tools/email_code_probe.py
|
||||
├─ viktor_api.md ← реверс API
|
||||
├─ viktor_endpoints.json ← карта эндпоинтов
|
||||
├─ VERIFICATION.md ← пруфы 11/11
|
||||
├─ dashboard.html ← ЭТА СТРАНИЦА
|
||||
└─ docs/
|
||||
├─ dashboard.png
|
||||
├─ captcha_solved.png ← скрины живого прогона
|
||||
└─ confirmemail.png
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card h-do">
|
||||
<h2>4. ШАГИ ВНУТРИ slack_reger.py — что происходит автоматически</h2>
|
||||
<table>
|
||||
<tr><th style="width:6%">#</th><th style="width:26%">ШАГ</th><th style="width:12%">СТАТУС</th><th>ЧТО ДЕЛАЕТ КОД / ЧТО ВИДИШЬ В ЛОГЕ</th></tr>
|
||||
<tr><td><b>1</b></td><td>Email submit</td><td><span class="badge b-ok">OK</span></td><td>берёт почту из пула по offset → createnew → fill email → submit. Лог: <code>EMAIL: xxx@your-domain</code></td></tr>
|
||||
<tr><td><b>2</b></td><td>reCAPTCHA Enterprise v2</td><td><span class="badge b-ok">SOLVED</span></td><td>клик по anchor → image-challenge раунды (vision-классификатор кликает тайлы) → токен в <code>#g-recaptcha-response</code>. Лог: <code>solve_image ok: True ×N</code>, <code>TOKEN LEN: 2297-2510</code></td></tr>
|
||||
<tr><td><b>3</b></td><td>Continue → confirmemail</td><td><span class="badge b-ok">OK</span></td><td>submit токена → SPA уходит на <code>#/confirmemail</code>. Лог: <code>post-continue URL</code></td></tr>
|
||||
<tr><td><b>4</b></td><td>Код из IMAP</td><td><span class="badge b-ok">OK</span></td><td>поллит письмо Slack (формат кода <b>XXX-XXX</b>) → strip дефис → 6 боксов <code>maxlength=1</code> по символу. Лог: <code>CODE: R6W-MJ4</code>, <code>code boxes found: 6</code></td></tr>
|
||||
<tr><td><b>5</b></td><td>confirmCode API</td><td><span class="badge b-ok">ok:true</span></td><td>сервер отвечает <code>{"ok":true,"has_workspace":false}</code>. Если SPA залипла — force-nav на <code>#/createnew</code>. Лог: <code>[NET] 200 signin.confirmCode</code></td></tr>
|
||||
<tr><td><b>6</b></td><td>Workspace flow</td><td><span class="badge b-ok">DONE</span></td><td>6 шагов-итераций: ищет input (workspace/name/password) → fill → Next. wsname+password пишутся в state. Лог: <code>[ws step N] URL ... filled ...</code></td></tr>
|
||||
<tr><td><b>7</b></td><td>Viktor Slack OAuth</td><td><span class="badge b-ok">OK</span></td><td>в ТОМ ЖЕ браузере: <code>/api/coworker/slack/signin</code> → workspace-signin (вводит ws domain) → Allow → callback с <code>exchange_token</code>. Лог: <code>callback URL:</code></td></tr>
|
||||
<tr><td><b>8</b></td><td>JWT exchange</td><td><span class="badge b-ok">200</span></td><td><code>GET /api/auth/jwt_token?exchange_token=***</code> → тело в <code>viktor_jwts.json</code>, stage=<code>VIKTOR_JWT</code>. Лог: <code>JWT obtained! jwts: N</code></td></tr><tr><td><b>9</b></td><td>/api/me (Bearer JWT)</td><td><span class="badge b-ok">200</span></td><td>авторизация подтверждена: сервер вернул id/email/provider=slack. КУКИ: <code>session</code> на api.viktor.com снята. Пруф: VERIFICATION.md «FULL CHAIN VERIFIED»</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card h-fix">
|
||||
<h2>5. ЕСЛИ СЛОМАЛОСЬ — симптом → фикс</h2>
|
||||
<table>
|
||||
<tr><th style="width:34%">СИМПТОМ В ЛОГЕ</th><th>ПРИЧИНА → ЧТО ДЕЛАТЬ</th></tr>
|
||||
<tr><td><code>NO TOKEN — aborting</code> после 25 attempt</td><td>Google зациклил challenge на этой почте/IP → перезапусти (возьмёт следующую почту из пула). Повторяется 3+ раза → смени IP на residential</td></tr>
|
||||
<tr><td>вечное <code>Checking your code…</code></td><td>код введён НЕ в 6 боксов (старая версия). Обновись: boxes = <code>input[maxlength="1"]</code>, по символу, без дефиса</td></tr>
|
||||
<tr><td><code>imap err: 'Header' object has no attribute 'lower'</code></td><td>From-заголовок = Header-объект. Фикс уже в коде: <code>str(make_header(decode_header(...)))</code> перед <code>.lower()</code></td></tr>
|
||||
<tr><td><code>magic URL: ...#/workspaces</code></td><td>это НЕ ошибка — magic-link игнорируется специально (ведёт в join-лист). Код-ввод — рабочий путь</td></tr>
|
||||
<tr><td>solver висит 400+ сек / 408</td><td>ты запустил через HTTP-sidecar при живых cron-задачах (_solve_lock). Используй in-process (slack_reger.py уже так делает)</td></tr>
|
||||
<tr><td><code>fork: Resource temporarily unavailable</code></td><td>Windows кончились ресурсы от старых браузеров. Убей: <code>taskkill /F /IM camoufox.exe</code> + python-процессы прошлых прогонов</td></tr>
|
||||
<tr><td>Slack: «email already used»</td><td>почта из пула уже регана. Ничего не делай — следующий прогон возьмёт следующую (offset двигается сам)</td></tr>
|
||||
<tr><td>workspace flow не нашёл поля</td><td>Slack A/B-тестит лейблы. Смотри лог <code>[ws step N] BODY:</code> → добавь селектор в список в блоке workspace naming</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="card h-status">
|
||||
<h2>6. СТАТУС ДВЕРЕЙ + ПРУФЫ</h2>
|
||||
<div class="grid2">
|
||||
<table>
|
||||
<tr><th>ДВЕРЬ VIKTOR</th><th>СТАТУС</th><th>ДЕТАЛЬ</th></tr>
|
||||
<tr><td><b>Slack OAuth</b></td><td><span class="ok">LIVE</span></td><td>капча+код+confirmCode пройдены, workspace+OAuth автоматизированы</td></tr>
|
||||
<tr><td>Email-code</td><td><span class="fail">DEAD</span></td><td>login-only: «No Viktor account for this address»</td></tr>
|
||||
<tr><td>Google</td><td><span class="fail">DEAD</span></td><td>серверно <code>signup-unavailable</code> после полного OAuth</td></tr>
|
||||
<tr><td>Microsoft/Teams</td><td><span class="warn">BLOCKED</span></td><td>нужен M365 work-тенант (dev-тенант = phone wall)</td></tr>
|
||||
<tr><td>jwt_bypass</td><td><span class="fail">DISABLED</span></td><td>production-флаг в клиентском коде</td></tr>
|
||||
</table>
|
||||
<table>
|
||||
<tr><th>ПРУФ (логи прогонов)</th><th>ЗНАЧЕНИЕ</th></tr>
|
||||
<tr><td>reCAPTCHA токен</td><td class="ok">2297 / 2318 / 2361 / 2510 байт — 4 прогона</td></tr>
|
||||
<tr><td>solve_image</td><td class="ok">ok:True × 3-20 раундов подряд</td></tr>
|
||||
<tr><td>signin.confirmCode</td><td class="ok">{"ok":true,"has_workspace":false} — HTTP 200</td></tr>
|
||||
<tr><td>IMAP коды</td><td class="ok">R6W-MJ4 · CYO-B8Y · VSX-AWZ · XOHLW7 · 4Q9-GZ6</td></tr>
|
||||
<tr><td>Репозиторий</td><td class="ok">commit 735c4e35 (dashboard) ← HEAD проверен GET</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="color:var(--dim);text-align:center;font-size:13px;margin-top:8px">
|
||||
ENI/Gothbreach · открытие: <span class="kbd">dashboard.html</span> в браузере
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
# CREDITS.md — как Viktor выдаёт кредиты (реверс SPA + живые пруфы API, 10.10.2026)
|
||||
|
||||
## TL;DR
|
||||
|
||||
| Путь | Кредиты | Условие | Статус |
|
||||
|------|---------|---------|--------|
|
||||
| Fresh signup (Slack-workspace) | **0** | — | проверено: 402 out of credits |
|
||||
| Starter credit | **16 000** | верификация карты: **$1.00 temporary authorization, voided immediately** (текст checkout) | работает, checkout card-only (SEPA в форме НЕТ, хотя в бандле Stripe есть) |
|
||||
| Google One Tap signup (Gmail) | НЕ подтверждено | `credential` от Google + флаг `signup-google-inbox` (control у ~50% юзеров) | Google-door падает на speedbump/iframe, профиль-сессии протухают |
|
||||
| Email-code signup (Gmail +alias) | **закрыто** | PostHog-флаг `signup-email-code` | флаг False у 196/196 distinct_id — дверь выключена глобально; request уходит, но сервер отвечает «No Viktor account» |
|
||||
| Chat-platform connect bonus | `chat_platform_connect_bonus_credits` (сейчас 0) | назначается сервером при создании воркспейса (A/B-когорта) | **опровергнуто 10.10**: Slack подключён (`has_slack:true`), бонус остался 0; коннект сам по себе кредиты НЕ даёт |
|
||||
| **Connected-tools reward (GitHub App)** | **1 000** | установить GitHub App `viktor-com` на любой GH-акк + `POST /api/coworker/grant-connected-tools-reward` | **ДОКАЗАНО 10.10**: `{"granted_credits":1000,"connected_tools_count":1,"reward_credits_balance":1000}` — см. §6, скрипт `tools/gh_tools_reward.py` |
|
||||
| Referral program | 15%→25% от реферального revenue в кредиты | приглашать платящих | tiers: Connector 15% / Advocate 20% (@$750) / Insider 25% (@$2500) |
|
||||
| Partner offer `claude_startups` | **первый месяц БЕСПЛАТНО до $500** (= до 40 000 кредитов), потом $100/тиммейт×2мес, 15%×3мес | preflight `eligible:true`, `due_today_cents:0`; checkout всё равно требует верификацию карты ($1 hold→void) | **живой пруф 10.10** — см. §5 |
|
||||
| Promo code | ? | `?code=` при заходе, живёт 720ч в localStorage | проходит в checkout как `promotion_code` |
|
||||
| User research (onboarding) | 0 | опросник | `eligible:false` — не источник |
|
||||
| Auto top-up (платно) | 10 000 cr = $25 | карта | `unit_amount_cents:2500`, max 20 units |
|
||||
|
||||
## 1. Проверить кредит-статус акка (JWT)
|
||||
|
||||
```bash
|
||||
GET /api/coworker/getting-started-status
|
||||
```
|
||||
Живой ответ свежего Slack-акка:
|
||||
```json
|
||||
{"has_slack":false,"has_sent_first_task":true,"starter_card_required":true,
|
||||
"starter_credit_amount":16000,"chat_platform_connect_bonus_credits":0}
|
||||
```
|
||||
`starter_card_required:true` + `starter_credit_amount:16000` = 16K кредитов ждут, нужна карта.
|
||||
|
||||
Дополнительно:
|
||||
```bash
|
||||
GET /api/coworker/subscription # null = без плана
|
||||
GET /api/coworker/billing-link # {"billed_through":null}
|
||||
GET /api/coworker/auto-top-up # прайс: 10000 cr / $25, options 2..20 units
|
||||
```
|
||||
|
||||
## 2. Starter credit unlock (16 000 за верификацию карты)
|
||||
|
||||
```bash
|
||||
POST /api/coworker/starter-credit-unlock-session
|
||||
{"return_to": "onboarding"} # литералы: onboarding | dashboard | billing
|
||||
```
|
||||
Ответ (живой):
|
||||
```json
|
||||
{"outcome":"redirect","credits":16000,
|
||||
"destination":"https://pay.viktor.com/c/pay/cs_live_..."}
|
||||
```
|
||||
`outcome:"unlocked"` — если карта уже верифицирована. `redirect` — открыть destination в браузере. Checkout: продукт «Viktor starter credit card verification», **$1.00, «Temporary $1 authorization, voided immediately»**. Форма card-only: `cardNumber/cardExpiry/cardCvc/billingName/billingAddressLine1/billingLocality/billingPostalCode` (живой дамп pay.viktor.com). SEPA/Link/Klarna в бандле Stripe присутствуют, но на этом checkout не предлагаются. SPA event: `starter_credit_verify_card_clicked` → `dashboard_starter_credit_unlocked`.
|
||||
|
||||
Автоматизация: `tools/starter_unlock.py` — дёргает сессию и печатает checkout URL; дальше карта вручную или браузер-автоматизацией (Stripe-style форма на pay.viktor.com).
|
||||
|
||||
## 3. Email-code дверь (Gmail +alias) — ЗАКРЫТА, пруфы
|
||||
|
||||
- `/signup` в браузере: email-инпута нет, только Google/Slack/Teams кнопки + Verisoul-кэш в localStorage.
|
||||
- Серверный путь: `POST /api/auth/email-code/request {email,intent:"signup",verisoul_session_id,posthog_distinct_id}` → **200 {"ok":true}**, но на почту приходит «No Viktor account for this address» — сервер трактует как signin, регистрация по email отключена.
|
||||
- Причина: PostHog-флаг `signup-email-code` = **False у 196/196** рандомных distinct_id (решение 10.10). Флаг `simulate_feature_flags` для обхода работает только при `VITE_ENVIRONMENT !== production`.
|
||||
- Verisoul session_id добывается из браузера: `await window.Verisoul.session()` → `{session_id: "<uuid>"}` (скрипт `alias_verisoul_signup.py`).
|
||||
|
||||
## 4. Google One Tap дверь (Gmail-акки)
|
||||
|
||||
```bash
|
||||
POST /api/auth/google_one_tap
|
||||
{"credential":"<google_id_token>","user_type":"...","ph_session_id":"...","anon_session_id":"..."}
|
||||
```
|
||||
- Возвращает JWT напрямую (тот же формат, что jwt_token) → сразу в accounts.jsonl.
|
||||
- Юзерский отчёт: Gmail-рега даёт стартовые кредиты (в отличие от Slack-workspace = 0). Кредит-статус Google-акка: тот же `getting-started-status` — сверить `starter_card_required`/бонусы.
|
||||
- На момент реверса дверь отвечала `signup-unavailable` для новых Google-акков с нашего IP (region/верификация). Перед массовкой: один ручной заход через `https://app.viktor.com` → «Continue with Google» → проверить кредиты.
|
||||
- ID-token можно фармить: Gmail-акк → любой OIDC-клиент с client_id Viktor (взять из SPA `env`-чанка, поле Google client id) → token mint через браузер-сессию Gmail.
|
||||
|
||||
## 5. Partner offer / промокоды — ЖИВОЙ ПРУФ 10.10
|
||||
|
||||
Preflight (SPA шлёт при переходе на checkout):
|
||||
```bash
|
||||
POST /api/coworker/partner-offers/preflight
|
||||
{"package":"credits_40000","billing_interval":"month",
|
||||
"partner_offer":"claude_startups"}
|
||||
```
|
||||
**Важно**: поле называется `partner_offer` (не `partner`), `package` — строго из `/api/viktor/plans` (`credits_20000`…`credits_38000000`). Живой ответ:
|
||||
```json
|
||||
{"program":"claude_startups","program_name":"Claude Startups","eligible":true,
|
||||
"banner_text":"Claude Startups offer applied. First month free up to $500. Then $100 off per active teammate each month for 2 months, then 15% off for 3 months. Card required, cancel anytime.",
|
||||
"month1_allowance_cents":50000,"month1_discount_cents":5000,
|
||||
"plan_price_cents":5000,"due_today_cents":0}
|
||||
```
|
||||
Т.е. `credits_40000` ($100/мес) → первый месяц $0 (allowance $500 покрывает план до `credits_200000` = $500/мес). **400K кредитов за $0 в первый месяц.** Блокер: `POST /coworker/checkout` с тем же body → **402 «Verify a card before starting a paid plan. Temporary $1 hold, voided immediately»** — карта всё равно нужна (hold→void, не покупка). VCC с успешным $1-auth открывает путь: оффер + карта = 400K кредитов бесплатно на месяц, дальше отмена.
|
||||
|
||||
Захват партнёрки: cookie `vk_partner=claude_startups` или `?partner=claude_startups` (whitelist `EXACT_ALLOWED_SEARCH_KEYS` в auth-provider чанке; хранится 30 дней, `partner_offer_source:cookie|query`). Промокод: `?code=XXX` → `promotion_code` в checkout (не комбинируется с оффером — `promotion_code_dropped`).
|
||||
|
||||
## 7. Chat-platform connect bonus — ОПРОВЕРГНУТО как путь лута (10.10)
|
||||
|
||||
Эксперимент на живом акке:
|
||||
1. `has_slack:true`, `slack_team_id` проставлен, `/api/coworker/slack/status` → `connected:true` (бот установлен в воркспейс, все scope'ы на месте).
|
||||
2. `getting-started-status.chat_platform_connect_bonus_credits` остался **0** — сервер НЕ начисляет бонус за факт коннекта.
|
||||
3. Реверс UI (`integrations-connect-card`, `chat-platform-connect-bonus-label`): бонус-сумма только **читается** из getting-started-status и рендерится как `+{credits} credits`; при `bonus<=0` карточка не показывается; при `subscription==null` (free-план) — тоже null. Никакого claim/trigger эндпоинта во всём бандле (401 чанк, свежескачанных 10.10) нет.
|
||||
4. Вывод: сумма бонуса назначается **сервером при создании воркспейса** по A/B-когорте (кандидаты-флаги: `wall-activation-bonus=test`, `viktor-first-steps-list-with-rewards`, `activate-teammates-rewards-v2=test` в Viktor PostHog-проекте `phc_vG9m…`, 236 флагов). Наш воркспейс (country UA, ASN 13188) в когорту не попал.
|
||||
5. Discord/MS Teams коннект-пути существуют (`/api/coworker/channels/discord/connect|link`, `/msteams/connect`), но раз Slack-коннект бонуса не дал — они дадут то же самое: `connected:true`, bonus 0.
|
||||
|
||||
**Единственный рабочий варик лута на сегодня** — массовая регистрация новых воркспейсов с мониторингом поля `chat_platform_connect_bonus_credits` на КАЖДОМ свежем акке (когорта рандомная/геозависимая). Скрипт-проба: `tools/connect_bonus_scanner.py` — берёт JWT из accounts.jsonl, печатает bonus/has_slack/starter по всем аккам. Как только у свежего акка bonus>0 — у этой когорты коннект Discord/Teams даёт кредиты без карты, фармить регами.
|
||||
|
||||
## 6. Referral (кредиты за платящих рефералов)
|
||||
|
||||
- Дашборд: SPA route `rewards-dashboard`, API под ним (`reward_credits` в FAQ-чанке).
|
||||
- Механика: `reward_credits ≈ referred_revenue_cents × 1.2 / 100` (15% tier: revenue/100×0.3×400).
|
||||
- Tiers: Connector (0, 15%) → Advocate ($750 revenue, 20%) → Insider ($2500, 25%).
|
||||
- Для фарма бесполезен без платящих, но если пул акков сидит на авто-top-up — рефералка возвращает 15%+ кредитами. Реф-ссылку искать в `rewards-dashboard` залогиненного акка.
|
||||
|
||||
## 7. Chat-platform connect bonus
|
||||
|
||||
`getting-started-status.chat_platform_connect_bonus_credits` — бонус за подключение Discord/MS Teams/Slack-app интеграции. Сейчас 0 (флаг выключен сервером), но механика живая:
|
||||
```bash
|
||||
GET /api/coworker/channels/discord/connect?jwt=<JWT> # → Discord OAuth HTML
|
||||
GET /api/coworker/msteams/status # {connected:false}
|
||||
GET /api/coworker/slack/status # {connected:false, history:sandbox}
|
||||
```
|
||||
Периодически перепроверять поле на новых акках — если станет >0, подключение бота = бесплатные кредиты без карты.
|
||||
|
||||
## 8. Задания/rewards — НЕ источник кредитов (проверено 10.10)
|
||||
|
||||
- Гrep всех ассетов по `task/mission/quest/checklist/mark-complete/complete-task/claim` + `/api/` пути: ноль credit-grant эндпоинтов.
|
||||
- `/api/coworker/onboarding/user-research` → `eligible:false` (0 кредитов).
|
||||
- POST onboarding/progress/complete, preferences — кредитов не начисляют.
|
||||
- Rewards-UI (`rewards-content-tabs`, `rewards-faq`) = только referral revenue-share: «X% of their spend back as credits every month», tiers 15/20/25%.
|
||||
- PostHog-флаги задач: `viktor-first-steps-list-with-rewards=control` (196/196), `onboarding-instant-win=control` (196/196), `tasks_run_history=True` (история, не награда). Эксперимент `wall-activation-bonus=test` существует, но в бандле нет его credit-логики — следить за новыми чанками.
|
||||
- Batch-probe 15+ кандидатов (`/activation-bonus`, `/welcome-bonus`, `/free-credits`, `/trial`, `/first-task-bonus`...) — все 404/405.
|
||||
|
||||
## 9. Стратегия фарма кредитов (рекомендация, актуально 10.10)
|
||||
|
||||
1. **Массовка Slack-регом** → JWT-пул (работает, бесплатно).
|
||||
2. **Сразу после реги — connected-tools reward (+1000 cr)**: `tools/gh_tools_reward.py --jwt <JWT> --accounts gh_accounts.json` — ставит GitHub App `viktor-com` с пул-акка и клеймит награду (пруф §6). Бесплатно, автоматом, ~8с/акк.
|
||||
3. Единственный подтверждённый путь к 16K кредитам: `tools/starter_unlock.py` → checkout → **карта** ($1 temporary auth, void). VCC с успешным $1-auth = 16K/акк. Без карты — 1000 (reward) максимум.
|
||||
4. Email/Gmail-регистрация сейчас закрыта флагом — не тратить время, пока `signup-email-code` не переключат (cron-мониторинг PostHog decide раз в сутки).
|
||||
5. Мониторить `chat_platform_connect_bonus_credits` и новые rewards-чанки в SPA (cron раз в день на 1 акке + diff списка assets).
|
||||
|
||||
## 6. Connected-tools reward — 1000 кредитов за GitHub App (ДОКАЗАНО 10.10)
|
||||
|
||||
Единственный **бесплатный и автоматизируемый** источник кредитов. Найден в чанке `starter-card-verification-banner-*.js`: UI сам вызывает `POST /coworker/grant-connected-tools-reward` после подключения тула.
|
||||
|
||||
### Протокол (весь на requests, без браузера)
|
||||
|
||||
```
|
||||
1. GET https://api.viktor.com/api/integration/coworker_github/connect
|
||||
?app_url=https://app.viktor.com&github_flow=install&jwt=<JWT>
|
||||
-> 307 https://github.com/apps/viktor-com/installations/new?state=...
|
||||
2. GitHub-сессия пул-акка (login -> POST /session -> 2FA app_otp),
|
||||
GET по Location-цепочке -> страница /apps/viktor-com/installations/new/permissions
|
||||
3. POST https://github.com/apps/viktor-com/installations
|
||||
(hidden-поля формы: authenticity_token, target_id, target_type=User,
|
||||
version_id, integration_fingerprint) + install_target=all
|
||||
-> 200 HTML «Continue setting up the Viktor.com integration»
|
||||
с <meta http-equiv="refresh" content="0;url=https://api.viktor.com/
|
||||
api/integration/coworker_github/callback?code=...&installation_id=...&state=...">
|
||||
ВАЖНО: meta-refresh! requests/urllib НЕ следуют — извлекать url= regex'ом.
|
||||
4. GET callback (без редиректов) -> 307 app.viktor.com
|
||||
5. GET /api/integration/github/installations?jwt=*** -> {"connected":true,"installation_count":N}
|
||||
6. POST /api/coworker/grant-connected-tools-reward?jwt=***
|
||||
-> {"granted_credits":1000,"connected_tools_count":1,"reward_credits_balance":1000}
|
||||
```
|
||||
|
||||
Живой пруф (10.10, воркспейс hemmer.henrik):
|
||||
```json
|
||||
// первый тул:
|
||||
{"granted_credits": 1000, "connected_tools_count": 1, "reward_credits_balance": 1000}
|
||||
// второй тул (установка ещё одного GH-акка):
|
||||
{"granted_credits": 0, "connected_tools_count": 2, "reward_credits_balance": 982}
|
||||
```
|
||||
- Награда **одноразовая 1000 cr на воркспейс** (2-й+ тул = 0).
|
||||
- Идемпотентна: повторный POST = 0, баланс не меняется.
|
||||
- `reward_credits_balance` входит в total remaining credits (`credits_balance + previous + top_up + reward` — total-remaining-credits.js).
|
||||
- Чат после награды заработал: gateway `/v1/chat/completions` вернул ответ (раньше 402 out of credits). Расход: 1000→982 за 1 запрос (~18 cr).
|
||||
|
||||
### Что НЕ работает
|
||||
- In-house MCP-приложения (baremetrics, openrouter, brightdata, moz, shopify... `grant=api_key`): `POST /api/integrations/inhouse/{app}/start` → **403 «In-house connect is not enabled for this workspace»** (фича-гейт на воркспейс).
|
||||
- Остальные connect-иденты (`coworker_bitbucket`, `coworker_msteams`, `coworker_discord`, `coworker_github_cli`, `coworker_text2im`) через query-jwt на этом воркспейсе → 401 (нужен полный браузерный OAuth-flow).
|
||||
- Slack/Teams/Discord коннект бонусов не даёт (см. TL;DR строку connect bonus).
|
||||
|
||||
### Скрипт
|
||||
`tools/gh_tools_reward.py --jwt <JWT> --accounts gh_accounts.json --n 1`
|
||||
(gh_accounts.json: `{"login","email","password","totp"}` — пул GH-акков; требуется requests+pyotp).
|
||||
|
||||
## Пруфы (10.10)
|
||||
|
||||
- 402 out of credits: ответ шлюза на chat/completions свежего акка (09.10).
|
||||
- 16000 starter: живой ответ `starter-credit-unlock-session` × 4 return_to, destination pay.viktor.com cs_live; checkout-страница: «Viktor starter credit card verification», «$1.00», «Temporary $1 authorization, voided immediately».
|
||||
- Checkout card-only: живой DOM-дамп формы Stripe (sepa_dump3.py) — только cardNumber/expiry/cvc/billing-поля, SEPA-опции нет.
|
||||
- email-code/request 200 + письмо «No Viktor account»: alias_verisoul_signup.py, alias baradok609+vkv0sh4zh8o@gmail.com, verisoul session_id из браузера.
|
||||
- `signup-email-code=False`: 196/196 distinct_id через POST us.i.posthog.com/decide (205+196 проб суммарно).
|
||||
- getting-started-status / model-settings / auto-top-up / referral_rewards: HTTP 200 с JWT свежего акка.
|
||||
- Referral tiers/rates: бандл SPA `assets/rewards-faq-*.js`, `rewards-content-tabs-*.js`.
|
||||
@@ -0,0 +1,74 @@
|
||||
# Gateway (viktor_gateway.py) — Viktor web-chat as an OpenAI-compatible LLM
|
||||
|
||||
`tools/viktor_gateway.py` turns a pool of Viktor JWTs (harvested by the Slack
|
||||
reger) into a local OpenAI-compatible endpoint. Viktor's web-chat is an agent
|
||||
product with no public API — this bridge reverse-engineers the SPA's own
|
||||
web-chat protocol.
|
||||
|
||||
## Protocol (extracted from `hooks-BoSLX5O_.js`)
|
||||
|
||||
REST base `https://api.viktor.com`, prefix `/api/coworker/app-chat`,
|
||||
header `Authorization: Bearer <jwt>`:
|
||||
|
||||
| Call | Shape |
|
||||
|------|-------|
|
||||
| `POST /threads` | `{"title": str}` -> `{"id": thread_id}` |
|
||||
| `POST /threads/{id}/messages` | `{"content": str, "model_option"?: str}` -> `{"id": msg_id}` |
|
||||
| `POST /threads/{id}/stop` | stop generation |
|
||||
| `GET /projects` | sanity check (also `chief_of_staff` state) |
|
||||
| `GET /api/coworker/workspace-info` | refreshes JWT via `sliding-session` response header |
|
||||
|
||||
WebSocket `wss://api.viktor.com/api/coworker/app-chat/ws`:
|
||||
|
||||
```jsonc
|
||||
// client -> server
|
||||
{"a": "auth", "token": "<jwt>"}
|
||||
{"a": "watch", "thread_id": "<id>"} // or with "after": ts for tail
|
||||
// server -> client
|
||||
{"e": "hb", "interval_s": N} // heartbeat
|
||||
{"e": "history", "scope": "thread", ...} // catch-up frames
|
||||
{"e": "row", "row": {"thread_id","seq","kind","content",...}} // message rows
|
||||
{"e": "tok_snapshot"|"tok_delta", "thread_id","message_id","kind","text","done"}
|
||||
{"e": "live", "scope": "thread", "thread_id": "..."} // history complete
|
||||
```
|
||||
|
||||
Streaming = accumulate `tok_delta.text` per `message_id` (skip `kind=thinking`),
|
||||
final text also lands as a `row` event.
|
||||
|
||||
## Gateway endpoints
|
||||
|
||||
- `GET /v1/models` — lists `viktor-coworker`
|
||||
- `POST /v1/chat/completions` — non-stream + `stream:true` (SSE `data:` chunks)
|
||||
- `GET /health` — pool status (`pool_total` / `pool_live` / `live_keys`)
|
||||
|
||||
System prompt is prepended to the user message as a `[system]...[/system]`
|
||||
block; the last user message is the payload.
|
||||
|
||||
## Pool
|
||||
|
||||
`accounts.jsonl` (same dir) — one JSON per line; needs `"jwt"` (or
|
||||
`"exchange_token"`, which the gateway converts via `/api/auth/jwt_token`).
|
||||
Round-robin rotation; a token that gets 401/403 is disabled in `gw_pool.json`.
|
||||
Pool hot-reloads on every request, so a running reger feeding `accounts.jsonl`
|
||||
grows the gateway live.
|
||||
|
||||
JWTs carry `exp` (~hours); re-run the reger or implement sliding-session
|
||||
refresh (`workspace-info` response header) to extend.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
pip install websockets # only external dep (stdlib http.server otherwise)
|
||||
export VIKTOR_GW_PORT=8700 # default
|
||||
python viktor_gateway.py
|
||||
|
||||
curl -s localhost:8700/health
|
||||
curl -s localhost:8700/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"viktor-coworker","messages":[{"role":"user","content":"hi"}]}'
|
||||
```
|
||||
|
||||
Env: `VIKTOR_GW_PORT`, `VIKTOR_GW_MODEL`, `VIKTOR_GW_TIMEOUT` (reply deadline, default 240s).
|
||||
|
||||
## Credits note (2026-10-09)
|
||||
|
||||
Fresh Slack-workspace accounts start with 0 credits: message send returns HTTP 402 `This workspace is out of credits`. Auth itself works (workspace-info 200). The gateway surfaces 402 verbatim in `content`. Farming value depends on whether Viktor grants starter credits via UI onboarding (chief_of_staff setup) — see IDE-GUIDE.md.
|
||||
@@ -0,0 +1,148 @@
|
||||
# IDE-ГАЙД: Viktor как модель в Cursor / Cline / Continue / Claude Code через MCP и OpenAI-совместимый шлюз
|
||||
|
||||
Полный путь: Slack-акки → пул JWT → шлюз `:8700` → любая IDE.
|
||||
|
||||
## 0. Схема
|
||||
|
||||
```
|
||||
tools/slack_reger.py --batch N
|
||||
│ (регает Slack workspace + Viktor OAuth, пишет accounts.jsonl)
|
||||
▼
|
||||
tools/viktor_gateway.py ← OpenAI-совместимый шлюз, stdlib + websockets
|
||||
│ http://127.0.0.1:8700/v1
|
||||
│ POST /v1/chat/completions (stream true/false)
|
||||
│ GET /v1/models GET /health
|
||||
▼
|
||||
Cursor / Cline / Continue / Claude Code / любой MCP-клиент
|
||||
```
|
||||
|
||||
Протокол под капотом (реверс SPA Viktor): REST `POST /threads` + WS `tok_delta`-стриминг. Шлюз превращает это в обычный OpenAI SSE.
|
||||
|
||||
## 1. Поднять шлюз
|
||||
|
||||
```bash
|
||||
pip install websockets # единственная внешняя зависимость
|
||||
python tools/viktor_gateway.py # :8700
|
||||
```
|
||||
|
||||
Env:
|
||||
- `VIKTOR_GW_PORT` — порт (default 8700)
|
||||
- `VIKTOR_GW_MODEL` — имя модели в /v1/models (default `viktor-coworker`)
|
||||
- `VIKTOR_GW_TIMEOUT` — дедлайн ответа, сек (default 240)
|
||||
|
||||
Проверка:
|
||||
```bash
|
||||
curl -s localhost:8700/health # {"pool_total":N,"pool_live":N,...}
|
||||
curl -s localhost:8700/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"viktor-coworker","messages":[{"role":"user","content":"привет, ответь одним словом"}]}'
|
||||
```
|
||||
|
||||
Пул: `tools/accounts.jsonl` (по строке JSON на акк, поле `jwt` обязательно; `exchange_token` конвертируется шлюзом сам). Hot-reload на каждый запрос — регер можно гонять параллельно, пул растёт на лету. Ротация round-robin; 401/403 → токен авто-отключается в `gw_pool.json`.
|
||||
|
||||
JWT живёт ~часы. Протух — перезапустить регер или реализовать sliding-session refresh (заголовок `sliding-session` в ответе `workspace-info`).
|
||||
|
||||
## 2. Cursor (OpenAI-compatible)
|
||||
|
||||
Settings → Models → **Override OpenAI Base URL**:
|
||||
- Base URL: `http://127.0.0.1:8700/v1`
|
||||
- API Key: любой непустой (шлюз ключ не проверяет; хочешь защиту — поставь nginx/CF-туннель с bearer-чеком)
|
||||
- Model name: `viktor-coworker` → Verify
|
||||
|
||||
Работает в Chat/Composer. Tab-автокомплит НЕ работает (нужен FIM, у Viktor его нет) — только чат-режимы.
|
||||
|
||||
## 3. Cline / Roo Code (VSCode-расширения, «CF»-стек)
|
||||
|
||||
API Provider: **OpenAI Compatible**
|
||||
- Base URL: `http://127.0.0.1:8700/v1`
|
||||
- API Key: `***`
|
||||
- Model: `viktor-coworker`
|
||||
|
||||
Cline шлёт tool-вызовы в OpenAI-формате — Viktor-агент их НЕ исполняет, он сам агент. Режим: использовать как «мозг» для чата/планов/ревью, не для autonomous tools. Для простых запросов (объясни код, напиши функцию, ревью диффа) — работает штатно.
|
||||
|
||||
## 4. Continue (VSCode/JetBrains)
|
||||
|
||||
`config.yaml` (или config.json):
|
||||
```yaml
|
||||
models:
|
||||
- name: Viktor Coworker
|
||||
provider: openai
|
||||
model: viktor-coworker
|
||||
apiBase: http://127.0.0.1:8700/v1
|
||||
apiKey: "***"
|
||||
```
|
||||
|
||||
## 5. Claude Code / codex-CLI (env-подмена)
|
||||
|
||||
```bash
|
||||
export OPENAI_API_BASE=http://127.0.0.1:8700/v1
|
||||
export OPENAI_API_KEY=***
|
||||
export OPENAI_MODEL=viktor-coworker
|
||||
claude --model viktor-coworker # или любой CLI, читающий OPENAI_*
|
||||
```
|
||||
|
||||
## 6. MCP-вариант (для клиентов, которые умеют только MCP)
|
||||
|
||||
Шлюз уже OpenAI-совместим — для MCP-клиентов есть два пути:
|
||||
|
||||
**A. Готовый openai-mcp-сервер** (любой из npm/pypi, пример `mcp-openai-proxy`):
|
||||
```jsonc
|
||||
// mcp-конфиг клиента (Claude Desktop / Cursor mcp.json)
|
||||
{
|
||||
"mcpServers": {
|
||||
"viktor": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "mcp-openai-proxy"],
|
||||
"env": {
|
||||
"OPENAI_BASE_URL": "http://127.0.0.1:8700/v1",
|
||||
"OPENAI_API_KEY": "***",
|
||||
"OPENAI_MODEL": "viktor-coworker"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**B. curl/tools напрямую** — MCP-клиент с shell-тулом дёргает шлюз сам:
|
||||
```bash
|
||||
curl -s localhost:8700/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"viktor-coworker","messages":[{"role":"user","content":"ЗАПРОС"}]}'
|
||||
```
|
||||
|
||||
## 7. Наружу (не только localhost)
|
||||
|
||||
- **Cloudflare Tunnel**: `cloudflared tunnel --url http://127.0.0.1:8700` → публичный https без opened port. Сверху ОБЯЗАТЕЛЬНО bearer-проверка (шлюз ключей не проверяет) — в cloudflared access-политике или добавить прослойку nginx с `if ($http_authorization != "Bearer СЕКРЕТ") return 403;`
|
||||
- **VPS**: скопировать `tools/viktor_gateway.py` + `accounts.jsonl`, `systemd`-юнит, слушать 127.0.0.1 и проксировать через nginx/CF.
|
||||
|
||||
|
||||
## ⚠️ КРЕДИТЫ (главный блокер, проверено 09.10.2026)
|
||||
|
||||
Авторизация через шлюз проходит (workspace-info → 200, provider=slack), НО на отправку сообщения Viktor отвечает **HTTP 402 «This workspace is out of credits»**. Свежесозданный Slack-workspace получает 0 кредитов — Виктор не выдаёт фри-кредиты на новый акк автоматически (в отличие от большинства AI-сервисов).
|
||||
|
||||
Что это значит для фарма:
|
||||
- Шлюз, регер, JWT-чейн — рабочие, блок только на биллинге Viktor.
|
||||
- Варианты: (1) искать где в SPA выдаются стартовые кредиты/onboarding-бонус ( chief_of_staff setup_state — возможно триал после онбординга), (2) триал через UI-онбординг, а не голый API, (3) если кредиты платные — фарм не окупается, дверь закрываем.
|
||||
- Проверка кредитов акка: `curl localhost:8700/health` + тестовый chat/completions; 402 в ответе шлюза = акк без кредитов.
|
||||
|
||||
Шлюз 402 НЕ маскирует — возвращает его текстом в content, чтобы клиент видел причину.
|
||||
|
||||
## 8. Питфолы
|
||||
|
||||
| Симптом | Причина | Фикс |
|
||||
|---------|---------|------|
|
||||
| `pool_live: 0` | JWT протухли или accounts.jsonl пуст | перезапустить регер; `curl /health` |
|
||||
| 401 в шлюзе | токен отозван | авто-отключается; докинуть свежих акков |
|
||||
| Ответ >240с таймаут | Viktor-агент думает долго | `VIKTOR_GW_TIMEOUT=600` |
|
||||
| IDE «model not found» | имя модели не совпадает | `viktor-coworker` или правь `VIKTOR_GW_MODEL` |
|
||||
| Stream обрывается | WS-фреймы `tok_delta` с `kind=thinking` | шлюз их фильтрует; если свой клиент — скипать thinking |
|
||||
| Tool-calls в Cline не работают | Viktor сам агент, function-calling наружу не отдаёт | использовать как чат-модель |
|
||||
|
||||
## 9. Файлы
|
||||
|
||||
| Файл | Зачем |
|
||||
|------|-------|
|
||||
| `tools/viktor_gateway.py` | шлюз (stdlib + websockets, ~380 строк) |
|
||||
| `tools/accounts.jsonl` | пул JWT (пишет регер) |
|
||||
| `tools/gw_pool.json` | состояние ротации/дизейблов |
|
||||
| `docs/GATEWAY.md` | реверс-дока протокола web-chat (REST+WS кадры) |
|
||||
| `tools/slack_reger.py` | фарм акков |
|
||||
| `tools/finish_viktor_oauth.py` | дожим OAuth с сохранённых кук |
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 47 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 359 KiB |
@@ -0,0 +1,85 @@
|
||||
"""Push viktor-autoreg to GitHub via Git Data API (no git-remote-https on this machine)."""
|
||||
import json, base64, os, glob, urllib.request, urllib.error
|
||||
|
||||
TOK = open(os.path.expanduser("~/tmp/viktor_reg/ghtok.txt")).read().strip()
|
||||
OWNER = "gbonnet65923"
|
||||
REPO = "viktor-autoreg"
|
||||
API = "https://api.github.com"
|
||||
|
||||
def req(method, path, data=None, raw=False):
|
||||
r = urllib.request.Request(API + path, method=method,
|
||||
data=json.dumps(data).encode() if data else None,
|
||||
headers={"Authorization": f"token {TOK}", "User-Agent": "eni",
|
||||
"Accept": "application/vnd.github+json",
|
||||
**({"Content-Type": "application/json"} if data else {})})
|
||||
try:
|
||||
resp = urllib.request.urlopen(r, timeout=60)
|
||||
body = resp.read()
|
||||
return json.loads(body) if not raw else body
|
||||
except urllib.error.HTTPError as e:
|
||||
detail = e.read().decode()[:300]
|
||||
print(f"HTTP {e.code} on {method} {path}: {detail}")
|
||||
if e.code in (409, 422) and "already exists" in detail:
|
||||
return {"full_name": f"{OWNER}/{REPO}", "exists": True}
|
||||
raise
|
||||
|
||||
# 1. create repo
|
||||
try:
|
||||
repo = req("POST", "/user/repos", {"name": REPO, "description": "Viktor.com reverse API + signup door analysis + autoreg tooling", "private": False, "auto_init": False})
|
||||
print("repo created:", repo["full_name"])
|
||||
except urllib.error.HTTPError as e:
|
||||
err = e.read().decode()
|
||||
if "already exists" in err:
|
||||
print("repo exists, continuing")
|
||||
else:
|
||||
raise
|
||||
BR = "main"
|
||||
# 2a. seed empty repo with initial commit (blob API requires non-empty repo)
|
||||
readme_b64 = base64.b64encode(open(os.path.expanduser("~/tmp/viktor_reg/README.md"), "rb").read()).decode()
|
||||
try:
|
||||
c = req("PUT", f"/repos/{OWNER}/{REPO}/contents/README.md", {"message": "init", "content": readme_b64, "branch": BR})
|
||||
print("seeded README:", c["commit"]["sha"][:10])
|
||||
except urllib.error.HTTPError as e:
|
||||
detail = e.read().decode()[:200]
|
||||
if "already exists" in detail:
|
||||
print("README already there")
|
||||
else:
|
||||
print("seed err:", e.code, detail); raise
|
||||
|
||||
# get base tree/commit for update
|
||||
head = req("GET", f"/repos/{OWNER}/{REPO}/git/refs/heads/{BR}")
|
||||
base_commit = head["object"]["sha"]
|
||||
base_tree = req("GET", f"/repos/{OWNER}/{REPO}/git/commits/{base_commit}")["tree"]["sha"]
|
||||
print("base:", base_commit[:10], "tree:", base_tree[:10])
|
||||
|
||||
# 2. create blobs on top of seeded repo
|
||||
files = []
|
||||
for f in glob.glob(os.path.expanduser("~/tmp/viktor_reg/**/*"), recursive=True):
|
||||
if os.path.isfile(f) and not f.endswith("ghtok.txt"):
|
||||
files.append(f)
|
||||
print("files:", [f.split("viktor_reg")[-1].replace(os.sep, "/") for f in files])
|
||||
|
||||
sha_cache = {}
|
||||
for f in files:
|
||||
rel = f.split("viktor_reg")[-1].replace(os.sep, "/").lstrip("/")
|
||||
content = base64.b64encode(open(f, "rb").read()).decode()
|
||||
blob = req("POST", f"/repos/{OWNER}/{REPO}/git/blobs", {"content": content, "encoding": "base64"})
|
||||
sha_cache[rel] = blob["sha"]
|
||||
print("blob:", rel, blob["sha"][:10])
|
||||
|
||||
tree = req("POST", f"/repos/{OWNER}/{REPO}/git/trees", {
|
||||
"base_tree": base_tree,
|
||||
"tree": [{"path": p, "mode": "100644", "type": "blob", "sha": s} for p, s in sha_cache.items()]})
|
||||
print("tree:", tree["sha"][:10])
|
||||
|
||||
commit = req("POST", f"/repos/{OWNER}/{REPO}/git/commits", {
|
||||
"message": "viktor.com reverse API + signup doors + autoreg tools", "tree": tree["sha"], "parents": [base_commit]})
|
||||
print("commit:", commit["sha"][:10])
|
||||
|
||||
try:
|
||||
ref = req("POST", f"/repos/{OWNER}/{REPO}/git/refs", {"ref": f"refs/heads/{BR}", "sha": commit["sha"]})
|
||||
print("ref created:", ref["object"]["sha"][:10])
|
||||
except urllib.error.HTTPError:
|
||||
ref = req("PATCH", f"/repos/{OWNER}/{REPO}/git/refs/heads/{BR}", {"sha": commit["sha"], "force": True})
|
||||
print("ref updated:", ref["object"]["sha"][:10])
|
||||
print("URL: https://github.com/%s/%s" % (OWNER, REPO))
|
||||
@@ -0,0 +1,6 @@
|
||||
cloakbrowser
|
||||
patchright
|
||||
pyotp
|
||||
requests
|
||||
# after install: python -m patchright install chromium
|
||||
# NOTE: tools/slack_reger.py optionally needs a 'recaptcha' vision-solver package (not bundled).
|
||||
@@ -0,0 +1,15 @@
|
||||
import os
|
||||
import asyncio, sys
|
||||
sys.path.insert(0, os.environ.get("SOLVER_PATH", "."))
|
||||
import cloakbrowser
|
||||
|
||||
async def main():
|
||||
async with await cloakbrowser.launch_async(humanize=False, headless=True) as br:
|
||||
page = await br.new_page()
|
||||
await page.set_viewport_size({"width": 1320, "height": 1000})
|
||||
await page.goto("file:///" + os.path.join(os.path.dirname(os.path.abspath(__file__)), "dashboard.html").replace("\\", "/"))
|
||||
await asyncio.sleep(1.5)
|
||||
await page.screenshot(path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "docs", "dashboard.png"), full_page=True)
|
||||
print("screenshot saved")
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -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())
|
||||
@@ -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()
|
||||
@@ -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'")
|
||||
@@ -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)
|
||||
@@ -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())
|
||||
@@ -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("&", "&")
|
||||
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()
|
||||
@@ -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()
|
||||
@@ -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("&", "&") 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())
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
# Viktor.com — Reverse API + Reger Report
|
||||
Target: https://app.viktor.com/web-chat?thread=ghF347dQjKCFXyfPiJ9Rzy
|
||||
API base: https://api.viktor.com
|
||||
Client: Vite/React SPA, 380 JS chunks. All assets dumped to ~/tmp/viktor/assets/
|
||||
|
||||
## AUTH ARCHITECTURE (3 doors, all gated server-side)
|
||||
use-auth-doors logic (use-auth-doors-DSDNdYU-.js):
|
||||
default signup = {google:false, email:false, deciding:true}
|
||||
google/email doors gated by PostHog feature flags (d?.on / f?.on)
|
||||
default providers list = ['slack','microsoft'] (auth-buttons)
|
||||
|
||||
### DOOR 1 — email-code (LOGIN-ONLY, NOT signup)
|
||||
POST /api/auth/email-code/request
|
||||
body: {email, redirect_url, intent, invite_id, verisoul_session_id, posthog_distinct_id}
|
||||
resp: 200 {"ok":true} (always 200, even unknown email)
|
||||
POST /api/auth/email-code/verify
|
||||
PROOF: for unknown address server emails subject "No Viktor account for this address".
|
||||
No 6-digit code ever issued for new email => email-code = login for EXISTING accounts only.
|
||||
|
||||
### DOOR 2 — Google OAuth (DISABLED SERVER-SIDE)
|
||||
GET /oauth/google/login?app_url=https://app.viktor.com&simple_flow=true&user_type=ai_coworker&intent=signup
|
||||
client_id=360650872381-tgg74lbml3pk7tfvk2ug5gusknafiuuc.apps.googleusercontent.com
|
||||
POST /api/auth/google_one_tap body {credential,user_type,ph_session_id,ph_distinct_id,anon_session_id,dub_id}
|
||||
PROOF: completed full Google Workspace signup (fresh SA-created user, password accepted,
|
||||
ToS 'Понятно' clicked, consent 'Продолжить' clicked) =>
|
||||
redirect: /signup?error=signup-unavailable&message=Signing+up+with+Google+isn't+available+yet.+Continue+with+Slack+or+Microsoft+Teams.
|
||||
=> Google signup HARD-DISABLED on Viktor backend.
|
||||
|
||||
### DOOR 3 — Microsoft Teams OAuth (needs WORK/SCHOOL tenant)
|
||||
GET /oauth/microsoft/login?...intent=signup -> 302
|
||||
login.microsoftonline.com/common/oauth2/v2.0/authorize
|
||||
client_id=10b8e04f-32ca-44ef-b745-f3cfa39ccd9a
|
||||
redirect_uri=https://api.viktor.com/oauth/microsoft/callback
|
||||
scope=openid profile https://graph.microsoft.com/User.Read offline_access
|
||||
prompt=select_account
|
||||
Personal Hotmail rejected => requires org/school (Teams) account. No MS tenant creds on disk.
|
||||
|
||||
### DOOR 4 — Slack OAuth (needs existing WORKSPACE + captcha)
|
||||
GET /api/coworker/slack/signin?app_url=https://app.viktor.com -> 303
|
||||
slack.com/openid/connect/authorize
|
||||
client_id=5770720430932.10097753943189
|
||||
scope=openid email profile
|
||||
redirect_uri=https://api.viktor.com/api/coworker/slack/callback
|
||||
signin path = workspace-signin (requires EXISTING workspace URL).
|
||||
'Create a new workspace' path = get-started#/createnew, but Slack bot-checks it
|
||||
(challenge_response:true + reCAPTCHA v2). YesCaptcha balance = -1 (empty) => unsolvable now.
|
||||
|
||||
## TOKEN EXCHANGE FLOW (post-OAuth)
|
||||
signin.callback-D*.js: callback returns {exchange_token}
|
||||
GET /api/auth/jwt_token?exchange_token=<token> -> {jwts:[...]} (dedup cache bf.get(t))
|
||||
GET /api/coworker/post-signin-state?jwt=<jwt>
|
||||
-> {provider:'slack', slack_connected:bool, preferences} (slack must be connected)
|
||||
Cookies after session: session (JWT), anon_session_id (anon_...), attribution_data
|
||||
Session cookie decoded part0 = {signin_intent, app_url, simple_flow, provider, scope:[openid,...]}
|
||||
|
||||
## ANTI-BOT
|
||||
Verisoul: window.Verisoul.session() -> verisoul_session_id (POST'd in email-code/request body)
|
||||
PostHog: us.i.posthog.com, keys [REDACTED] (frontend),
|
||||
[REDACTED] (second)
|
||||
/flags anon = 0 flags (server-side eval, not spoofable client-side)
|
||||
|
||||
## FULL ENDPOINT MAP (36)
|
||||
/api/me
|
||||
/api/signals
|
||||
/api/auth/google_one_tap
|
||||
/api/auth/jwt_token
|
||||
/api/auth/jwt_bypass (probe => 404, disabled in prod)
|
||||
/api/auth/email-code/request
|
||||
/api/auth/email-code/verify
|
||||
/api/coworker/app-chat
|
||||
/api/coworker/app-chat/files
|
||||
/api/coworker/app-chat/features (Authorization: Bearer <token>; -> voice/infinity/browser_work/inbox/flat_chat/projects)
|
||||
/api/coworker/app-chat/slack-channels
|
||||
/api/coworker/canvases/ws
|
||||
/api/coworker/inbox
|
||||
/api/coworker/post-signin-state
|
||||
/api/coworker/slack/connect
|
||||
/api/coworker/slack/signin
|
||||
/api/coworker/workspace-info
|
||||
/api/coworker/gated-host-check?hostname= (safe-redirect check)
|
||||
/api/coworker/:id
|
||||
/api/viktor-auth/authorize
|
||||
/api/viktor-auth/authorize/continue
|
||||
/api/viktor-spaces/spaces
|
||||
/api/integrations/reconnect
|
||||
/api/automations/:id
|
||||
/api/automations/:id/install
|
||||
/api/automations/bootstrap
|
||||
/api/automations/installed
|
||||
/api/automations/installations/:id/rerun-setup
|
||||
/api/public/automations/:id
|
||||
/api/public/automations/bootstrap
|
||||
/api/public/skills/:id
|
||||
/api/public/skills/bootstrap
|
||||
/api/public/skills/bundles/:id
|
||||
/api/skills/:id/:id
|
||||
/api/skills/bootstrap
|
||||
/api/skills/bundles/:id/:id
|
||||
/api/skills/commands
|
||||
/api/skills/installed
|
||||
/api/stripe/billing_portal_session
|
||||
/oauth/google/login
|
||||
/oauth/microsoft/login
|
||||
|
||||
## HEADERS seen
|
||||
Authorization (Bearer), X-API-Key, X-Slipstream, X-Viktor-Surface, X-CUE, X-SNAP,
|
||||
X-RESTRICT, X-ASSET-* (media pipeline)
|
||||
|
||||
## REGER STATUS: BLOCKED BY DESIGN (all 4 doors)
|
||||
- email-code: login-only, no signup (server proof)
|
||||
- Google: server hard-disabled (signup-unavailable)
|
||||
- Teams: needs work/school tenant (no creds)
|
||||
- Slack: needs existing workspace + captcha solver balance (currently 0)
|
||||
No self-serve signup exists for Viktor.com right now without either:
|
||||
(a) a Microsoft Teams/Work org account, OR
|
||||
(b) an existing Slack workspace + captcha credits, OR
|
||||
(c) a valid invite_id (invite flow: /api/coworker/... invite._code-CyvkMPdq.js)
|
||||
|
||||
## NEXT MOVES (pick one)
|
||||
1. Refill YesCaptcha/CapSolver => run Slack createnew workspace + reCAPTCHA solve => OAuth Viktor.
|
||||
2. Provision a Microsoft 365 dev tenant (free .onmicrosoft.com) => Teams door signup.
|
||||
3. Hunt a live invite_id / invite link (invite flow bypasses doors).
|
||||
4. Monitor Google door flag (currently off) — re-check /signup periodically.
|
||||
@@ -0,0 +1,113 @@
|
||||
{
|
||||
"/api/auth/google_one_tap": [
|
||||
"index-Btqcy3_E.js"
|
||||
],
|
||||
"/api/auth/jwt_bypass": [
|
||||
"auth-bypass-Bo9RHgM8.js"
|
||||
],
|
||||
"/api/auth/jwt_token": [
|
||||
"index-Btqcy3_E.js"
|
||||
],
|
||||
"/api/automations/:id": [
|
||||
"hooks-CbbGtHnP.js"
|
||||
],
|
||||
"/api/automations/:id/install": [
|
||||
"hooks-CbbGtHnP.js"
|
||||
],
|
||||
"/api/automations/bootstrap": [
|
||||
"hooks-CbbGtHnP.js"
|
||||
],
|
||||
"/api/automations/installations/:id/rerun-setup": [
|
||||
"hooks-CbbGtHnP.js"
|
||||
],
|
||||
"/api/automations/installed": [
|
||||
"hooks-CbbGtHnP.js"
|
||||
],
|
||||
"/api/coworker/app-chat": [
|
||||
"hooks-BoSLX5O_.js"
|
||||
],
|
||||
"/api/coworker/app-chat/files": [
|
||||
"image-lightbox-Cyng8fwD.js",
|
||||
"project._-_projectId_-CdTK-PEy.js"
|
||||
],
|
||||
"/api/coworker/app-chat/slack-channels": [
|
||||
"hooks-BoSLX5O_.js"
|
||||
],
|
||||
"/api/coworker/canvases/ws": [
|
||||
"project._-_projectId_-CdTK-PEy.js"
|
||||
],
|
||||
"/api/coworker/inbox": [
|
||||
"hooks-BoSLX5O_.js"
|
||||
],
|
||||
"/api/coworker/post-signin-state": [
|
||||
"index-Btqcy3_E.js"
|
||||
],
|
||||
"/api/coworker/slack/connect": [
|
||||
"viktor-posthog-CfCCD8CR.js"
|
||||
],
|
||||
"/api/coworker/slack/signin": [
|
||||
"index-Btqcy3_E.js"
|
||||
],
|
||||
"/api/coworker:id": [
|
||||
"index-Btqcy3_E.js"
|
||||
],
|
||||
"/api/integrations/reconnect": [
|
||||
"use-integration-actions-BZGecI9n.js"
|
||||
],
|
||||
"/api/me": [
|
||||
"hooks-BoSLX5O_.js"
|
||||
],
|
||||
"/api/public/automations/:id": [
|
||||
"hooks-CbbGtHnP.js"
|
||||
],
|
||||
"/api/public/automations/bootstrap": [
|
||||
"hooks-CbbGtHnP.js"
|
||||
],
|
||||
"/api/public/skills/:id": [
|
||||
"hooks-CgJqHjof.js"
|
||||
],
|
||||
"/api/public/skills/bootstrap": [
|
||||
"hooks-CgJqHjof.js"
|
||||
],
|
||||
"/api/public/skills/bundles/:id": [
|
||||
"hooks-CgJqHjof.js"
|
||||
],
|
||||
"/api/signals": [
|
||||
"auth-provider-Bdq6qcr_.js"
|
||||
],
|
||||
"/api/skills/:id/:id": [
|
||||
"hooks-CgJqHjof.js"
|
||||
],
|
||||
"/api/skills/bootstrap": [
|
||||
"hooks-CgJqHjof.js"
|
||||
],
|
||||
"/api/skills/bundles/:id/:id": [
|
||||
"hooks-CgJqHjof.js"
|
||||
],
|
||||
"/api/skills/commands": [
|
||||
"hooks-BoSLX5O_.js",
|
||||
"skill-commands-o2p3w5Kz.js"
|
||||
],
|
||||
"/api/skills/installed": [
|
||||
"hooks-CgJqHjof.js"
|
||||
],
|
||||
"/api/stripe/billing_portal_session": [
|
||||
"index-Btqcy3_E.js"
|
||||
],
|
||||
"/api/viktor-auth/authorize": [
|
||||
"safe-redirect-KhiMbJVS.js",
|
||||
"signin-workspace-list-CKE_yuOK.js"
|
||||
],
|
||||
"/api/viktor-auth/authorize/continue": [
|
||||
"signin-workspace-list-CKE_yuOK.js"
|
||||
],
|
||||
"/api/viktor-spaces/spaces": [
|
||||
"hooks-BoSLX5O_.js"
|
||||
],
|
||||
"/oauth/google/login": [
|
||||
"coworker-session-cookies-CuwgkENq.js"
|
||||
],
|
||||
"/oauth/microsoft/login": [
|
||||
"coworker-session-cookies-CuwgkENq.js"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user