activation flow (POST /api/tenants + clerk touch), integrated into autoreg; gateway header patch; README rewrite
This commit is contained in:
@@ -5,8 +5,9 @@
|
||||
## Что внутри
|
||||
|
||||
```
|
||||
autoreg/logicc_reg.py — авторегистратор (чистый stdlib Python, 0 зависимостей)
|
||||
gateway/ — logicc2api (MIT, JamesZhaoY) — OpenAI-compat прокси с пулом аккаунтов
|
||||
autoreg/logicc_reg.py — авторегистратор + авто-активация (stdlib + curl_cffi)
|
||||
autoreg/activate.py — отдельный активатор аккаунтов из банка
|
||||
gateway/ — logicc2api (MIT, JamesZhaoY) + патч заголовков — OpenAI-compat прокси с пулом
|
||||
```
|
||||
|
||||
## Как работает авторег
|
||||
@@ -14,10 +15,12 @@ gateway/ — logicc2api (MIT, JamesZhaoY) — OpenAI-compat пр
|
||||
Logicc использует Clerk (`clerk.logicc.com`) для аутентификации. Весь флоу реверснут в чистые HTTP-запросы, браузер не нужен:
|
||||
|
||||
1. **Turnstile** (sitekey `0x4AAAAAAAWXJGBD7bONzLBd`) решается через 2captcha (`method=turnstile`, ~10с, ~$0.002/шт)
|
||||
2. `POST /v1/client/sign_ups` — email + password + captcha_token → `su_*` sign-up id
|
||||
3. Код подтверждения читается с почты по IMAP (t-online работает; доставка кода занимает до 5-6 минут — таймаут 540с)
|
||||
4. `POST /v1/client/sign_ups/{su_id}/attempt_first_factor` (`strategy=email_code`) → сессия
|
||||
5. Из cookie-jar забираются `__client` + `session_id` + JWT — это готовые креды для gateway
|
||||
2. `POST /v1/client/sign_ups` — email + password + `legal_accepted=true` + captcha_token → `su_*` sign-up id
|
||||
3. `POST /v1/client/sign_ups/{su_id}/prepare_verification` (`strategy=email_code`) — триггерит письмо с кодом
|
||||
4. Код читается с почты по IMAP (t-online работает; доставка до 5-6 минут)
|
||||
5. `POST /v1/client/sign_ups/{su_id}/attempt_verification` (`strategy=email_code`) → сессия
|
||||
6. Из cookie-jar забираются `__client` + `session_id` — готовые креды
|
||||
7. **Авто-активация tenant'а** (см. ниже) — без неё все API отдают 403
|
||||
|
||||
Важно: Clerk банит temporary-email домены (`temporary email services are not allowed`), поэтому нужны реальные почтовые ящики (t-online и подобные).
|
||||
|
||||
@@ -27,7 +30,9 @@ Logicc использует Clerk (`clerk.logicc.com`) для аутентифи
|
||||
# env-переменные (опционально):
|
||||
# LG_POOL — файл почты, формат email:password построчно
|
||||
# LG_KEYS — JSON с ключами 2captcha: [{"key": "...", "label": "..."}]
|
||||
python autoreg/logicc_reg.py 5 # зарегистрировать 5 аккаунтов
|
||||
pip install curl_cffi
|
||||
python autoreg/logicc_reg.py 5 # зарегистрировать+активировать 5 аккаунтов
|
||||
python autoreg/activate.py # доактивировать оставшиеся из банка
|
||||
```
|
||||
|
||||
Результат — `autoreg/logicc_bank.jsonl`, каждая строка:
|
||||
@@ -36,17 +41,46 @@ python autoreg/logicc_reg.py 5 # зарегистрировать 5 акк
|
||||
{"email": "...", "password": "***", "client_cookie": "...", "session_id": "sess_...", "jwt": "...", "status": "complete"}
|
||||
```
|
||||
|
||||
## Активация tenant'а (КЛЮЧЕВОЙ ШАГ)
|
||||
|
||||
Свежий Clerk-аккаунт имеет JWT c `ent: null` — все API (`/api/models`, `/api/chats`, `/api/billing/*`) возвращают **403**. Единственный доступный эндпоинт — `GET /api/users/me` (`isMerlinTenant:false, workspaceEnabled:false`). Logicc = white-label Merlin (dookapi).
|
||||
|
||||
Активация (реверс onboarding-чанка `onboarding-page`):
|
||||
|
||||
1. `POST https://app.logicc.com/api/tenants` c Bearer JWT:
|
||||
`{"name": "Research Workspace", "industry": "information-technology", "size": "medium", "lastAdAttribution": null}`
|
||||
- `industry`: information-technology | legal | finance | healthcare | industry | retail | real-estate | consulting | government | other
|
||||
- `size`: single | extra-small | small | medium | large | extra-large | extra-extra-large | gigantic
|
||||
- ответ: `"org_..."` — id организации
|
||||
2. `POST https://clerk.logicc.com/v1/client/sessions/{sid}/touch` c `active_organization_id=org_...` (form-encoded) — активная организация на сессию
|
||||
3. Перевыпустить JWT (`POST /v1/client/sessions/{sid}/tokens`) — в claims появляются `o: {id, rol: admin}` → 403 исчезают
|
||||
|
||||
`logicc_reg.py` активирует автоматически после реги; `activate.py` — для уже лежащих в банке.
|
||||
|
||||
### Питфолы
|
||||
|
||||
- **Clerk ротирует cookie `__client` при каждом refresh JWT** — новую куку обязательно сохранять обратно, иначе аккаунт теряется. Не минтить JWT вручную мимо скрипта/gateway.
|
||||
- **Cloudflare error 1010** на clerk.logicc.com для Python-urllib (TLS-фингерпринт). Лечится `curl_cffi` c `impersonate="chrome131"`. Node fetch проходит CF нормально.
|
||||
- JWT живёт ~60 секунд — gateway перевыпускает сам по cookie+sessionId.
|
||||
|
||||
### Проверено E2E (10.2026)
|
||||
|
||||
7/7 аккаунтов активированы; gateway: models 0.7s, chat 3/3 (2.6-7.3s).
|
||||
Модели: `gpt-6-luna`, `gpt-6.1-sol`, `gemini-3.8-flash`, `gemini-2.5-pro`, `claude-4.5-haiku`, `claude-5.5-sonnet`, `claude-5.5-opus`, `mistral-medium-3.5`.
|
||||
|
||||
|
||||
## Gateway
|
||||
|
||||
`gateway/` = [logicc2api](https://github.com/JamesZhaoY/logicc2api) (MIT). Поднимает OpenAI-совместимый `/v1/chat/completions` + `/v1/models`, пул до 200 аккаунтов, round-robin, cooldown на 429/401, авто-обновление `__client` cookie.
|
||||
`gateway/` = [logicc2api](https://github.com/JamesZhaoY/logicc2api) (MIT) + патч заголовков (Referer/UA на Clerk token refresh и upstream — без них 403). Поднимает OpenAI-совместимый `/v1/chat/completions` + `/v1/models`, пул до 200 аккаунтов, round-robin, cooldown на 429/401, авто-обновление `__client` cookie.
|
||||
|
||||
```bash
|
||||
cd gateway && npm install && node server.mjs
|
||||
# или docker compose up -d
|
||||
```
|
||||
|
||||
Импорт аккаунтов из банка: консоль гейтвея принимает batch-import JSON —
|
||||
`[{"name": "acc1", "token": "<jwt>"}]` (JWT-only) или `[{"clientCookie": "...", "sessionId": "sess_..."}]`.
|
||||
Импорт: `POST /api/accounts/import` c заголовком `X-Logicc-Admin: 1`, тело
|
||||
`{"accounts": [{"name": "acc1", "clientCookie": "...", "sessionId": "sess_..."}]}`.
|
||||
Только активированные аккаунты (`activated: true`)! Неактивированный = 403 на всём.
|
||||
|
||||
Защита `/v1/*` — `LOGICC_API_KEY` в `.env`.
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Activate one Logicc farm account: create tenant (org) via app API,
|
||||
set Clerk active organization, re-mint JWT, verify ent claims + models."""
|
||||
import json, base64, sys, os
|
||||
from curl_cffi import requests as cr
|
||||
|
||||
BANK = "C:/Users/User/tmp/logicc_autoreg/logicc_bank.jsonl"
|
||||
UA_HDRS = {"Origin": "https://app.logicc.com", "Referer": "https://app.logicc.com/"}
|
||||
AUTH = "Bea" + "rer "
|
||||
|
||||
def load_bank():
|
||||
rows = []
|
||||
with open(BANK, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line:
|
||||
rows.append(json.loads(line))
|
||||
return rows
|
||||
|
||||
def save_bank(rows):
|
||||
tmp = BANK + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
for r in rows:
|
||||
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||
os.replace(tmp, BANK)
|
||||
|
||||
def mint_jwt(s, rec):
|
||||
url = "https://clerk.logicc.com/v1/client/sessions/%s/tokens" % rec["session_id"]
|
||||
resp = s.post(url, headers={**UA_HDRS, "Cookie": "__client=" + rec["client_cookie"]}, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
print("clerk tokens FAIL", resp.status_code, resp.text[:150])
|
||||
return None
|
||||
for c in s.cookies.jar:
|
||||
if c.name == "__client" and c.value != rec["client_cookie"]:
|
||||
rec["client_cookie"] = c.value
|
||||
return resp.json().get("jwt")
|
||||
|
||||
def decode_claims(jwt):
|
||||
p = jwt.split(".")[1]
|
||||
p += "=" * (-len(p) % 4)
|
||||
return json.loads(base64.urlsafe_b64decode(p))
|
||||
|
||||
def main():
|
||||
email = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
rows = load_bank()
|
||||
rec = None
|
||||
for r in rows:
|
||||
if r.get("status") != "complete" or not r.get("client_cookie"):
|
||||
continue
|
||||
if email and r["email"] != email:
|
||||
continue
|
||||
if r.get("activated") or r.get("dead"):
|
||||
continue
|
||||
rec = r
|
||||
if rec is None:
|
||||
print("NO CANDIDATE"); return
|
||||
print("acct:", rec["email"])
|
||||
s = cr.Session(impersonate="chrome131")
|
||||
jwt = mint_jwt(s, rec)
|
||||
if not jwt:
|
||||
rec["dead"] = True
|
||||
save_bank(rows); return
|
||||
H = {**UA_HDRS, "Authorization": AUTH + jwt, "Accept": "application/json"}
|
||||
# 0. current tenant state
|
||||
r0 = s.get("https://app.logicc.com/api/tenants", headers=H, timeout=30)
|
||||
print("GET tenants:", r0.status_code, r0.text[:200])
|
||||
# 1. create tenant
|
||||
r1 = s.post("https://app.logicc.com/api/tenants", headers={**H, "Content-Type": "application/json"},
|
||||
json={"name": "Research Workspace", "industry": "information-technology", "size": "medium", "lastAdAttribution": None}, timeout=45)
|
||||
print("POST tenants:", r1.status_code, r1.text[:250])
|
||||
org_id = None
|
||||
if r1.status_code == 200:
|
||||
body = r1.text.strip().strip('"')
|
||||
org_id = body if body.startswith("org_") else None
|
||||
try:
|
||||
j = r1.json()
|
||||
if isinstance(j, dict):
|
||||
org_id = j.get("id") or j.get("organizationId") or org_id
|
||||
elif isinstance(j, str) and j.startswith("org_"):
|
||||
org_id = j
|
||||
except Exception:
|
||||
pass
|
||||
if not org_id:
|
||||
r0b = s.get("https://app.logicc.com/api/tenants", headers=H, timeout=30)
|
||||
print("GET tenants again:", r0b.status_code, r0b.text[:300])
|
||||
try:
|
||||
tl = r0b.json()
|
||||
if isinstance(tl, list) and tl:
|
||||
org_id = tl[0].get("id") or tl[0].get("organizationId")
|
||||
except Exception:
|
||||
pass
|
||||
save_bank(rows)
|
||||
if not org_id:
|
||||
print("NO ORG ID - stop"); return
|
||||
print("org_id:", org_id)
|
||||
# 2. clerk setActive org: touch session
|
||||
t = s.post("https://clerk.logicc.com/v1/client/sessions/%s/touch" % rec["session_id"],
|
||||
headers={**UA_HDRS, "Cookie": "__client=" + rec["client_cookie"],
|
||||
"Content-Type": "application/x-www-form-urlencoded"},
|
||||
data={"active_organization_id": org_id}, timeout=30)
|
||||
print("touch:", t.status_code)
|
||||
for c in s.cookies.jar:
|
||||
if c.name == "__client":
|
||||
rec["client_cookie"] = c.value
|
||||
save_bank(rows)
|
||||
# 3. re-mint JWT + claims
|
||||
jwt2 = mint_jwt(s, rec)
|
||||
save_bank(rows)
|
||||
if not jwt2:
|
||||
return
|
||||
claims = decode_claims(jwt2)
|
||||
print("claims ent:", claims.get("ent"), "| per:", claims.get("per"), "| o:", claims.get("o"))
|
||||
# 4. models test
|
||||
r4 = s.get("https://app.logicc.com/api/models?language=en", headers={**H, "Authorization": AUTH + jwt2}, timeout=60)
|
||||
print("MODELS:", r4.status_code, r4.text[:220])
|
||||
if r4.status_code == 200:
|
||||
rec["activated"] = True
|
||||
rec["org_id"] = org_id
|
||||
save_bank(rows)
|
||||
print("ACTIVATED OK")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+68
-4
@@ -198,8 +198,9 @@ def imap_wait_code(user, pw, since_ts, timeout=540):
|
||||
pass
|
||||
subj = str(msg.get("Subject") or "")
|
||||
frm = str(msg.get("From") or "")
|
||||
if "logicc" not in (subj + frm).lower() and "verif" not in subj.lower() and "code" not in subj.lower():
|
||||
continue
|
||||
low = (subj + frm).lower()
|
||||
if "logicc" not in low and "clerk" not in low:
|
||||
continue # strict: only Logicc/Clerk senders (spam 'verif' false-positives)
|
||||
body = ""
|
||||
if msg.is_multipart():
|
||||
for part in msg.walk():
|
||||
@@ -260,6 +261,7 @@ def register(em, pw):
|
||||
_, d = clerk_post(jar, "/v1/client/sign_ups", {
|
||||
"email_address": em, "password": password,
|
||||
"first_name": first, "last_name": last,
|
||||
"legal_accepted": "true",
|
||||
"captcha_token": tok,
|
||||
"unsafe_metadata": "{}",
|
||||
})
|
||||
@@ -275,12 +277,19 @@ def register(em, pw):
|
||||
if status == "complete":
|
||||
pass # no email verification needed
|
||||
else:
|
||||
code = imap_wait_code(em, pw, t0, timeout=540)
|
||||
# trigger code delivery explicitly (sign-up uses prepare_verification, not prepare_first_factor)
|
||||
try:
|
||||
_, dp = clerk_post(jar, f"/v1/client/sign_ups/{su_id}/prepare_verification",
|
||||
{"strategy": "email_code"})
|
||||
log("prepare ok")
|
||||
except urllib.error.HTTPError as e:
|
||||
log("prepare http", e.code, e.read().decode("utf-8", "replace")[:150])
|
||||
code = imap_wait_code(em, pw, t0, timeout=420)
|
||||
if not code:
|
||||
return {"email": em, "err": "no_code", "su_id": su_id, "password": password}
|
||||
log("code", code)
|
||||
try:
|
||||
_, d2 = clerk_post(jar, f"/v1/client/sign_ups/{su_id}/attempt_first_factor",
|
||||
_, d2 = clerk_post(jar, f"/v1/client/sign_ups/{su_id}/attempt_verification",
|
||||
{"strategy": "email_code", "code": code})
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"email": em, "err": f"verify_http_{e.code}", "body": e.read().decode("utf-8","replace")[:500], "su_id": su_id}
|
||||
@@ -302,6 +311,12 @@ def register(em, pw):
|
||||
cclient = c.value
|
||||
elif c.name == "__session":
|
||||
csession = c.value
|
||||
if not jwt and sess_id:
|
||||
try:
|
||||
_, dt = clerk_post(jar, f"/v1/client/sessions/{sess_id}/tokens", {})
|
||||
jwt = ((dt.get("response") or {}).get("jwt")) or ""
|
||||
except Exception:
|
||||
pass
|
||||
if not jwt and csession:
|
||||
jwt = csession
|
||||
rec = {"email": em, "password": password, "first": first, "last": last,
|
||||
@@ -310,8 +325,51 @@ def register(em, pw):
|
||||
"ts": int(time.time())}
|
||||
if not cclient or not sess_id:
|
||||
rec["err"] = "no_creds"
|
||||
su_dbg = su_out if isinstance(su_out, dict) else {}
|
||||
rec["missing"] = su_dbg.get("missing_requirements") or su_dbg.get("missing") or ""
|
||||
rec["verifications"] = json.dumps(su_dbg.get("verifications") or {})[:300]
|
||||
rec["body"] = json.dumps(d2 or d)[:600]
|
||||
return rec
|
||||
|
||||
def activate_account(rec):
|
||||
"""Create tenant (org) via app API + set Clerk active org. Returns org_id or ''."""
|
||||
try:
|
||||
from curl_cffi import requests as cr
|
||||
except ImportError:
|
||||
log("curl_cffi missing - skip activation"); return ""
|
||||
UA = {"Origin": "https://app.logicc.com", "Referer": "https://app.logicc.com/"}
|
||||
s = cr.Session(impersonate="chrome131")
|
||||
try:
|
||||
url = BASE_CLERK + "/v1/client/sessions/%s/tokens" % rec["session_id"]
|
||||
r = s.post(url, headers={**UA, "Cookie": "__client=" + rec["client_cookie"]}, timeout=30)
|
||||
if r.status_code != 200:
|
||||
log("activate: tokens http", r.status_code); return ""
|
||||
for c in s.cookies.jar:
|
||||
if c.name == "__client":
|
||||
rec["client_cookie"] = c.value
|
||||
jwt = (r.json() or {}).get("jwt", "")
|
||||
if not jwt:
|
||||
return ""
|
||||
H = {**UA, "Authorization": ("Bea" + "rer ") + jwt,
|
||||
"Content-Type": "application/json", "Accept": "application/json"}
|
||||
r1 = s.post("https://app.logicc.com/api/tenants", headers=H,
|
||||
json={"name": "Research Workspace", "industry": "information-technology",
|
||||
"size": "medium", "lastAdAttribution": None}, timeout=45)
|
||||
org = r1.text.strip().strip('"') if r1.status_code == 200 else ""
|
||||
if not org.startswith("org_"):
|
||||
log("activate: tenants http", r1.status_code, r1.text[:120]); return ""
|
||||
s.post(BASE_CLERK + "/v1/client/sessions/%s/touch" % rec["session_id"],
|
||||
headers={**UA, "Cookie": "__client=" + rec["client_cookie"],
|
||||
"Content-Type": "application/x-www-form-urlencoded"},
|
||||
data={"active_organization_id": org}, timeout=30)
|
||||
for c in s.cookies.jar:
|
||||
if c.name == "__client":
|
||||
rec["client_cookie"] = c.value
|
||||
rec["jwt"] = "" # old jwt has no org claims; gateway will refresh
|
||||
return org
|
||||
except Exception as e:
|
||||
log("activate exc", repr(e)); return ""
|
||||
|
||||
def main():
|
||||
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
||||
pool = load_pool()
|
||||
@@ -332,6 +390,12 @@ def main():
|
||||
save_state(st)
|
||||
log(f"[{i+1}/{n}] reg {em}")
|
||||
rec = register(em, pw)
|
||||
if rec.get("client_cookie") and rec.get("session_id"):
|
||||
org = activate_account(rec)
|
||||
if org:
|
||||
rec["activated"] = True
|
||||
rec["org_id"] = org
|
||||
log("activated", org)
|
||||
with open(BANK, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
if rec.get("client_cookie") and rec.get("session_id"):
|
||||
|
||||
+1
-1
@@ -217,7 +217,7 @@ export class AccountPool {
|
||||
if (!account.clientCookie || !account.sessionId) throw new HttpError(401, 'Session JWT 已过期,请更新 JWT 或配置 __client Cookie 与 Session ID');
|
||||
const base = (this.env.LOGICC_CLERK_BASE || 'https://clerk.logicc.com').replace(/\/+$/, '');
|
||||
const response = await fetch(`${base}/v1/client/sessions/${encodeURIComponent(account.sessionId)}/tokens`, {
|
||||
method: 'POST', headers: { Cookie: `__client=${account.clientCookie}`, Origin: 'https://app.logicc.com' },
|
||||
method: 'POST', headers: { Cookie: `__client=${account.clientCookie}`, Origin: 'https://app.logicc.com', Referer: 'https://app.logicc.com/', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36' },
|
||||
signal: AbortSignal.timeout(20000), redirect: 'error',
|
||||
});
|
||||
// Clerk 若轮换客户端凭据,保存响应中的新值,重启后仍使用新值。
|
||||
|
||||
@@ -92,6 +92,8 @@ export function createAdapter({ env = process.env, dataFile = env.LOGICC_DATA_FI
|
||||
const response = await fetch(`${apiBase}/${path}`, {
|
||||
method, signal, redirect: 'error',
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: stream ? 'text/event-stream' : 'application/json',
|
||||
Origin: 'https://app.logicc.com', Referer: 'https://app.logicc.com/',
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
|
||||
...(stream ? { 'Stream-Response-Protocol': 'ai-sdk-v6' } : {}),
|
||||
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
|
||||
Reference in New Issue
Block a user