Files
honen-toolkit/honen_api.py
T

313 lines
13 KiB
Python

"""
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 <email> <password>")