diff --git a/README.md b/README.md index 293497e..c6de2e5 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ farm2.py волна: N аккаунтов, K лент, резерв поч shim2.py OpenAI-совместимый шлюз (stdlib http.server, без зависимостей кроме requests) models.json каталог: display name -> {id, api, credit} (93 модели) healthcheck.py разовая проверка пула: /health + тестовый чат +recon/ скрипты разведки UI: логин headful через CDP, дашборд, поиск выбора модели +docs/ui-notes.md реверс веб-интерфейса: cookie-авторизация, табы бота, где живёт выбор модели ``` ## Как устроен chat.co (реверс) @@ -102,6 +104,21 @@ mail.tmwlsw.com, tvnetwork.hu, aliyun.com. Формат файла `soil.txt` отказы bot 403 (антифрод по IP), verify 400 (OTP), otp (IMAP-троттлинг) ``` +## Дашборд и модели + +Полный разбор — `docs/ui-notes.md`. Коротко: SPA авторизуется двумя httpOnly cookie +(`auth-token`, `auth-refresh-token`), выбор модели живёт на вкладке **Tune Bot**, +и free-аккаунт видит там ровно выданный набор (у нас — 3 модели: Grok 4.3 Fast, +GPT-4.1 Mini, DeepSeek-R1 Bedrock), а не весь каталог. + +Проверка доступного набора без UI: + +```bash +curl -s https://fwb567mce3.us-east-1.awsapprunner.com/chatbot/ -H "Authorization: Bearer " | jq '.data.chatbot.availableModelIds' +``` + +Скрин: `docs/img/models_in_dashboard.png`. + ## Пиитфолы 1. `POST /auth/login` отдаёт 403 при заходе с «грязного» IP — менять egress, а не почту. diff --git a/docs/img/models_in_dashboard.png b/docs/img/models_in_dashboard.png new file mode 100644 index 0000000..456a2f4 Binary files /dev/null and b/docs/img/models_in_dashboard.png differ diff --git a/docs/ui-notes.md b/docs/ui-notes.md new file mode 100644 index 0000000..5d55565 --- /dev/null +++ b/docs/ui-notes.md @@ -0,0 +1,76 @@ +# UI / дашборд chat.co — что реально показывает сайт + +Заметки по реверсу веб-интерфейса (проверено 03.11.2026 на free-аккаунте). + +## Вход + +- Форма: `https://chat.co/auth/login` — поле `email` + скрытый `input[name=cf-turnstile-response]`, кнопка `Proceed`. +- Turnstile sitekey `0x4AAAAAAChjbcr8LGkrIuGG`; в headful Chrome решается сам за ~2 с, в headless — нет. +- После `Proceed` приходит письмо «OTP for login» с 6-значным кодом; вводится на следующем шаге. +- Успешный `POST /auth/verify/email` (201) отдаёт **две httpOnly cookie**: + `auth-token` (JWT, ~301 символ) и `auth-refresh-token`. + Токены SPA в `localStorage` не хранит — только cookie, поэтому «подставить токен скриптом» нельзя, + нужно ставить cookie (`ctx.add_cookies` в Playwright / `Network.setCookie` в CDP). + +Полный сценарий UI-логина — `recon/login_ui.py` (headful через CDP + чтение OTP по IMAP). + +## Адреса дашборда + +| Путь | Что это | +|---|---| +| `/home` | новый дашборд («Atlas», эксперты, кредиты) | +| `/dashboard?view=classic` | старый дашборд: карточки ботов, метрики, настройки | +| `/dashboard`, `/analytics`, `/staff`, `/profile` | разделы старого дашборда | +| `/home/chatbot//settings` | 404 — такого пути нет | + +Карточка бота в classic-дашборде открывает страницу с табами: +`Bot Overview · Conversation · Chat Logs · Handoff · Documents · Phone Line · Appointments · +MCP Tools · Tune Bot · Appearance · Deployment · Integrations · ROI & Metrics · Settings`. + +## Модели + +Выбор модели живёт на вкладке **Tune Bot**: + +``` +Select AI Model (You can select multiple) * + [ Grok 4.3 (Fast) ] [ GPT-4.1 Mini ] + +Default Model * + DeepSeek-R1 (Bedrock) +``` + +То есть UI free-аккаунта показывает **3 модели**, а не весь каталог. +Скрин: `docs/img/models_in_dashboard.png`. + +Через API то же самое видно в объекте бота: + +```bash +GET https://fwb567mce3.us-east-1.awsapprunner.com/chatbot/{botId} +Authorization: Bearer + +data.chatbot.availableModelIds -> ["6ab600e25dc8cc609e69da54", "6948a9b8348be275bb55551b"] # 2 id +data.chatbot.aiModel -> {name:"DeepSeek-R1 (Bedrock)", apiModelName:"deepseek.r1-v1:0", + messageCredit:4, displayOrder:87, isActive:true} +``` + +Полный каталог платформы (93 записи вида `{id, api, credit}`) в дашборде не рендерится — +он собирается из отдельного списка моделей и используется ядром бота. +Поэтому «скриншот всех моделей с сайта» на free-аккаунте физически не получить: сайт отдаёт +только выданный набор, остальное закрыто тарифом. + +## Смена модели + +```bash +PATCH /chatbot/{botId}/ai-model {"aiModelId": ""} +``` + +Именно это делает шлюз (`shim2.py`, функция `ask`) перед каждым запросом, если текущая модель +бота не совпадает с запрошенной. + +## Пиитфолы UI + +1. Онбординг-модалка «Welcome to Chat.co!» перекрывает карточки — сначала `Skip`. +2. Cookie-баннер (`Accept`) перехватывает клики по нижним элементам. +3. Headful Chrome умирает после 1-2 переходов (`TargetClosedError`) — снимать скрин сразу + после нужного шага и поднимать браузер заново под следующий. +4. `text=node` не кликается, пока открыта модалка; после `Skip` — работает. \ No newline at end of file diff --git a/recon/dash_shot.py b/recon/dash_shot.py new file mode 100644 index 0000000..48ae59c --- /dev/null +++ b/recon/dash_shot.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Открывает дашборд chat.co с готовыми cookie, ищет раздел моделей и снимает скрин.""" +import json, os, re, sys, time +from playwright.sync_api import sync_playwright + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PORT = os.environ.get("CDP_PORT", "9244") +OUT = os.environ.get("CC_OUT", r"C:\Users\User\tmp\chatco\card") + +tok = json.load(open(r"C:\Users\User\tmp\chatco\.tokens.json", encoding="utf-8")) +cookies = [] +for raw in tok.get("cookies") or []: + pair = raw.split(";")[0] + if "=" not in pair: + continue + name, value = pair.split("=", 1) + cookies.append({"name": name.strip(), "value": value.strip(), "domain": ".chat.co", "path": "/"}) +print("cookies:", [c["name"] for c in cookies], flush=True) + +with sync_playwright() as p: + b = p.chromium.connect_over_cdp("http://127.0.0.1:%s" % PORT) + ctx = b.contexts[0] + ctx.add_cookies(cookies) + pg = ctx.pages[0] if ctx.pages else ctx.new_page() + pg.set_viewport_size({"width": 1440, "height": 1800}) + pg.goto("https://chat.co/", wait_until="domcontentloaded", timeout=90000) + time.sleep(6) + print("url:", pg.url, "| title:", pg.title(), flush=True) + print("landing body:", " ".join(pg.inner_text("body")[:200].split()), flush=True) + # куда ведёт дашборд + for path in ["/dashboard", "/chatbots", "/chatbot", "/app", "/workspace"]: + try: + pg.goto("https://chat.co" + path, wait_until="domcontentloaded", timeout=45000) + time.sleep(5) + body = " ".join(pg.inner_text("body")[:300].split()) + if "404" in pg.title() or "not found" in body.lower(): + print(path, "-> 404", flush=True) + continue + print(path, "->", pg.url, "|", body[:150], flush=True) + pg.screenshot(path=os.path.join(OUT, "dash_%s.png" % path.strip("/"))) + except Exception as e: + print(path, "ERR", str(e)[:70], flush=True) + print("links:", pg.eval_on_selector_all("a", "els => els.map(e => e.getAttribute('href')).filter(Boolean).slice(0,50)"), flush=True) \ No newline at end of file diff --git a/recon/find_models.py b/recon/find_models.py new file mode 100644 index 0000000..e97c895 --- /dev/null +++ b/recon/find_models.py @@ -0,0 +1,34 @@ +import json, os, sys, time +from playwright.sync_api import sync_playwright +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PORT=os.environ.get("CDP_PORT","9249"); OUT=r"C:\Users\User\tmp\chatco\card" +tok=json.load(open(r"C:\Users\User\tmp\chatco\.tokens.json",encoding="utf-8")) +ck=[] +for raw in tok.get("cookies") or []: + pr=raw.split(";")[0] + if "=" in pr: + n,v=pr.split("=",1); ck.append({"name":n.strip(),"value":v.strip(),"domain":".chat.co","path":"/"}) +with sync_playwright() as p: + b=p.chromium.connect_over_cdp("http://127.0.0.1:%s"%PORT); ctx=b.contexts[0]; ctx.add_cookies(ck) + pg=ctx.pages[0] if ctx.pages else ctx.new_page(); pg.set_viewport_size({"width":1500,"height":1800}) + pg.goto("https://chat.co/dashboard?view=classic", wait_until="domcontentloaded", timeout=90000); time.sleep(6) + for lab in ["Accept","Skip"]: + try: pg.click("text=%s"%lab, timeout=2500) + except Exception: pass + pg.click("text=node", timeout=6000); time.sleep(6) + try: + pg.click("text=Tune Bot", timeout=6000); time.sleep(6); print("tune bot opened", flush=True) + except Exception as e: print("tune fail", str(e)[:60], flush=True) + pg.screenshot(path=os.path.join(OUT,"tune.png")) + body=pg.inner_text("body"); open(os.path.join(OUT,"tune.txt"),"w",encoding="utf-8").write(body) + # все селекты/дропдауны на странице + print("SELECTS:", pg.eval_on_selector_all("select","els=>els.map(e=>e.name||e.id||e.className.slice(0,20))"), flush=True) + print("LABELS:", [x for x in body.split('\n') if 'model' in x.lower() or 'AI' == x.strip()][:10], flush=True) + for sel in ["text=DeepSeek-R1", "button:has-text('DeepSeek')", "[role=combobox]"]: + try: + pg.click(sel, timeout=4000); time.sleep(3) + pg.screenshot(path=os.path.join(OUT,"tune_drop.png")) + t=pg.inner_text("body"); open(os.path.join(OUT,"tune_drop.txt"),"w",encoding="utf-8").write(t) + print("opened", sel, "| sample:", " ".join(t[:300].split())[:200], flush=True) + break + except Exception: continue diff --git a/recon/login_ui.py b/recon/login_ui.py new file mode 100644 index 0000000..6e454ea --- /dev/null +++ b/recon/login_ui.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""UI-логин chat.co в headful Chrome (CDP) + скрин раздела моделей.""" +import imaplib, email, json, os, re, subprocess, sys, time +from playwright.sync_api import sync_playwright + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") +PORT = os.environ.get("CDP_PORT", "9244") +EMAIL = os.environ.get("CC_EMAIL", "252d4f@rambler.ru") +SHOT = os.environ.get("CC_SHOT", r"C:\Users\User\tmp\chatco\card\site_models.png") + + +def otp(mail, pw, since_ts, timeout=240): + """Читает код из последнего письма chat.co, пришедшего после since_ts.""" + deadline = time.time() + timeout + while time.time() < deadline: + try: + M = imaplib.IMAP4_SSL("imap.rambler.ru", 993, timeout=30) + M.login(mail, pw) + M.select("INBOX", readonly=True) + typ, d = M.search(None, "FROM", '"chat.co"') + ids = [int(x) for x in (d[0].split() if d and d[0] else [])] + for i in reversed(ids[-8:]): + _, dd = M.fetch(str(i), "(RFC822)") + m = email.message_from_bytes(dd[0][1]) + try: + ts = time.mktime(email.utils.parsedate(m["Date"])) + except Exception: + ts = 0 + if ts < since_ts - 120: + continue + body = "" + for p in m.walk(): + if p.get_content_type() in ("text/html", "text/plain"): + body += p.get_payload(decode=True).decode("utf-8", "ignore") + txt = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", re.sub(r"", " ", body))) + mm = re.search(r"verification code\s*(\d{6})", txt, re.I) or re.search(r"\b(\d{6})\b", txt) + if mm: + M.logout() + return mm.group(1) + M.logout() + except Exception as e: + print("imap", type(e).__name__, str(e)[:60], flush=True) + time.sleep(8) + return None + + +def main(): + pw = None + for line in open(r"C:\Users\User\tmp\chatco\pool.jsonl", encoding="utf-8"): + try: + r = json.loads(line) + except Exception: + continue + if r.get("email") == EMAIL and r.get("pw"): + pw = r["pw"] + break + print("pw?", bool(pw), flush=True) + + with sync_playwright() as p: + b = p.chromium.connect_over_cdp("http://127.0.0.1:%s" % PORT) + ctx = b.contexts[0] + pg = [x for x in ctx.pages if "chat.co" in (x.url or "")] or [ctx.new_page()] + pg = pg[0] + pg.goto("https://chat.co/auth/login", wait_until="domcontentloaded", timeout=90000) + time.sleep(4) + print("title:", pg.title(), flush=True) + + # cookie banner + for sel in ["text=Accept", "button:has-text('Accept')"]: + try: + pg.click(sel, timeout=2500) + break + except Exception: + pass + pg.fill("input[name=email]", EMAIL) + t0 = time.time() + tok = "" + for _ in range(45): + tok = pg.eval_on_selector("input[name=cf-turnstile-response]", "e => e.value") + if tok and len(tok) > 20: + print("turnstile solved in %.0fs" % (time.time() - t0), flush=True) + break + time.sleep(2) + if not tok: + print("TURNSTILE FAIL", flush=True) + return 2 + pg.click("button:has-text('Proceed')") + time.sleep(5) + print("after proceed:", pg.url, flush=True) + + code = otp(EMAIL, pw, t0) + print("otp:", code, flush=True) + if not code: + return 3 + # поле кода: ищем любой видимый input, кроме email + inputs = pg.eval_on_selector_all("input", "els => els.map(e => ({name:e.name, type:e.type, ph:e.placeholder}))") + print("inputs:", inputs, flush=True) + filled = False + for sel in ["input[name=otp]", "input[autocomplete='one-time-code']", "input[inputmode='numeric']", "input[type=text]"]: + try: + pg.fill(sel, code, timeout=3000) + filled = True + print("filled via", sel, flush=True) + break + except Exception: + continue + if not filled: + print("no otp field", flush=True) + pg.screenshot(path=SHOT.replace(".png", "_otpstep.png")) + return 4 + for sel in ["button:has-text('Verify')", "button:has-text('Continue')", "button:has-text('Proceed')", "button[type=submit]"]: + try: + pg.click(sel, timeout=2500) + break + except Exception: + continue + time.sleep(10) + print("url after otp:", pg.url, flush=True) + pg.screenshot(path=SHOT.replace(".png", "_dash.png"), full_page=False) + print("nav:", pg.eval_on_selector_all("a", "els => els.map(e => e.getAttribute('href')).filter(Boolean).slice(0,40)"), flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file