#!/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}")