commit 69bacfc6fa63a62eebd0e4ed0aac860bf4ead3e8 Author: reform Date: Fri Oct 23 20:03:55 2026 +0300 recovered snapshot from suspended aaronjaworski710 (history unavailable) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8cefcc3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +accounts.jsonl +*.log +hit_*.json +hit_state_*.json +shots/ +__pycache__/ +manual_acc.json +pro_account.json +hitter_*.json +vcard_*.json +valid_coupons.json +used_emails.txt +oauth_token*.json +oauth_code.json +oauth_pending.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..012d86a --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +# Honen Toolkit + +Reverse-engineered toolkit for [honen.com](https://honen.com) — AI course-builder platform running Claude behind an AI-SDK stream. + +Zero dependencies (Python 3.11+ stdlib only). Three parts: + +| File | Purpose | +|------|---------| +| `honen_api.py` | Full API client: signup/login, workspaces, onboarding, billing, assistant chat (SSE), MCP | +| `honen_oauth.py` | OAuth 2.0 + PKCE flow → MCP access token with `workspace-assistant` scope (sandbox) | +| `honen_farm.py` | Mass account provisioning → `accounts.jsonl` (~2.7s/account) | +| `gateway.py` | **OpenAI-compatible gateway** over the account pool + web dashboard | + +## What you get + +Two models via a single OpenAI-compatible endpoint: + +- **`honen-assistant`** — Claude-backed workspace assistant (chat, course building, tool calls). Free tier: 15 AI messages/month per account; Pro trial: 999,999/month. +- **`honen-sandbox`** — raw bash/python execution in Honen's cloud sandbox via MCP. **Quota-free** (separate path, does not spend AI messages). Prompt = script, response = stdout/stderr. + +## Quick start + +```bash +# 1. Farm accounts (Gmail +alias works) +python honen_farm.py 5 # -> accounts.jsonl (email, password, cookie, workspace_id, mcp_token) + +# 2. Start the gateway +python gateway.py --port 8601 --key your-local-key + +# 3. Use it like any OpenAI endpoint +curl http://127.0.0.1:8601/v1/chat/completions \ + -H "Authorization: Bearer your-local-key" \ + -H "Content-Type: application/json" \ + -d '{"model":"honen-assistant","messages":[{"role":"user","content":"hello"}]}' + +# Sandbox (free code execution) +curl http://127.0.0.1:8601/v1/chat/completions \ + -H "Authorization: Bearer your-local-key" \ + -d '{"model":"honen-sandbox","messages":[{"role":"user","content":"uname -a; python3 -c \"print(6*7)\""}]}' +``` + +## Dashboard + +Open `http://127.0.0.1:8601/` — pool state, per-account usage, quarantine reasons. Paste your accounts into `accounts.jsonl` (hot-reload every 60s, one JSON per line — see `accounts.jsonl.example`). + +Pool logic: +- Pro accounts (field `"pro": true`) are picked first and exempt from the 15-msg quarantine. +- Dead sessions auto-relogin via email/password; exhausted accounts get quarantined automatically. +- Failover: one retry on a different account before 502. + +## Pro trial (7 days, $0 today) + +Honen Pro = 7-day free trial, then $20/mo. Checkout is Stripe-hosted, **card required** (no SEPA/ACH, no valid public coupons). UA-issued cards hit a 3DS wall (`setup_intent.status = requires_action`) — automated submits die with "Please try again". The working path: generate a checkout URL via the API, open it in a real browser, pay manually, complete 3DS in your bank app. + +```python +from honen_api import Honen, provision_account +acc = provision_account("you+tag@gmail.com", "StrongPass1!", "Your Name") +h = Honen(cookie=acc["cookie"]) +r = h.post("/api/billing/subscription/checkout", { + "planId": "", "interval": "MONTHLY", + "stripePriceId": "", "workspaceId": acc.get("workspaceId"), +}) +print(r["checkoutUrl"]) # open in browser, pay manually +``` + +Plan/price IDs rotate — pull live ones from `POST /api/billing/plans/list`. After payment, verify server-side: `POST /api/billing/subscription/get` → `status: TRIALING`. + +## API surface (reverse-engineered) + +Auth is a `courses_session` cookie (`POST /api/auth/signup {email,password,name}`). Notable endpoints: + +- `POST /api/workspaces/create-personal`, `/api/workspaces/get` +- `POST /api/user/onboarding` (profileData: ageRange, education, howDidYouHear, useCase, complete) +- `POST /api/billing/plans/list | subscription/checkout | subscription/get | usage/get | coupon/validate` +- `POST /api/workspace-assistant/chat` — AI-SDK v5 SSE stream (tool events included — the gateway surfaces them as `[tool name] input -> output`) +- `POST /api/courses/draft/create`, `/api/courses/editor-chat` +- MCP: full **OAuth 2.0 + PKCE** server — `/api/oauth/register` (dynamic client registration), `/api/oauth/authorize` (consent POST needs `Origin`/`Referer` of the consent page or it returns `access_denied`), `/api/oauth/token`. Scopes: `honen:mcp workspace-assistant course:edit site:edit knowledgebase.read knowledgebase.write`. Access token lives 90 days, refresh 365. +- ⚠️ `POST /api/mcp/token` still issues a bearer, but it no longer carries the `workspace-assistant` scope → sandbox calls return `Forbidden: missing MCP scope`. Use `honen_oauth.py` instead. +- `GET /openapi.json` — their own public spec + +## Sandbox (honen-sandbox model) + +Cloud micro-VM ("just-bash"): `python3` (no ssl/pip/network), persistent `/data` (7.6MB), 23 skill guides at `/skills/*.md`, and platform commands `fetch-*` / `do-*` / `navigate-*` (workspace data, courses, invites, analytics...). It is NOT a general PC agent — no outbound internet, no local machine access. + +```bash +python honen_oauth.py you+tag@gmail.com YourPass # -> oauth_token_*.json (full PKCE flow) +``` + +Put `"oauth_token"` into the account's `accounts.jsonl` line and the gateway picks it up (auto re-issues via the OAuth flow on expiry). + +## Disclaimer + +Research/interop toolkit. Respect honen.com ToS and rate limits. + +--- + +[**t.me/AlStack**](https://t.me/AlStack) — AI tools, gateways, farming pipelines diff --git a/accounts.jsonl.example b/accounts.jsonl.example new file mode 100644 index 0000000..acaafd8 --- /dev/null +++ b/accounts.jsonl.example @@ -0,0 +1,2 @@ +{"email": "you+tag1@gmail.com", "password": "StrongPass1!", "cookie": "courses_session=...", "workspace_id": "6ac...", "mcp_token": "eyJ...", "pro": false} +{"email": "you+tag2@gmail.com", "password": "StrongPass2!", "cookie": "courses_session=...", "workspace_id": "6ac...", "mcp_token": "eyJ...", "pro": true, "ai_remaining": 999999} diff --git a/gateway.py b/gateway.py new file mode 100644 index 0000000..e98c28a --- /dev/null +++ b/gateway.py @@ -0,0 +1,330 @@ +""" +gateway.py — OpenAI-compatible gateway over a pool of free Honen.com accounts. + +Models: + honen-assistant -> Workspace Assistant (Claude via AI SDK stream), general chat + tools info + honen-sandbox -> raw bash/python execution in the account's cloud sandbox + (prompt = script; response = stdout/stderr; no LLM, no message quota) + +Free tier per account: 15 AI msgs/month (assistant/editor chat). Sandbox calls via +assistant chat also spend aiMessages; pure MCP bash does NOT (separate quota-free path). + +Run: python gateway.py [--port 8600] [--key honen-local-2026] +Bank: accounts.jsonl (from honen_farm.py). Hot-reload every 60s. + +Endpoints: + GET / dashboard (pool state) + GET /v1/models + POST /v1/chat/completions (stream + non-stream) +""" +import json +import os +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from honen_api import Honen, HonenMCP, HonenError + +HERE = os.path.dirname(os.path.abspath(__file__)) +BANK = os.path.join(HERE, "accounts.jsonl") +STATE_LOCK = threading.Lock() +POOL = [] # list of account dicts +QUARANTINE = {} # email -> reason +USAGE = {} # email -> {"used": int, "remaining": int, "ts": float} + + +def load_pool(): + global POOL + accs = [] + if os.path.exists(BANK): + with open(BANK, encoding="utf-8") as f: + for ln in f: + ln = ln.strip() + if ln: + try: + accs.append(json.loads(ln)) + except ValueError: + pass + with STATE_LOCK: + POOL = accs + for a in accs: + if a.get("pro"): + u = USAGE.setdefault(a["email"], {"used": 0, "remaining": 15, "ts": 0}) + u["remaining"] = max(u["remaining"], a.get("ai_remaining", 999999)) + + +def reloader(): + while True: + time.sleep(60) + try: + load_pool() + except Exception: + pass + + +def pick_account(): + with STATE_LOCK: + cands = [a for a in POOL if a["email"] not in QUARANTINE] + if not cands: + return None + # pro accounts first, then round-robin by fewest recent uses + cands.sort(key=lambda a: (not a.get("pro"), USAGE.get(a["email"], {}).get("used", 0))) + return cands[0] + + +def mark_usage(email, used_delta=1): + u = USAGE.setdefault(email, {"used": 0, "remaining": 15, "ts": 0}) + u["used"] += used_delta + u["remaining"] = max(0, u["remaining"] - used_delta) + u["ts"] = time.time() + if u["remaining"] <= 0: + with STATE_LOCK: + QUARANTINE[email] = "ai quota exhausted" + + +def quarantine(email, reason): + with STATE_LOCK: + QUARANTINE[email] = reason + + +def get_honen(acc): + h = Honen(acc["cookie"]) + try: + s = h.session() + if not s or not s.get("user"): + raise HonenError("dead session") + return h + except Exception: + # relogin + try: + h = Honen.login(acc["email"], acc["password"]) + acc["cookie"] = h.cookie + return h + except Exception as e: + quarantine(acc["email"], f"relogin failed: {str(e)[:80]}") + raise + + +def chat_assistant(acc, messages, stream_writer=None): + h = get_honen(acc) + hist = [] + for m in messages[:-1]: + c = m.get("content") + if isinstance(c, list): + c = " ".join(x.get("text", "") for x in c if isinstance(x, dict)) + hist.append({"role": "user" if m.get("role") == "user" else "assistant", "text": str(c)}) + last = messages[-1] + c = last.get("content") + if isinstance(c, list): + c = " ".join(x.get("text", "") for x in c if isinstance(x, dict)) + text = str(c) + + session_id = acc.get("_session_id") + out = {} + + def on_event(t, ev): + if t == "text-delta" and stream_writer: + stream_writer(ev.get("delta", "")) + + try: + res = h.assistant_chat(text, acc["workspace_id"], session_id=session_id, + history=hist[-10:], timeout=240, on_event=on_event) + except HonenError as e: + msg = str(e) + if "PAYWALL" in msg.upper() or "LIMIT" in msg.upper() or "QUOTA" in msg.upper(): + quarantine(acc["email"], "quota: " + msg[:100]) + raise + acc["_session_id"] = res.get("sessionId") or session_id + mark_usage(acc["email"]) + out["content"] = res.get("text") or "" + if res.get("tools"): + tl = [] + for t in res["tools"]: + o = str(t.get("output", "")) + tl.append(f"[tool {t.get('name')}] {json.dumps(t.get('input'), ensure_ascii=False)[:300]}" + + (f"\n-> {o[:800]}" if o else "")) + out["content"] = (out["content"] + "\n\n" + "\n\n".join(tl)).strip() + return out + + +def _bank_update(acc): + """Persist updated fields of one account back to accounts.jsonl.""" + try: + lines = [json.loads(l) for l in open(BANK, encoding="utf-8") if l.strip()] + for a in lines: + if a.get("email") == acc.get("email"): + a.update({k: v for k, v in acc.items() if k in ("oauth_token", "oauth_refresh", "mcp_token", "cookie", "pro", "ai_remaining")}) + with open(BANK, "w", encoding="utf-8") as f: + for a in lines: + f.write(json.dumps(a, ensure_ascii=False) + "\n") + except Exception: + pass + + +def sandbox_exec(acc, script): + tok = acc.get("oauth_token") or acc.get("mcp_token") + mcp = HonenMCP(tok) + try: + return mcp.bash(acc["workspace_id"], script, timeout=180) + except Exception as e: + # oauth/mcp token could expire or lack scope; re-issue via full OAuth flow + try: + h = get_honen(acc) + from honen_oauth import get_oauth_token + t = get_oauth_token(h, h.cookie.split("courses_session=")[-1]) + acc["oauth_token"] = t["access_token"] + if "refresh_token" in t: + acc["oauth_refresh"] = t["refresh_token"] + _bank_update(acc) + mcp = HonenMCP(acc["oauth_token"]) + return mcp.bash(acc["workspace_id"], script, timeout=180) + except Exception as e2: + quarantine(acc["email"], f"mcp dead: {str(e2)[:100]}") + raise + + +class Handler(BaseHTTPRequestHandler): + api_key = "honen-local-2026" + + def log_message(self, *a): + pass + + def _send(self, code, obj, ctype="application/json"): + b = obj if isinstance(obj, bytes) else json.dumps(obj, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(b))) + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(b) + + def do_OPTIONS(self): + self.send_response(204) + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Headers", "*") + self.send_header("Access-Control-Allow-Methods", "*") + self.end_headers() + + def do_GET(self): + if self.path == "/v1/models": + self._send(200, {"object": "list", "data": [ + {"id": "honen-assistant", "object": "model", "owned_by": "honen"}, + {"id": "honen-sandbox", "object": "model", "owned_by": "honen"}, + ]}) + elif self.path == "/": + with STATE_LOCK: + pool_n = len(POOL) + q = dict(QUARANTINE) + rows = [] + for a in POOL: + u = USAGE.get(a["email"], {}) + rows.append({"email": a["email"], "ws": a["workspace_id"], + "used": u.get("used", 0), + "quarantined": q.get(a["email"], "")}) + html = ("" + "

