"""Pure-HTTP SSO cookie -> OAuth PKCE tokens for Grok Build/CLI access.""" from __future__ import annotations import base64 import hashlib import json import re import secrets import time from typing import Any, Callable from urllib.parse import parse_qs, quote, unquote, urlencode, urljoin, urlparse from . import grpcweb from .oauth_device import CLIENT_ID, ISSUER, SCOPE from .proxyutil import resolve_proxy, set_runtime_proxy AUTHORIZATION_ENDPOINT = f"{ISSUER}/oauth2/authorize" TOKEN_ENDPOINT = f"{ISSUER}/oauth2/token" ACCOUNTS_ORIGIN = "https://accounts.x.ai" CREATE_COOKIE_SETTER_RPC = f"{ACCOUNTS_ORIGIN}/auth_mgmt.AuthManagement/CreateCookieSetterLink" # Updated 2026-08-16: x.ai rotated the consent server-action id AND moved it out # of the initial HTML into a client-rendered JS chunk (createServerReference in # module 827004). This value is the fast path; _extract_consent_action_id_from_bundles # self-heals the next rotation. SUBMIT_OAUTH2_CONSENT_ACTION = "40b2dd48cd9fcc160a2c686b89f9f3468af49c36ca" DEFAULT_REDIRECT_URI = "http://127.0.0.1:56121/callback" LogFn = Callable[[str], None] class PKCEMintError(RuntimeError): """PKCE protocol path failed; caller may fall back to other mint methods. Structured fields (preferred over message substring matching): - ``code``: stable machine token (e.g. consent_action_missing, cancelled) - ``retryable``: False when remint/spin will not heal (empty SPA / missing action id / cancelled / missing dependency). Callers still may residual to device/browser per product flags; retryable only classifies the PKCE failure itself. """ def __init__( self, message: str, *, code: str = "pkce_error", retryable: bool = True, ) -> None: super().__init__(message) self.code = str(code or "pkce_error").strip() or "pkce_error" self.retryable = bool(retryable) def _noop_log(_: str) -> None: return None def _b64url(raw: bytes) -> str: return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=") def _code_verifier() -> str: return _b64url(secrets.token_bytes(48)) def _code_challenge(verifier: str) -> str: return _b64url(hashlib.sha256(verifier.encode("ascii")).digest()) def _session(proxy: str | None): try: from curl_cffi import requests as cf_requests except ImportError as e: raise PKCEMintError( "curl_cffi not installed; cannot run PKCE mint", code="dependency", retryable=False, ) from e kwargs: dict[str, Any] = {"impersonate": "chrome131"} resolved = resolve_proxy(proxy) if resolved: kwargs["proxies"] = {"http": resolved, "https": resolved} return cf_requests.Session(**kwargs) def _set_sso_cookie(session: Any, sso_cookie: str) -> None: sso_cookie = (sso_cookie or "").strip() if not sso_cookie: raise PKCEMintError("empty sso cookie", code="empty_sso", retryable=False) for domain in ("accounts.x.ai", ".accounts.x.ai", ".x.ai", "auth.x.ai"): try: session.cookies.set("sso", sso_cookie, domain=domain, path="/") except Exception: pass try: session.cookies.set("sso-rw", sso_cookie, domain=domain, path="/") except Exception: pass def _grpc_headers(referer: str) -> dict[str, str]: return { "content-type": "application/grpc-web+proto", "x-grpc-web": "1", "x-user-agent": "connect-es/2.1.1", "accept": "*/*", "origin": ACCOUNTS_ORIGIN, "referer": referer, "sec-fetch-site": "same-origin", "sec-fetch-mode": "cors", "sec-fetch-dest": "empty", } def _extract_urls_from_fields(fields: list[dict[str, Any]]) -> list[str]: urls: list[str] = [] for field in fields: if field.get("type") == "string": value = str(field.get("value") or "") if value.startswith(("http://", "https://")): urls.append(value) elif field.get("type") == "bytes" and field.get("hex"): try: urls.extend(_extract_urls_from_fields(grpcweb.decode_message(bytes.fromhex(field["hex"])))) except Exception: pass return urls def _parse_grpc_error(headers: dict[str, str], body: bytes) -> tuple[int | None, str]: status = headers.get("grpc-status") message = unquote(headers.get("grpc-message") or "") if status is not None: try: return int(status), message except ValueError: return None, message try: parsed = grpcweb.parse_response(body) except Exception: return None, message if parsed.get("grpc_status") is not None: return int(parsed["grpc_status"]), message or str(parsed.get("trailers") or "") return None, message def _build_authorization_url( *, client_id: str, redirect_uri: str, state: str, nonce: str, code_challenge: str, scope: str, ) -> str: params = { "client_id": client_id, "code_challenge": code_challenge, "code_challenge_method": "S256", "nonce": nonce, "plan": "generic", "redirect_uri": redirect_uri, "referrer": "cli-proxy-api", "response_type": "code", "scope": scope, "state": state, } return AUTHORIZATION_ENDPOINT + "?" + urlencode(params) def _code_from_url(url: str, state: str) -> str: qs = parse_qs(urlparse(url).query) if (qs.get("state") or [""])[0] != state: raise PKCEMintError( "authorization failed: state mismatch", code="state_mismatch", retryable=True, ) code = (qs.get("code") or [""])[0] if not code: raise PKCEMintError( f"authorization failed: missing code in {url[:200]}", code="missing_code", retryable=True, ) return code def _extract_action_id_from_html(page_html: str | None) -> str | None: """Parse Next.js server-action id for submitOAuth2Consent from consent HTML/RSC. Returns None for empty/SPA shells so callers do not silently POST a stale hardcoded action id (live symptom: HTTP 404 "Server action not found"). """ if not page_html or not isinstance(page_html, str): return None text = page_html if len(text) < 40 and "createServerReference" not in text and "submitOAuth2Consent" not in text: return None # 1) createServerReference)("id", ... "submitOAuth2Consent" m = re.search( r'createServerReference\)\("([a-f0-9]{40,44})"[^)]*submitOAuth2Consent', text, ) if m: return m.group(1) # 2) name-before-id / flight payload near submitOAuth2Consent # e.g. submitOAuth2Consent",{id:"…"} or {"id":"…","bound":null},"submitOAuth2Consent" near = re.search( r'submitOAuth2Consent["\']?\s*[,}][\s\S]{0,200}?"([a-f0-9]{40,44})"' r'|' r'"([a-f0-9]{40,44})"[\s\S]{0,200}?submitOAuth2Consent' r'|' r'submitOAuth2Consent["\']?\s*,\s*\{[^}]*?id["\']?\s*:\s*["\']([a-f0-9]{40,44})', text, ) if near: for g in near.groups(): if g: return g # 3) next-action header value embedded in HTML m = re.search( r'(?:next-action|nextAction)["\']?\s*[:=]\s*["\']([a-f0-9]{40,44})', text, re.I, ) if m: return m.group(1) # 4) last-resort: single anonymous createServerReference id on page refs = re.findall(r'createServerReference\)\("([a-f0-9]{40,44})"', text) if len(refs) == 1: return refs[0] return None # createServerReference)("",callServer,void 0,findSourceMapURL,"submitOAuth2Consent") # — the consent server action on the current (2026-08-16) CSR page. The action # NAME is the server reference's last argument, which disambiguates it from other # page actions (e.g. getSession ends with "getSession"). Same shape strategy #1 # extracts from HTML, but the reference lives in a JS chunk, not the initial HTML. _SCRIPT_SRC_RE = re.compile(r']*src="([^"]+)"', re.I) _SERVER_REF_CONSENT_RE = re.compile( r'createServerReference\)\("([a-f0-9]{40,44})"[^)]*submitOAuth2Consent' ) def _extract_consent_action_id_from_bundles( session: Any, page_html: str | None, timeout: float = 30.0, ) -> str | None: """Scan the consent page's referenced JS chunks for the server-action id. x.ai's consent page is client-rendered (Turbopack): the submitOAuth2Consent server-action reference lives in a JS chunk, not the initial HTML. We fetch the chunks named by ``page_html``