Honen Gateway

" + f"

pool: {pool_n} | quarantined: {len(q)} | models: honen-assistant (Claude, 15 msg/mo per acc), honen-sandbox (bash/python, quota-free)

" + "" + + "".join(f"" for r in rows) + + "
emailworkspacemsgs usedquarantine
{r['email']}{r['ws']}{r['used']}{r['quarantined']}
") + self._send(200, html.encode(), "text/html; charset=utf-8") + else: + self._send(404, {"error": "not found"}) + + def do_POST(self): + if self.path != "/v1/chat/completions": + return self._send(404, {"error": "not found"}) + auth = self.headers.get("Authorization", "") + if self.api_key and auth != "Bearer " + self.api_key: + return self._send(401, {"error": {"message": "invalid api key"}}) + try: + n = int(self.headers.get("Content-Length", 0)) + body = json.loads(self.rfile.read(n)) + except Exception: + return self._send(400, {"error": {"message": "bad json"}}) + model = body.get("model", "honen-assistant") + messages = body.get("messages") or [] + stream = bool(body.get("stream")) + if not messages: + return self._send(400, {"error": {"message": "messages required"}}) + + acc = pick_account() + if not acc: + return self._send(503, {"error": {"message": "no live accounts in pool"}}) + + cmid = f"chatcmpl-honen-{int(time.time()*1000)}" + created = int(time.time()) + try: + if model == "honen-sandbox": + script = messages[-1].get("content") + if isinstance(script, list): + script = " ".join(x.get("text", "") for x in script if isinstance(x, dict)) + out_text = sandbox_exec(acc, str(script)) + else: + if stream: + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + + def writer(delta): + if not delta: + return + chunk = {"id": cmid, "object": "chat.completion.chunk", "created": created, + "model": model, + "choices": [{"index": 0, "delta": {"content": delta}, "finish_reason": None}]} + self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode()) + self.wfile.flush() + + res = chat_assistant(acc, messages, stream_writer=writer) + end = {"id": cmid, "object": "chat.completion.chunk", "created": created, + "model": model, + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]} + self.wfile.write(f"data: {json.dumps(end)}\n\ndata: [DONE]\n\n".encode()) + return + out_text = chat_assistant(acc, messages)["content"] + resp = {"id": cmid, "object": "chat.completion", "created": created, "model": model, + "choices": [{"index": 0, "message": {"role": "assistant", "content": out_text}, + "finish_reason": "stop"}], + "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}} + self._send(200, resp) + except Exception as e: + # failover once to another account + try: + acc2 = pick_account() + if acc2 and acc2["email"] != acc["email"]: + if model == "honen-sandbox": + out_text = sandbox_exec(acc2, str(script)) + else: + out_text = chat_assistant(acc2, messages)["content"] + resp = {"id": cmid, "object": "chat.completion", "created": created, "model": model, + "choices": [{"index": 0, "message": {"role": "assistant", "content": out_text}, + "finish_reason": "stop"}], + "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}} + return self._send(200, resp) + except Exception as e2: + e = e2 + self._send(502, {"error": {"message": f"{type(e).__name__}: {str(e)[:300]}"}}) + + +def main(): + port = 8600 + key = "honen-local-2026" + argv = sys.argv[1:] + for i, a in enumerate(argv): + if a == "--port": + port = int(argv[i + 1]) + elif a == "--key": + key = argv[i + 1] + Handler.api_key = key + load_pool() + threading.Thread(target=reloader, daemon=True).start() + srv = ThreadingHTTPServer(("0.0.0.0", port), Handler) + print(f"honen gateway on :{port} pool={len(POOL)} key=***") + srv.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/honen_api.py b/honen_api.py new file mode 100644 index 0000000..b0b15fa --- /dev/null +++ b/honen_api.py @@ -0,0 +1,312 @@ +""" +honen_api.py — Honen.com (StudyFetch) private API client. + +Reverse-engineered 2026-10-13. Stdlib only (urllib), Python 3.9+. + +Auth model: + - POST /api/auth/signup {email,password,name} -> 201 + Set-Cookie: courses_session (Hapi iron Fe26.2) + - NO captcha, NO email verification. Cookie lives 7 days; re-obtain via POST /api/auth/login. + - POST /api/mcp/token {workspaceId} -> Fe26.2 bearer for https://honen.com/api/mcp/mcp (MCP, 19 tools) + +Free tier per account (POST /api/billing/usage/get {workspaceId}): + - aiMessagesPerMonth: 15 (workspace assistant + editor chat) + - fastBuildsPerMonth: 1 (course build) + - researchBuildsPerMonth: 0 + +Chat (AI SDK v5 UI Message Stream over SSE): + - POST /api/workspace-assistant/chat (Claude; tool: workspace_sandbox bash) + - POST /api/courses/editor-chat (course builder; tools: course_editor, propose_course_outline) +""" +import json +import re +import ssl +import time +import uuid +import urllib.request +import urllib.error + +BASE = "https://honen.com" +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36") +CTX = ssl.create_default_context() + + +class HonenError(Exception): + pass + + +class Honen: + def __init__(self, cookie: str = None): + self.cookie = cookie # full "courses_session=..." string + + # ---------- low level ---------- + def _req(self, method, path, body=None, headers=None, timeout=60, raw=False): + url = BASE + path + data = None + hdrs = {"User-Agent": UA, "Accept": "application/json"} + if body is not None: + data = json.dumps(body).encode() + hdrs["Content-Type"] = "application/json" + if self.cookie: + hdrs["Cookie"] = self.cookie + if headers: + hdrs.update(headers) + req = urllib.request.Request(url, data=data, headers=hdrs, method=method) + try: + resp = urllib.request.urlopen(req, timeout=timeout, context=CTX) + except urllib.error.HTTPError as e: + txt = e.read().decode("utf-8", "replace") + try: + j = json.loads(txt) + raise HonenError(f"{e.code} {j.get('error', {}).get('code')}: " + f"{j.get('error', {}).get('message')} :: {txt[:300]}") + except (ValueError, HonenError) as ex: + if isinstance(ex, HonenError): + raise + raise HonenError(f"{e.code}: {txt[:300]}") + if raw: + # do NOT consume the body — caller streams it; grab cookie from headers + for k, v in resp.headers.items(): + if k.lower() == "set-cookie" and "courses_session=" in v: + self.cookie = v.split(";")[0] + return resp, None + payload = resp.read() + # capture session cookie if server (re)set it + for k, v in resp.headers.items(): + if k.lower() == "set-cookie" and "courses_session=" in v: + self.cookie = v.split(";")[0] + return json.loads(payload.decode("utf-8", "replace")) + + def post(self, path, body=None, timeout=60): + out = self._req("POST", path, body if body is not None else {}, timeout=timeout) + if isinstance(out, dict) and out.get("success") is False: + raise HonenError(json.dumps(out.get("error"))[:400]) + return out.get("data") if isinstance(out, dict) and "data" in out else out + + # ---------- auth ---------- + @classmethod + def signup(cls, email, password, name): + h = cls() + h._req("POST", "/api/auth/signup", + {"email": email, "password": password, "name": name}, timeout=45) + if not h.cookie: + raise HonenError("signup OK but no session cookie") + return h + + @classmethod + def login(cls, email, password): + h = cls() + h._req("POST", "/api/auth/login", {"email": email, "password": password}, timeout=45) + if not h.cookie: + raise HonenError("login OK but no session cookie") + return h + + def session(self): + out = self._req("GET", "/api/auth/session") + return out.get("data") if isinstance(out, dict) and "data" in out else out + + def logout(self): + return self.post("/api/auth/logout") + + # ---------- onboarding / workspace ---------- + def create_personal_workspace(self): + d = self.post("/api/workspaces/create-personal") + return d # {"workspaceId":..., "slug":...} + + def onboarding_personal(self, age="25-34", edu="college", hear="chatgpt"): + self.post("/api/user/onboarding", {"profileData": {"useCase": "personal"}}) + self.post("/api/user/onboarding", + {"profileData": {"ageRange": age, "education": edu, "howDidYouHear": hear}}) + return self.post("/api/user/onboarding", { + "complete": True, + "profileData": {"ageRange": age, "education": edu, + "howDidYouHear": hear, "useCase": "personal"}}) + + def workspace_get(self, workspace_id): + return self.post("/api/workspaces/get", {"workspaceId": workspace_id}) + + def usage(self, workspace_id): + return self.post("/api/billing/usage/get", {"workspaceId": workspace_id})["usage"] + + def plans(self): + return self.post("/api/billing/plans/list", {})["plans"] + + def checkout_url(self, stripe_price_id): + return self.post("/api/billing/subscription/checkout", + {"stripePriceId": stripe_price_id})["checkoutUrl"] + + def validate_coupon(self, code): + try: + return self.post("/api/billing/coupon/validate", {"code": code}) + except HonenError: + return None + + def mcp_token(self, workspace_id): + return self.post("/api/mcp/token", {"workspaceId": workspace_id})["token"] + + # ---------- courses ---------- + def draft_create(self, topic, content_type="COURSE", material_refs=None): + body = {"topic": topic, "contentType": content_type} + if material_refs: + body["materialRefs"] = material_refs + return self.post("/api/courses/draft/create", body, timeout=90) + + def course_update(self, course_id, **fields): + return self.post("/api/courses/update", {"courseId": course_id, **fields}) + + # ---------- chat (AI SDK v5 SSE) ---------- + def _chat_stream(self, api_path, text, session_id=None, workspace_id=None, + course_id=None, history=None, timeout=300, on_event=None): + msgs = [] + for i, hm in enumerate(history or []): + msgs.append({"id": f"h{i}", "role": hm["role"], + "parts": [{"type": "text", "text": hm["text"]}]}) + mid = f"m-{uuid.uuid4().hex[:8]}" + msgs.append({"id": mid, "role": "user", "parts": [{"type": "text", "text": text}]}) + body = {"id": str(uuid.uuid4()), "messages": msgs, + "trigger": "submit-message", "messageId": mid} + if session_id: + body["sessionId"] = session_id + if course_id: + body["courseId"] = course_id + if workspace_id: + body["pageContext"] = {"pathname": "/dashboard/create-course", + "workspaceId": workspace_id} + resp, _ = self._req("POST", api_path, body, + headers={"Accept": "text/event-stream"}, + timeout=timeout, raw=True) + # stream manually + return resp + + @staticmethod + def parse_ai_stream(resp, on_event=None): + """Yield (type, data) from an AI SDK v5 SSE response; returns dict summary.""" + text_parts, tools, session_id, finish = [], [], None, None + while True: + raw = resp.readline() + if not raw: + break + line = raw.decode("utf-8", "replace").strip() + if not line.startswith("data: "): + continue + d = line[6:] + if d == "[DONE]": + continue + try: + ev = json.loads(d) + except ValueError: + continue + t = ev.get("type") + if on_event: + on_event(t, ev) + if t == "text-delta": + text_parts.append(ev.get("delta", "")) + elif t == "start": + session_id = (ev.get("messageMetadata") or {}).get("sessionId") or session_id + elif t == "tool-input-available": + tools.append({"name": ev.get("toolName"), "input": ev.get("input")}) + elif t == "tool-output-available": + if tools: + tools[-1]["output"] = ev.get("output") + elif t == "finish": + finish = ev.get("messageMetadata") or {} + session_id = finish.get("sessionId") or session_id + return {"text": "".join(text_parts), "tools": tools, + "sessionId": session_id, "finish": finish} + + def assistant_chat(self, text, workspace_id, session_id=None, history=None, + timeout=300, on_event=None): + resp = self._chat_stream("/api/workspace-assistant/chat", text, + session_id=session_id, workspace_id=workspace_id, + history=history, timeout=timeout) + return self.parse_ai_stream(resp, on_event) + + def editor_chat(self, text, course_id, session_id=None, history=None, + timeout=600, on_event=None): + resp = self._chat_stream("/api/courses/editor-chat", text, + session_id=session_id, course_id=course_id, + history=history, timeout=timeout) + return self.parse_ai_stream(resp, on_event) + + # ---------- MCP (machine access, bearer token) ---------- +class HonenMCP: + """MCP streamable-http client for https://honen.com/api/mcp/mcp (no cookie needed).""" + ENDPOINT = BASE + "/api/mcp/mcp" + + def __init__(self, token: str): + self.token = token + self._id = 0 + + def call(self, method, params=None, timeout=120): + self._id += 1 + body = {"jsonrpc": "2.0", "id": self._id, "method": method} + if params is not None: + body["params"] = params + data = json.dumps(body).encode() + req = urllib.request.Request(self.ENDPOINT, data=data, method="POST", headers={ + "Authorization": "Bea" + "rer " + self.token, + "Content-Type": "application/json", + "Accept": "application/json, text/event-stream", + "User-Agent": UA, + }) + raw = urllib.request.urlopen(req, timeout=timeout, context=CTX).read().decode("utf-8", "replace") + for line in raw.split("\n"): + line = line.strip() + if line.startswith("data: "): + return json.loads(line[6:]) + return json.loads(raw) + + def initialize(self): + return self.call("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, + "clientInfo": {"name": "honen-toolkit", "version": "1.0"}}) + + def tools_list(self): + return [t["name"] for t in self.call("tools/list", {}).get("result", {}).get("tools", [])] + + def tool(self, name, arguments, timeout=180): + r = self.call("tools/call", {"name": name, "arguments": arguments}, timeout=timeout) + res = r.get("result", {}) + out = [] + for c in res.get("content", []): + if c.get("type") == "text": + out.append(c.get("text", "")) + return "\n".join(out) + + def bash(self, workspace_id, script, timeout=180): + """Run bash/python in the Workspace Assistant cloud sandbox.""" + return self.tool("workspace_assistant", + {"workspaceId": workspace_id, "script": script}, timeout=timeout) + + +# ---------- one-shot provisioning ---------- +def provision_account(email, password, name, age="25-34", edu="college", hear="chatgpt"): + """signup -> personal workspace -> onboarding -> mcp token -> usage. Returns account dict.""" + h = Honen.signup(email, password, name) + ws = h.create_personal_workspace() + wsid = ws["workspaceId"] + h.onboarding_personal(age=age, edu=edu, hear=hear) + usage = h.usage(wsid) + tok = h.mcp_token(wsid) + sess = h.session() + return { + "email": email, "password": password, "name": name, + "user_id": sess["user"]["id"], + "workspace_id": wsid, "slug": ws.get("slug"), + "cookie": h.cookie, "mcp_token": tok, + "ai_messages_per_month": usage.get("aiMessagesPerMonth"), + "fast_builds_per_month": usage.get("fastBuildsPerMonth"), + "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + } + + +if __name__ == "__main__": + import sys + if len(sys.argv) > 1 and sys.argv[1] == "selftest": + email = sys.argv[2] if len(sys.argv) > 2 else None + pwd = sys.argv[3] if len(sys.argv) > 3 else None + if email and pwd: + h = Honen.login(email, pwd) + s = h.session() + print("login OK:", s["user"]["email"], "id", s["user"]["id"]) + else: + print("usage: python honen_api.py selftest ") diff --git a/honen_farm.py b/honen_farm.py new file mode 100644 index 0000000..d673486 --- /dev/null +++ b/honen_farm.py @@ -0,0 +1,105 @@ +""" +honen_farm.py — mass-register Honen.com accounts. + +Usage: + python honen_farm.py [start_index] [--mail-base you@gmail.com] + +No captcha, no email verification. Each account: + signup -> personal workspace -> onboarding complete -> MCP token -> usage snapshot +Bank: accounts.jsonl (one JSON per line), used emails: used_emails.txt +Free tier per account: 15 AI messages/month + 1 fast course build. +""" +import json +import os +import random +import string +import sys +import time + +from honen_api import HonenError, provision_account + +HERE = os.path.dirname(os.path.abspath(__file__)) +BANK = os.path.join(HERE, "accounts.jsonl") +USED = os.path.join(HERE, "used_emails.txt") + +FIRST = ["Alex", "Jordan", "Morgan", "Casey", "Riley", "Taylor", "Jamie", "Drew", + "Sam", "Robin", "Chris", "Pat", "Nikola", "Viktor", "Lena", "Marco", + "Sofia", "Ivan", "Olga", "Dmitri", "Anna", "Pavel", "Mira", "Leon"] +LAST = ["Keller", "Novak", "Brandt", "Fischer", "Weber", "Wolf", "Sokolov", "Orlov", + "Marchetti", "Duval", "Nowak", "Horvat", "Petrov", "Lindner", "Vogel", "Kolar"] + + +def gen_password(): + alpha = string.ascii_letters + digits = string.digits + p = (random.choice(string.ascii_uppercase) + + "".join(random.choices(alpha, k=10)) + + "".join(random.choices(digits, k=4)) + + random.choice("!@#$%&*") + + random.choice(string.ascii_uppercase)) + lst = list(p) + random.shuffle(lst) + return "".join(lst) + + +def load_used(): + if not os.path.exists(USED): + return set() + with open(USED, encoding="utf-8") as f: + return {ln.strip().lower() for ln in f if ln.strip()} + + +def main(): + args = [a for a in sys.argv[1:] if not a.startswith("--")] + n = int(args[0]) if args else 3 + start = int(args[1]) if len(args) > 1 else 0 + mail_base = "baradok609@gmail.com" + for a in sys.argv[1:]: + if a.startswith("--mail-base="): + mail_base = a.split("=", 1)[1] + elif a.startswith("--mail-base"): + mail_base = sys.argv[sys.argv.index(a) + 1] + + used = load_used() + ok = fail = 0 + for i in range(start, start + n * 3): + if ok >= n: + break + tag = "hn" + "".join(random.choices(string.ascii_lowercase + string.digits, k=10)) + if "+" in mail_base and "@" in mail_base: + base, dom = mail_base.split("@") + email = f"{base}+{tag}@{dom}" + else: + email = f"{mail_base.split('@')[0]}+{tag}@{mail_base.split('@')[-1]}" + if email.lower() in used: + continue + name = f"{random.choice(FIRST)} {random.choice(LAST)}" + pwd = gen_password() + t0 = time.time() + try: + acc = provision_account(email, pwd, name) + with open(BANK, "a", encoding="utf-8") as f: + f.write(json.dumps(acc, ensure_ascii=False) + "\n") + with open(USED, "a", encoding="utf-8") as f: + f.write(email.lower() + "\n") + ok += 1 + print(f"[{ok}/{n}] OK {email} ws={acc['workspace_id']} " + f"msgs={acc['ai_messages_per_month']} builds={acc['fast_builds_per_month']} " + f"({time.time()-t0:.1f}s)") + except HonenError as e: + fail += 1 + print(f"[fail] {email}: {str(e)[:160]}") + with open(USED, "a", encoding="utf-8") as f: + f.write(email.lower() + "\n") + if "RATE" in str(e).upper() or "429" in str(e): + print("rate limited — sleeping 90s") + time.sleep(90) + except Exception as e: + fail += 1 + print(f"[err] {email}: {type(e).__name__} {str(e)[:140]}") + time.sleep(random.uniform(4, 9)) + print(f"\nDONE ok={ok} fail={fail} bank={BANK}") + + +if __name__ == "__main__": + main() diff --git a/honen_oauth.py b/honen_oauth.py new file mode 100644 index 0000000..bf7ffe1 --- /dev/null +++ b/honen_oauth.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Honen OAuth for MCP — получить access_token со скоупом workspace-assistant. + +/api/mcp/token больше НЕ даёт скоуп workspace-assistant (sandbox bash = Forbidden). +Нужен полный OAuth 2.0 + PKCE flow через consent-страницу: + register (один раз, client_id переиспользуется) -> authorize -> consent POST -> token. +access_token живёт 90 дней, refresh_token — 365. + +Usage: python honen_oauth.py (логин по креденшенам) + python honen_oauth.py --cookie +Пишет oauth_token.json (или oauth_token_.json). +""" +import json, ssl, sys, re, secrets, hashlib, base64, urllib.request, urllib.parse, urllib.error, os + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from honen_api import Honen, UA + +BASE = "https://honen.com" +CTX = ssl.create_default_context() +SCOPES = "honen:mcp workspace-assistant course:edit site:edit knowledgebase.read knowledgebase.write" +CLIENT_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "oauth_client.json") + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + + +def _open_noredirect(url, data=None, headers=None, method=None): + op = urllib.request.build_opener(_NoRedirect, urllib.request.HTTPSHandler(context=CTX)) + req = urllib.request.Request(url, data=data, method=method, + headers={"User-Agent": UA, **(headers or {})}) + try: + resp = op.open(req, timeout=30) + return resp.status, dict(resp.headers), resp.read().decode(errors="replace") + except urllib.error.HTTPError as e: + return e.code, dict(e.headers), e.read().decode(errors="replace") + + +def get_client(h): + """Динамическая регистрация OAuth-клиента (кэшируется в oauth_client.json).""" + if os.path.exists(CLIENT_FILE): + reg = json.load(open(CLIENT_FILE)) + if reg.get("client_id"): + return reg + s, _, b = _open_noredirect(BASE + "/api/oauth/register", + data=json.dumps({"client_name": "eni-toolkit", "redirect_uris": ["http://localhost:33418/callback"], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], "token_endpoint_auth_method": "none"}).encode(), + headers={"Content-Type": "application/json"}, method="POST") + if s not in (200, 201): + raise RuntimeError(f"oauth register failed {s}: {b[:200]}") + reg = json.loads(b) + json.dump(reg, open(CLIENT_FILE, "w")) + return reg + + +def authorize(h, cookie, reg): + """Authorize + consent approve (POST с Origin/Referer обязателен — иначе access_denied).""" + verifier = secrets.token_urlsafe(48) + challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() + state = secrets.token_hex(8) + params = {"response_type": "code", "client_id": reg["client_id"], + "redirect_uri": reg["redirect_uris"][0], "scope": SCOPES, "state": state, + "code_challenge": challenge, "code_challenge_method": "S256"} + consent = BASE + "/oauth/authorize?" + urllib.parse.urlencode(params) + s, hd, b = _open_noredirect(consent, headers={"Cookie": "courses_session=" + cookie, "Accept": "text/html"}) + if s not in (200, 307): + raise RuntimeError(f"consent page HTTP {s}") + if s == 307: # /api/oauth/authorize -> /oauth/authorize + s, hd, b = _open_noredirect(hd["Location"] if "Location" in hd else hd.get("location", consent), + headers={"Cookie": "courses_session=" + cookie, "Accept": "text/html"}) + if "decision" not in b and "code=" not in (hd.get("Location") or hd.get("location") or ""): + raise RuntimeError("consent form not found (session dead?)") + data = urllib.parse.urlencode({**params, "decision": "approve"}).encode() + s2, hd2, b2 = _open_noredirect(BASE + "/api/oauth/authorize", data=data, method="POST", headers={ + "Cookie": "courses_session=" + cookie, "Content-Type": "application/x-www-form-urlencoded", + "Origin": BASE, "Referer": consent, "Sec-Fetch-Site": "same-origin", + "Sec-Fetch-Mode": "navigate", "Sec-Fetch-Dest": "document"}) + loc = hd2.get("Location") or hd2.get("location") or "" + if "code=" not in loc: + raise RuntimeError(f"approve failed {s2}: {(loc or b2)[:200]}") + q = urllib.parse.parse_qs(urllib.parse.urlparse(loc).query) + if q.get("state", [""])[0] != state: + raise RuntimeError("state mismatch") + return q["code"][0], verifier + + +def exchange(code, verifier, reg): + data = urllib.parse.urlencode({"grant_type": "authorization_code", "code": code, + "redirect_uri": reg["redirect_uris"][0], "client_id": reg["client_id"], + "code_verifier": verifier}).encode() + s, _, b = _open_noredirect(BASE + "/api/oauth/token", data=data, method="POST", + headers={"Content-Type": "application/x-www-form-urlencoded"}) + if s != 200: + raise RuntimeError(f"token exchange {s}: {b[:200]}") + return json.loads(b) + + +def refresh(refresh_token, reg): + data = urllib.parse.urlencode({"grant_type": "refresh_token", "refresh_token": refresh_token, + "client_id": reg["client_id"]}).encode() + s, _, b = _open_noredirect(BASE + "/api/oauth/token", data=data, method="POST", + headers={"Content-Type": "application/x-www-form-urlencoded"}) + if s != 200: + raise RuntimeError(f"refresh {s}: {b[:200]}") + return json.loads(b) + + +def get_oauth_token(h, cookie, reg=None): + reg = reg or get_client(h) + code, verifier = authorize(h, cookie, reg) + return exchange(code, verifier, reg) + + +if __name__ == "__main__": + args = sys.argv[1:] + if args and args[0] == "--cookie": + h = Honen(cookie=args[1]) + cookie = args[1].split("courses_session=")[-1] + tag = "cookie" + elif len(args) >= 2: + h = Honen(); h.login(args[0], args[1]); cookie = h.cookie.split("courses_session=")[-1] + tag = args[0] + else: + print(__doc__); raise SystemExit(1) + tok = get_oauth_token(h, cookie) + out = f"oauth_token_{tag.replace('@','_at_')}.json" if tag != "cookie" else "oauth_token.json" + json.dump(tok, open(out, "w")) + print(f"OK scope={tok.get('scope','')[:60]} expires_in={tok.get('expires_in')} -> {out}") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..080a066 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +# honen-toolkit — stdlib only (urllib/http.server/json). No pip deps required.