recovered from aaronjaworski710
CI / offline-tests (push) Has been cancelled
CI / web-unit-tests (push) Has been cancelled
CI / package-console10 (push) Has been cancelled

This commit is contained in:
reform
2026-10-23 20:02:14 +03:00
commit 8044e88be4
409 changed files with 104886 additions and 0 deletions
+88
View File
@@ -0,0 +1,88 @@
"""CPA xAI (Grok Build free) auth helpers for the register machine.
Produce CLIProxyAPI-compatible ``xai-<email>.json`` credentials.
"""
from .accounts import (
AccountLine,
email_in_existing,
email_match_keys,
existing_cpa_emails,
format_account_line,
normalize_sso_cookie,
parse_accounts_file,
)
from .mint import mint_and_export
from .pkce_mint import PKCEMintError, mint_with_sso_pkce
from .probe import classify_chat_probe, probe_mini_response, probe_models
from .protocol_mint import (
ProtocolMintError,
extract_sso_from_cookies,
mint_with_sso_protocol,
)
from .refresh import (
access_token_usable,
ensure_auth_tokens,
refresh_auth_file,
refresh_xai_tokens,
)
from .schema import (
CLIENT_ID,
DEFAULT_BASE_URL,
DEFAULT_CLIENT_HEADERS,
DEFAULT_REDIRECT_URI,
DEFAULT_TOKEN_ENDPOINT,
build_cpa_xai_auth,
credential_file_name,
expired_from_access_token,
)
from .writer import (
is_chat_retryable_auth,
load_entitlement_denied_emails,
patch_cpa_xai_auth,
record_entitlement_denied,
write_cpa_xai_auth,
)
# CLIENT_ID lives in oauth_device; re-export from schema if present
try:
from .oauth_device import CLIENT_ID as OAUTH_CLIENT_ID
except Exception: # pragma: no cover
OAUTH_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
__all__ = [
"AccountLine",
"CLIENT_ID",
"DEFAULT_BASE_URL",
"DEFAULT_CLIENT_HEADERS",
"DEFAULT_REDIRECT_URI",
"DEFAULT_TOKEN_ENDPOINT",
"OAUTH_CLIENT_ID",
"PKCEMintError",
"ProtocolMintError",
"build_cpa_xai_auth",
"classify_chat_probe",
"credential_file_name",
"email_in_existing",
"email_match_keys",
"existing_cpa_emails",
"expired_from_access_token",
"extract_sso_from_cookies",
"format_account_line",
"is_chat_retryable_auth",
"load_entitlement_denied_emails",
"mint_and_export",
"mint_with_sso_pkce",
"mint_with_sso_protocol",
"normalize_sso_cookie",
"parse_accounts_file",
"patch_cpa_xai_auth",
"probe_mini_response",
"probe_models",
"record_entitlement_denied",
"access_token_usable",
"ensure_auth_tokens",
"refresh_auth_file",
"refresh_xai_tokens",
"write_cpa_xai_auth",
]
+121
View File
@@ -0,0 +1,121 @@
"""Parse register machine accounts_cli.txt lines."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
def normalize_sso_cookie(value: str | None) -> str:
"""Normalize SSO cookie / JWT-like token from ledger or browser export.
Some capture paths prefix a stray ``-`` before ``eyJ...``. Protocol mint
treats that as invalid and lands on sign-in; stripping restores a usable JWT.
Only strips leading dashes when a JWT header (``eyJ``) is nearby — never
blindly lstrip all dashes from arbitrary session ids.
"""
s = (value or "").strip()
if not s:
return ""
# Strip accidental leading dashes only when a JWT header is present nearby.
while s.startswith("-") and "eyJ" in s[:8]:
s = s[1:].lstrip()
return s.strip()
def format_account_line(email: str, password: str, sso: str | None = None) -> str:
"""Build one accounts_cli ledger line with normalized SSO."""
email_s = (email or "").strip()
password_s = (password or "").strip()
sso_s = normalize_sso_cookie(sso)
if sso_s:
return f"{email_s}----{password_s}----{sso_s}\n"
return f"{email_s}----{password_s}\n"
def email_match_keys(email: str) -> set[str]:
"""Identity keys for plus-alias ↔ sanitized filename matching.
CPA filenames replace ``+`` (and other unsafe chars) with ``-``, so
``user+abc@x.com`` becomes stem ``user-abc@x.com``. Skip/existing checks
must treat both forms as the same account.
"""
e = (email or "").strip().lower()
if not e:
return set()
keys = {e, e.replace("+", "-")}
try:
from .schema import credential_file_name
fn = credential_file_name(e)
if fn.startswith("xai-") and fn.endswith(".json"):
stem = fn[len("xai-") : -len(".json")].lower()
if stem:
keys.add(stem)
except Exception:
pass
return keys
def email_in_existing(email: str, existing: set[str]) -> bool:
"""True if email (any alias/sanitized form) is already in existing set."""
if not existing:
return False
return bool(email_match_keys(email) & existing)
@dataclass
class AccountLine:
email: str
password: str
sso: str
raw: str
line_no: int
def parse_accounts_file(path: str | Path) -> list[AccountLine]:
path = Path(path)
out: list[AccountLine] = []
if not path.is_file():
return out
for i, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
s = line.strip()
if not s or s.startswith("#"):
continue
parts = s.split("----")
if len(parts) < 2:
continue
email = parts[0].strip()
password = parts[1].strip()
sso = normalize_sso_cookie(parts[2] if len(parts) > 2 else "")
if not email or not password:
continue
out.append(AccountLine(email=email, password=password, sso=sso, raw=s, line_no=i))
return out
def existing_cpa_emails(auth_dir: str | Path) -> set[str]:
"""Emails already present as xai-*.json in auth_dir.
Returns an expanded key set (raw email, plus→dash, filename stem) so
skip-existing works for Hotmail plus-aliases even when JSON lacks email.
"""
auth_dir = Path(auth_dir)
found: set[str] = set()
if not auth_dir.is_dir():
return found
for p in auth_dir.glob("xai-*.json"):
name = p.name[len("xai-") : -len(".json")]
if name:
found |= email_match_keys(name)
try:
import json
d = json.loads(p.read_text(encoding="utf-8"))
em = str(d.get("email") or "").strip()
if em:
found |= email_match_keys(em)
except Exception:
continue
return found
File diff suppressed because it is too large Load Diff
+107
View File
@@ -0,0 +1,107 @@
"""Minimal gRPC-web/protobuf codec for accounts.x.ai AuthManagement calls."""
from __future__ import annotations
import struct
from typing import Any
WT_VARINT = 0
WT_FIXED64 = 1
WT_LEN = 2
WT_FIXED32 = 5
def encode_varint(value: int) -> bytes:
if value < 0:
raise ValueError("varint must be non-negative")
out = bytearray()
while True:
byte = value & 0x7F
value >>= 7
if value:
out.append(byte | 0x80)
else:
out.append(byte)
return bytes(out)
def _tag(field_no: int, wire_type: int) -> bytes:
return encode_varint((field_no << 3) | wire_type)
def encode_string(field_no: int, text: str) -> bytes:
raw = text.encode("utf-8")
return _tag(field_no, WT_LEN) + encode_varint(len(raw)) + raw
def frame_request(message: bytes) -> bytes:
return b"\x00" + struct.pack(">I", len(message)) + message
def _read_varint(data: bytes, i: int) -> tuple[int, int]:
result = 0
shift = 0
while True:
b = data[i]
i += 1
result |= (b & 0x7F) << shift
if not (b & 0x80):
return result, i
shift += 7
def decode_message(data: bytes) -> list[dict[str, Any]]:
fields: list[dict[str, Any]] = []
i = 0
n = len(data)
while i < n:
tag, i = _read_varint(data, i)
field_no = tag >> 3
wt = tag & 0x07
if wt == WT_VARINT:
val, i = _read_varint(data, i)
fields.append({"field": field_no, "type": "varint", "value": val})
elif wt == WT_FIXED64:
chunk = data[i : i + 8]
i += 8
fields.append({"field": field_no, "type": "fixed64", "hex": chunk.hex()})
elif wt == WT_LEN:
ln, i = _read_varint(data, i)
chunk = data[i : i + ln]
i += ln
try:
s = chunk.decode("utf-8")
if s.isprintable():
fields.append({"field": field_no, "type": "string", "value": s})
continue
except UnicodeDecodeError:
pass
fields.append({"field": field_no, "type": "bytes", "hex": chunk.hex(), "len": ln})
elif wt == WT_FIXED32:
chunk = data[i : i + 4]
i += 4
fields.append({"field": field_no, "type": "fixed32", "hex": chunk.hex()})
else:
raise ValueError(f"unsupported wire type {wt} at offset {i}")
return fields
def parse_response(body: bytes) -> dict[str, Any]:
messages: list[list[dict[str, Any]]] = []
trailers: dict[str, str] = {}
i = 0
n = len(body)
while i + 5 <= n:
flag = body[i]
length = struct.unpack(">I", body[i + 1 : i + 5])[0]
payload = body[i + 5 : i + 5 + length]
i += 5 + length
if flag & 0x80:
for line in payload.decode("utf-8", "replace").split("\r\n"):
if ":" in line:
k, v = line.split(":", 1)
trailers[k.strip().lower()] = v.strip()
else:
messages.append(decode_message(payload))
grpc_status = int(trailers["grpc-status"]) if "grpc-status" in trailers else None
return {"messages": messages, "trailers": trailers, "grpc_status": grpc_status}
+762
View File
@@ -0,0 +1,762 @@
"""High-level: mint CPA xai-*.json for one free registered account."""
from __future__ import annotations
from pathlib import Path
from typing import Any, Callable
from .accounts import normalize_sso_cookie
from .browser_confirm import mint_with_browser
from .pkce_mint import PKCEMintError, mint_with_sso_pkce
from .probe import (
MODELS_MISSING_ERROR,
MODELS_MISSING_REASON,
apply_chat_probe_to_result,
build_probe_transport,
pick_chat_probe_model,
probe_chat_with_retries,
probe_models,
resolve_gate_probe_policy,
)
from .protocol_mint import ProtocolMintError, extract_sso_from_cookies, mint_with_sso_protocol
from .proxyutil import proxy_log_label, resolve_proxy, set_runtime_proxy
from .schema import DEFAULT_BASE_URL, build_cpa_xai_auth, credential_file_name
from .writer import stamp_auth_chat_fields, write_cpa_xai_auth
LogFn = Callable[[str], None]
def _noop(_: str) -> None:
return None
def _is_pkce_non_retryable(err: str | Exception | None) -> bool:
"""True when this PKCE failure must not remint-spin the same PKCE path.
Covers more than empty SPA / action-id extract:
- structured ``retryable=False`` (any code)
- structured codes: consent_action_missing / consent_action_rejected /
dependency / empty_sso / cancelled
- legacy message needles for consent HTML / Server Action extract
Residual policy is separate: non-retryable consent shells may still fall
through to device/browser when ``allow_device_flow_fallback`` is True.
Cancel is non-retryable *and* must short-circuit residual (see
``_is_cancelled_error``) — do not spend device/browser after abort.
Distinct from transient network (token_exchange, state_mismatch, etc.).
"""
if isinstance(err, PKCEMintError):
if err.retryable is False:
return True
code = str(getattr(err, "code", "") or "").strip().lower()
if code in {
"consent_action_missing",
"consent_action_rejected",
"dependency",
"empty_sso",
"cancelled",
}:
return True
# Structured True/unknown → use message needles below for residual classes
err = str(err)
s = (str(err) if err is not None else "").lower()
if not s:
return False
needles = (
"server action not found",
"consent html missing",
"submitoauth2consent",
"action id",
"action_id",
"stale hardcoded fallback",
"empty spa",
)
return any(n in s for n in needles)
def _is_cancelled_error(err: Exception | str | None) -> bool:
"""True when the failure is an explicit cancel/abort (no residual grant)."""
if isinstance(err, PKCEMintError):
if str(getattr(err, "code", "") or "").strip().lower() == "cancelled":
return True
s = (str(err) if err is not None else "").strip().lower()
return s == "cancelled" or s.startswith("cancelled")
def _is_server_policy_error(err: str | Exception | None) -> bool:
"""True when the token exchange was denied by the x.ai auth SERVER policy.
Device-code poll returns ``oauth2/token 400 invalid_grant: Access denied
[tax=server_policy]`` (oauth_device.py) whenever the server-side policy
refuses the account/client token exchange. It can never be resolved by
spending a 240s browser device phase — so mint must fast-fail and surface
it instead of burning the browser residual dead-end.
"""
low = str(err or "").lower()
return (
"invalid_grant" in low
and ("access denied" in low or "server_policy" in low)
) or "tax=server_policy" in low
def _is_consent_dead_end_error(err: str | Exception | None) -> bool:
"""True when the x.ai consent page itself is a non-retryable dead-end.
Next.js consent HTML missing/broken ``submitOAuth2Consent`` action id makes
the programmatic PKCE submit return HTTP 404 (structured code
``consent_action_missing`` / ``consent_action_rejected``, retryable=False).
The browser residual walks that same broken consent page (device phase), so
spending browser_timeout_sec there is a dead end — mint must fast-fail and
surface it instead. Distinct from ``empty_sso`` (no cookie — interactive
browser login may still succeed) and transient network errors.
``code`` is duck-typed (any object carrying ``.code``, e.g. a PKCEMintError
copy loaded via importlib spec in tests) — class identity must not matter.
"""
code = str(getattr(err, "code", "") or "").strip().lower()
if code in {"consent_action_missing", "consent_action_rejected"}:
return True
s = (str(err) if err is not None else "").lower()
if not s:
return False
needles = (
"server action not found",
"consent html missing",
"submitoauth2consent",
"action id",
"action_id",
"stale hardcoded fallback",
)
return any(n in s for n in needles)
def _should_stamp_protocol_error(mint_method: str) -> bool:
"""Stamp prior PKCE/device failure reason when residual path produced tokens.
Pure pkce/protocol primary success should not carry a protocol_error.
Residuals (protocol_device, browser after protocol fail) should.
"""
mm = (mint_method or "").strip().lower()
return mm not in ("pkce", "protocol")
def _cancelled_result(
email: str,
*,
mint_method: str,
protocol_err: str | None = None,
pkce_error_code: str | None = "cancelled",
) -> dict[str, Any]:
"""Stable cancelled fail dict — never residual after abort."""
out: dict[str, Any] = {
"ok": False,
"email": email,
"error": "cancelled",
"mint_method": mint_method,
"mint_fail_reason": "cancelled",
"pkce_retryable": False,
}
if pkce_error_code:
out["pkce_error_code"] = pkce_error_code
if protocol_err:
out["protocol_error"] = str(protocol_err)[:500]
return out
def classify_browser_mint_error(err: Exception | str | None) -> tuple[str, str]:
"""Map browser/protocol mint exceptions → (mint_fail_reason, mint_fail_phase).
Stable taxonomy for SUMMARY_JSON / ops:
device_click_stall | browser_timeout | auth_failed | browser_boot | mint_error | cancelled
"""
s = str(err if err is not None else "").strip()
low = s.lower()
if not s:
return ("mint_error", "")
if low == "cancelled" or low.startswith("cancelled"):
return ("cancelled", "")
phase = ""
if "phase=" in low:
try:
phase = low.split("phase=", 1)[1].split(None, 1)[0].strip()
except Exception:
phase = ""
if "device_click_stall" in low:
return ("device_click_stall", phase or "device")
if "browser confirm timeout" in low or (
"timeout" in low and "phase=" in low
):
return ("browser_timeout", phase or "device")
if "auth failed" in low or "turnstile" in low:
return ("auth_failed", phase or "password")
if (
"chromium" in low
or "browser connection" in low
or "the browser connection fails" in low
):
return ("browser_boot", phase or "boot")
return ("mint_error", phase)
def mint_and_export(
*,
email: str,
password: str,
auth_dir: str | Path,
page: Any | None = None,
proxy: str | None = None,
headless: bool = False,
base_url: str = DEFAULT_BASE_URL,
probe: bool = True,
probe_chat: bool = True,
browser_timeout_sec: float = 240.0,
force_standalone: bool = True,
cookies: Any | None = None,
sso: str | None = None,
reuse_browser: bool = True,
recycle_every: int = 15,
prefer_protocol: bool = True,
protocol_only: bool = False,
protocol_poll_timeout_sec: float = 90.0,
allow_device_flow_fallback: bool = True,
protocol_flow: str = "pkce",
priority: int = 1000,
probe_via: str = "hybrid",
cpa_probe_base_url: str = "",
cpa_probe_api_key: str = "",
probe_credential_pin: str = "",
probe_pin_header: str = "X-CPA-Credential",
allow_unpinned_cpa_gate: bool = False,
log: LogFn | None = None,
cancel: Callable[[], bool] | None = None,
) -> dict[str, Any]:
"""Full pipeline: (protocol PKCE | device residual | browser) → write CPA → probe.
Protocol path (curl_cffi + sso cookie) is tried first when prefer_protocol
and an sso cookie is available. ``protocol_flow`` selects the HTTP grant:
``pkce`` (default, authorization-code) or ``device`` (legacy device-code —
known to yield /models-ok-but-chat-403).
``allow_device_flow_fallback`` (product default True) lets failed PKCE fall
through to device flow for local disk residual; device tokens are often
chat-denied — inject still requires chat_ok / entitlement hard gate.
On protocol failure, falls back to browser mint unless protocol_only=True.
``mint_method`` taxonomy (disk + SUMMARY observability):
- ``pkce`` — SSO HTTP authorization-code success
- ``protocol`` — primary device flow (``protocol_flow=device``)
- ``protocol_device`` — PKCE failed then device residual succeeded
- ``browser`` — browser device-auth residual
Dual stamp path: auth is written at create with ``mint_method`` /
``protocol_error`` via ``extra=``; after probe, ``stamp_auth_chat_fields``
re-merges the same observability fields so probe patches never drop them.
priority: CPA auth-file routing weight (CLIProxyAPI). Default 1000.
Mid-tier probe (tebi CPA):
- ``probe_via``: direct | cpa | hybrid (product default hybrid until pin proven).
- Unpinned ``cpa`` never stamps chat_ok; policy falls back to hybrid
(direct gate + optional observational ``probe_via_cpa_ok`` smoke).
- Auth file ``base_url`` remains upstream cli-chat-proxy (argument ``base_url``),
never the public CPA OpenAI base.
Returns dict with keys: ok, token_ok?, path, email, probe_*, error?,
mint_method?, entitlement_denied?, chat_retryable?, chat_ok?,
probe_gate_via?, probe_via_cpa_ok?, probe_policy_reason?, protocol_error?.
Honesty: ``token_ok=True`` means OIDC tokens were written. Product ``ok``
is True only after required probes succeed (or when all probes are off,
where token write alone is the success criterion). Never claim product
ok before probe resolution when probes are enabled.
Product rule: when probe_chat=True, models-only success is not enough —
free Build chat must pass /v1/responses. 403 permission-denied is
non-retryable entitlement failure (do not remint-spin).
"""
log = log or _noop
email = (email or "").strip()
if not email or not password:
# Protocol can work with sso alone; password only required for browser fallback
if not email:
return {"ok": False, "email": email, "error": "missing email"}
if not (sso or extract_sso_from_cookies(cookies)):
return {"ok": False, "email": email, "error": "missing email/password"}
# Config/explicit proxy wins over shell https_proxy (common 7890 trap).
# Thread-local pin — safe under concurrent mint workers.
resolved = resolve_proxy(proxy)
set_runtime_proxy(resolved or None)
log(f"mint start: {email} proxy={proxy_log_label(resolved) or '(none)'}")
# Normalize at mint core so every caller (export, backfill, GUI) is safe.
sso_val = normalize_sso_cookie(sso) or extract_sso_from_cookies(cookies)
tokens: dict[str, Any] | None = None
protocol_err: str | None = None
if prefer_protocol and sso_val:
flow = (protocol_flow or "pkce").strip().lower()
if flow not in {"pkce", "device"}:
return {
"ok": False,
"email": email,
"error": f"unsupported cpa_protocol_flow: {protocol_flow}; expected pkce or device",
"mint_method": "protocol",
}
# Track whether we already attempted PKCE for residual fail labeling.
pkce_attempted = False
if flow == "pkce":
log(
"mint try protocol (SSO HTTP PKCE authorization-code; best-effort — "
"empty consent SPA shell → residual device/browser)"
)
try:
tokens = mint_with_sso_pkce(
sso_cookie=sso_val,
email=email,
proxy=resolved or None,
log=log,
cancel=cancel,
)
log("mint protocol PKCE SUCCESS")
except PKCEMintError as e:
protocol_err = str(e)
pkce_attempted = True
non_retry = _is_pkce_non_retryable(e)
code = str(getattr(e, "code", "") or "").strip()
log(
f"mint protocol PKCE failed"
f"{' (non-retryable)' if non_retry else ''}"
f"{f' code={code}' if code else ''}"
f": {e}"
)
# Cancel/abort: never residual to device or browser.
if _is_cancelled_error(e) or (cancel and cancel()):
log("mint cancelled after PKCE — skip residual device/browser")
return _cancelled_result(
email,
mint_method="pkce",
protocol_err=protocol_err,
pkce_error_code=code or "cancelled",
)
if allow_device_flow_fallback:
if non_retry:
log(
"mint best-effort residual → device flow "
"(PKCE non-retryable extract/consent; accept device residual)"
)
else:
log("mint fallback → device flow")
else:
if protocol_only:
return {
"ok": False,
"email": email,
"error": f"pkce protocol failed: {protocol_err}",
"mint_method": "pkce",
"pkce_error_code": code or None,
"pkce_retryable": bool(e.retryable),
}
log(
"mint device residual disabled "
"(allow_device_flow_fallback=False) → browser if available"
)
except Exception as e: # noqa: BLE001
protocol_err = str(e)
pkce_attempted = True
log(f"mint protocol PKCE exception: {e}")
if _is_cancelled_error(e) or (cancel and cancel()):
log("mint cancelled after PKCE exception — skip residual")
return _cancelled_result(
email,
mint_method="pkce",
protocol_err=protocol_err,
)
if allow_device_flow_fallback:
log("mint fallback → device flow")
else:
if protocol_only:
return {
"ok": False,
"email": email,
"error": f"pkce protocol failed: {protocol_err}",
"mint_method": "pkce",
}
log(
"mint device residual disabled "
"(allow_device_flow_fallback=False) → browser if available"
)
if tokens is None and (flow == "device" or allow_device_flow_fallback):
# Re-check cancel before spending a device-code grant.
if cancel and cancel():
log("mint cancelled before device residual — skip")
return _cancelled_result(
email,
mint_method="protocol_device" if pkce_attempted else "protocol",
protocol_err=protocol_err,
)
if flow == "device":
log("mint try protocol (SSO HTTP device flow)")
try:
tokens = mint_with_sso_protocol(
sso_cookie=sso_val,
email=email,
proxy=resolved or None,
poll_timeout_sec=protocol_poll_timeout_sec,
log=log,
cancel=cancel,
)
# Taxonomy: primary device vs PKCE residual device.
if pkce_attempted:
tokens["mint_method"] = "protocol_device"
tokens["protocol_error"] = str(protocol_err)[:500]
log("mint protocol device residual SUCCESS (mint_method=protocol_device)")
else:
tokens["mint_method"] = "protocol"
log("mint protocol device-flow SUCCESS")
except ProtocolMintError as e:
device_err = str(e)
log(f"mint protocol device-flow failed: {e}")
protocol_err = (
f"pkce: {protocol_err}; device: {device_err}" if protocol_err else device_err
)
fail_mm = "protocol_device" if pkce_attempted else "protocol"
if _is_cancelled_error(e) or (cancel and cancel()):
log("mint cancelled during device residual — skip browser")
return _cancelled_result(
email,
mint_method=fail_mm,
protocol_err=protocol_err,
)
if protocol_only:
return {
"ok": False,
"email": email,
"error": f"protocol_only: {protocol_err}",
"mint_method": fail_mm,
"protocol_error": str(protocol_err)[:500],
}
log("mint fallback → browser")
except Exception as e: # noqa: BLE001
device_err = str(e)
log(f"mint protocol device-flow exception: {e}")
protocol_err = (
f"pkce: {protocol_err}; device: {device_err}" if protocol_err else device_err
)
fail_mm = "protocol_device" if pkce_attempted else "protocol"
if _is_cancelled_error(e) or (cancel and cancel()):
log("mint cancelled during device residual exception — skip browser")
return _cancelled_result(
email,
mint_method=fail_mm,
protocol_err=protocol_err,
)
if protocol_only:
return {
"ok": False,
"email": email,
"error": f"protocol_only: {protocol_err}",
"mint_method": fail_mm,
"protocol_error": str(protocol_err)[:500],
}
log("mint fallback → browser")
elif prefer_protocol and not sso_val:
log("mint protocol skipped (no sso cookie) → browser")
if protocol_only:
return {
"ok": False,
"email": email,
"error": "protocol_only but no sso cookie",
"mint_method": "protocol",
}
elif not prefer_protocol:
log("mint protocol disabled → browser")
if tokens is None:
# Abort must not open a browser residual grant.
if cancel and cancel():
log("mint cancelled before browser residual — skip")
return _cancelled_result(
email,
mint_method="browser",
protocol_err=protocol_err,
)
if protocol_err and _is_cancelled_error(protocol_err):
log("mint cancelled (protocol_err) — skip browser residual")
return _cancelled_result(
email,
mint_method="pkce",
protocol_err=protocol_err,
)
# Server-policy denial or a broken consent page can never be fixed by a
# browser device phase — fast-fail now instead of burning
# browser_timeout_sec on a dead-end (pxed live: submitOAuth2Consent
# HTTP 404 code=consent_action_missing, retryable=False).
if protocol_err and (
_is_server_policy_error(protocol_err) or _is_consent_dead_end_error(protocol_err)
):
label = (
"server_policy"
if _is_server_policy_error(protocol_err)
else "consent_dead_end"
)
log(
f"mint fast-fail ({label}) — skip browser residual: "
f"{str(protocol_err)[:300]}"
)
return {
"ok": False,
"email": email,
"error": f"{label}: {protocol_err[:400]}",
"protocol_error": str(protocol_err)[:500],
"mint_method": "protocol_device"
if (
prefer_protocol
and sso_val
and (protocol_flow or "pkce").strip().lower() == "pkce"
and protocol_err
)
else ("protocol" if protocol_err else "browser"),
}
if not password:
return {
"ok": False,
"email": email,
"error": protocol_err or "protocol failed and no password for browser fallback",
"protocol_error": protocol_err,
"mint_method": "protocol_device"
if (prefer_protocol and sso_val and (protocol_flow or "pkce").strip().lower() == "pkce" and protocol_err)
else ("protocol" if protocol_err else "browser"),
}
try:
tokens = mint_with_browser(
email=email,
password=password,
page=None if force_standalone else page,
proxy=resolved or None,
headless=headless,
browser_timeout_sec=browser_timeout_sec,
force_standalone=force_standalone,
cookies=cookies,
reuse_browser=reuse_browser,
recycle_every=recycle_every,
poll_log=log,
cancel=cancel,
)
tokens["mint_method"] = "browser"
if protocol_err:
tokens["protocol_error"] = protocol_err
except Exception as e: # noqa: BLE001
log(f"mint failed: {e}")
if _is_cancelled_error(e) or (cancel and cancel()):
return _cancelled_result(
email,
mint_method="browser",
protocol_err=protocol_err or str(e),
)
err = str(e)
if protocol_err:
err = f"{err} (protocol: {protocol_err})"
reason, phase = classify_browser_mint_error(e)
out_fail: dict[str, Any] = {
"ok": False,
"email": email,
"error": err,
"protocol_error": protocol_err,
"mint_method": "browser",
"mint_fail_reason": reason,
}
if phase:
out_fail["mint_fail_phase"] = phase
return out_fail
try:
pri = int(priority)
except Exception:
pri = 1000
mint_method = str(tokens.get("mint_method") or "browser").strip() or "browser"
extra_auth: dict[str, Any] = {"mint_method": mint_method}
# Stamp prior protocol failure reason on residual success paths only
# (protocol_device / browser after protocol fail). Pure pkce/protocol keep clean.
if protocol_err and _should_stamp_protocol_error(mint_method):
extra_auth["protocol_error"] = str(protocol_err)[:500]
# Device residual may already carry protocol_error on tokens dict.
if tokens.get("protocol_error") and "protocol_error" not in extra_auth:
extra_auth["protocol_error"] = str(tokens.get("protocol_error"))[:500]
payload = build_cpa_xai_auth(
email=email,
access_token=tokens["access_token"],
refresh_token=tokens["refresh_token"],
id_token=tokens.get("id_token"),
expires_in=tokens.get("expires_in"),
base_url=base_url,
priority=pri,
extra=extra_auth,
)
path = write_cpa_xai_auth(auth_dir, payload)
log(f"wrote {path} priority={pri} mint_method={mint_method}")
# Chat gate implies models probe (need has_grok_45 before /responses).
run_models = bool(probe or probe_chat)
# Honesty: token write is always token_ok. Product ok is True only when
# probes are disabled (token write alone is the success criterion) or after
# the probe path sets ok. Never claim product ok before probe resolution.
result: dict[str, Any] = {
"ok": not run_models,
"token_ok": True,
"email": email,
"path": str(path),
"user_code": tokens.get("user_code"),
"base_url": base_url,
"proxy": proxy_log_label(resolved),
"mint_method": mint_method,
"priority": pri,
}
if protocol_err and _should_stamp_protocol_error(mint_method):
result["protocol_error"] = str(protocol_err)[:500]
elif tokens.get("protocol_error"):
result["protocol_error"] = str(tokens.get("protocol_error"))[:500]
# Resolve product gate vs optional CPA observational smoke.
# Auth write always uses upstream base_url (cli-chat-proxy), never CPA public host.
pin = (probe_credential_pin or "").strip()
if not pin and email:
# Default pin identity is the CPA auth filename (safe ops handle).
pin = credential_file_name(email=email)
policy = resolve_gate_probe_policy(
via=probe_via,
cpa_base_url=cpa_probe_base_url,
cpa_api_key=cpa_probe_api_key,
credential_pin=pin if str(probe_via or "").strip().lower() != "direct" else "",
allow_unpinned_cpa_gate=bool(allow_unpinned_cpa_gate),
)
result["probe_gate_via"] = policy.get("gate_via") or "direct"
result["probe_policy_reason"] = policy.get("reason") or ""
result["probe_via_cpa_ok"] = None
log(
f"probe policy: via={probe_via!r} gate={result['probe_gate_via']} "
f"cpa_smoke={policy.get('cpa_smoke')} reason={result['probe_policy_reason']}"
)
gate_transport = build_probe_transport(
via=str(policy.get("gate_via") or "direct"),
upstream_base_url=base_url,
cpa_base_url=cpa_probe_base_url,
cpa_api_key=cpa_probe_api_key,
access_token=tokens["access_token"],
credential_pin=pin if str(policy.get("gate_via")) == "cpa" else "",
pin_header=probe_pin_header or "X-CPA-Credential",
)
if run_models:
pr = probe_models(
tokens["access_token"],
base_url=base_url,
proxy=resolved or None,
transport=gate_transport,
)
result["probe_models"] = pr
log(
f"probe models: ok={pr.get('ok')} status={pr.get('status')} "
f"has_grok_45={pr.get('has_grok_45')} ids={pr.get('model_ids')} "
f"mode={pr.get('transport_mode')!r} "
f"error={str(pr.get('error') or '')[:200]}"
)
if not pr.get("has_grok_45"):
if probe_chat:
apply_chat_probe_to_result(
result,
None,
models_missing=True,
models_status=int(pr.get("status") or 0),
)
else:
result["ok"] = False
result["error"] = MODELS_MISSING_ERROR
result["chat_ok"] = False
result["usable"] = False
result["fail_reason"] = MODELS_MISSING_REASON
elif probe_chat:
chat_model = pick_chat_probe_model(pr.get("model_ids") or [])
log(
f"probe chat model: {chat_model} "
f"(ids={pr.get('model_ids') or []})"
)
ch = probe_chat_with_retries(
tokens["access_token"],
base_url=base_url,
proxy=resolved or None,
max_attempts=3,
log=log,
transport=gate_transport,
model=chat_model,
)
apply_chat_probe_to_result(result, ch)
if result.get("entitlement_denied"):
log(
"FAIL-FAST: chat entitlement_denied — skip remint/retry for this account"
)
else:
# models-only probe path (chat off): product ok only when grok-4.5 listed
result["ok"] = True
# Observational CPA mid-tier smoke: never replaces chat_ok for inject.
if (
policy.get("cpa_smoke")
and result.get("chat_ok") is True
and not result.get("entitlement_denied")
and (cpa_probe_base_url or "").strip()
and (cpa_probe_api_key or "").strip()
):
cpa_t = build_probe_transport(
via="cpa",
upstream_base_url=base_url,
cpa_base_url=cpa_probe_base_url,
cpa_api_key=cpa_probe_api_key,
access_token=tokens["access_token"],
credential_pin=pin,
pin_header=probe_pin_header or "X-CPA-Credential",
)
try:
smoke = probe_chat_with_retries(
tokens["access_token"],
base_url=base_url,
proxy=resolved or None,
max_attempts=1,
log=log,
transport=cpa_t,
)
result["probe_cpa_smoke"] = smoke
result["probe_via_cpa_ok"] = bool(smoke.get("ok"))
log(
f"cpa smoke: ok={smoke.get('ok')} status={smoke.get('status')} "
f"code={smoke.get('error_code')!r} mode={smoke.get('transport_mode')!r}"
)
except Exception as e: # noqa: BLE001
result["probe_via_cpa_ok"] = False
result["probe_cpa_smoke_error"] = str(e)
log(f"cpa smoke failed: {e}")
# Dual stamp: create-time write already put mint_method/protocol_error via
# extra_auth. Re-stamp after probe so chat fields never drop mint observability
# (stamp_auth_chat_fields merges result + updates; both carry mint_method).
if result.get("path"):
try:
updates = {
"probe_gate_via": result.get("probe_gate_via"),
"probe_policy_reason": result.get("probe_policy_reason"),
}
if result.get("probe_via_cpa_ok") is True or result.get("probe_via_cpa_ok") is False:
updates["probe_via_cpa_ok"] = bool(result.get("probe_via_cpa_ok"))
if result.get("mint_method"):
updates["mint_method"] = str(result.get("mint_method"))
if result.get("protocol_error"):
updates["protocol_error"] = str(result.get("protocol_error"))[:500]
stamped = stamp_auth_chat_fields(result["path"], result, updates=updates)
if stamped.get("import_gate"):
result["import_gate"] = stamped["import_gate"]
except Exception as e: # noqa: BLE001
log(f"stamp auth chat flags failed: {e}")
result["stamp_error"] = str(e)
return result
+348
View File
@@ -0,0 +1,348 @@
"""xAI OAuth device-code grant (Grok CLI / CPA client).
Endpoints from https://auth.x.ai/.well-known/openid-configuration
"""
from __future__ import annotations
import json
import ssl
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from typing import Any, Callable
from .proxyutil import resolve_proxy
# Keep in sync with CLIProxyAPI internal/auth/xai/types.go
CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
ISSUER = "https://auth.x.ai"
DEVICE_CODE_URL = "https://auth.x.ai/oauth2/device/code"
TOKEN_URL = "https://auth.x.ai/oauth2/token"
SCOPE = "openid profile email offline_access grok-cli:access api:access"
LogFn = Callable[[str], None]
def _noop_log(_: str) -> None:
return None
def _proxy_handler(proxy: str | None = None) -> urllib.request.ProxyHandler | None:
p = resolve_proxy(proxy)
if not p:
return None
return urllib.request.ProxyHandler({"http": p, "https": p})
def _ssl_context() -> ssl.SSLContext | None:
"""Use certifi's CA bundle when available.
macOS Framework Python / uv venv can have an empty or incomplete OpenSSL
trust store, which makes stdlib urllib fail with
CERTIFICATE_VERIFY_FAILED even when curl/browser requests work.
"""
try:
import certifi # type: ignore
return ssl.create_default_context(cafile=certifi.where())
except Exception:
return None
def _opener(proxy: str | None = None) -> urllib.request.OpenerDirector:
handlers: list[Any] = []
ctx = _ssl_context()
if ctx is not None:
handlers.append(urllib.request.HTTPSHandler(context=ctx))
ph = _proxy_handler(proxy)
if ph is not None:
handlers.append(ph)
return urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener()
def _is_transient_net_error(exc: BaseException) -> bool:
"""Proxy/TLS blips that should not kill an already-approved device flow."""
if isinstance(exc, (TimeoutError, BrokenPipeError, ConnectionResetError, ConnectionAbortedError, ConnectionRefusedError)):
return True
if isinstance(exc, urllib.error.URLError):
reason = getattr(exc, "reason", None)
if isinstance(reason, BaseException) and _is_transient_net_error(reason):
return True
msg = str(exc).lower()
needles = (
"broken pipe",
"connection reset",
"connection aborted",
"timed out",
"timeout",
"temporarily unavailable",
"network is unreachable",
"name or service not known",
"unexpected_eof",
"eof occurred",
"ssl",
"handshake",
"remote end closed",
"bad gateway",
"connection refused",
)
return any(n in msg for n in needles)
# ssl.SSLError and generic OSError (errno 32 Broken pipe, 104 reset, etc.)
try:
import ssl
if isinstance(exc, ssl.SSLError):
return True
except Exception:
pass
if isinstance(exc, OSError):
if getattr(exc, "errno", None) in {32, 104, 110, 111, 113, 101}:
return True
msg = str(exc).lower()
return any(n in msg for n in ("broken pipe", "timed out", "connection reset", "ssl"))
return False
def _post_form(
url: str,
form: dict[str, str],
timeout: float = 30.0,
*,
proxy: str | None = None,
retries: int = 0,
retry_sleep: float = 1.5,
) -> tuple[int, dict[str, Any] | str]:
data = urllib.parse.urlencode(form).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
method="POST",
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"User-Agent": "grok-reg-cpa-xai-minter/1.0",
},
)
last: BaseException | None = None
attempts = max(int(retries), 0) + 1
for i in range(attempts):
opener = _opener(proxy)
try:
with opener.open(req, timeout=timeout) as resp:
body = resp.read().decode("utf-8", errors="replace")
status = getattr(resp, "status", 200) or 200
try:
return int(status), json.loads(body)
except json.JSONDecodeError:
return int(status), body
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="replace")
try:
return int(e.code), json.loads(body)
except json.JSONDecodeError:
return int(e.code), body
except BaseException as e: # noqa: BLE001
last = e
if not _is_transient_net_error(e) or i + 1 >= attempts:
raise
time.sleep(retry_sleep * (i + 1))
assert last is not None
raise last
@dataclass
class DeviceCodeSession:
device_code: str
user_code: str
verification_uri: str
verification_uri_complete: str
expires_in: int
interval: int
raw: dict[str, Any]
@dataclass
class TokenResult:
access_token: str
refresh_token: str
id_token: str | None
token_type: str
expires_in: int
raw: dict[str, Any]
class OAuthDeviceError(RuntimeError):
pass
def request_device_code(
*,
client_id: str = CLIENT_ID,
scope: str = SCOPE,
timeout: float = 30.0,
proxy: str | None = None,
) -> DeviceCodeSession:
status, body = _post_form(
DEVICE_CODE_URL,
{"client_id": client_id, "scope": scope},
timeout=timeout,
proxy=proxy,
retries=2,
retry_sleep=1.0,
)
if status != 200 or not isinstance(body, dict):
raise OAuthDeviceError(f"device code request failed HTTP {status}: {body!r}")
device_code = str(body.get("device_code") or "").strip()
user_code = str(body.get("user_code") or "").strip()
if not device_code or not user_code:
raise OAuthDeviceError(f"device code response missing fields: {body}")
vuri = str(body.get("verification_uri") or "https://accounts.x.ai/oauth2/device").strip()
vcomplete = str(
body.get("verification_uri_complete") or f"{vuri}?user_code={user_code}"
).strip()
expires_in = int(body.get("expires_in") or 1800)
interval = max(int(body.get("interval") or 5), 1)
return DeviceCodeSession(
device_code=device_code,
user_code=user_code,
verification_uri=vuri,
verification_uri_complete=vcomplete,
expires_in=expires_in,
interval=interval,
raw=body,
)
def poll_device_token(
device_code: str,
*,
client_id: str = CLIENT_ID,
interval: int = 5,
expires_in: int = 1800,
timeout: float = 30.0,
log: LogFn | None = None,
cancel: Callable[[], bool] | None = None,
proxy: str | None = None,
) -> TokenResult:
"""Poll token endpoint until authorized or expired.
Transient proxy/TLS errors (Broken pipe, SSL EOF, timeouts) are retried
until the device-code deadline so a successful browser consent is not
wasted by a single flaky poll.
"""
log = log or _noop_log
deadline = time.time() + max(expires_in - 5, 30)
sleep_for = max(interval, 1)
net_streak = 0
max_net_streak = 20
while time.time() < deadline:
if cancel and cancel():
raise OAuthDeviceError("cancelled")
try:
status, body = _post_form(
TOKEN_URL,
{
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
"device_code": device_code,
"client_id": client_id,
},
timeout=timeout,
proxy=proxy,
retries=2,
retry_sleep=1.0,
)
net_streak = 0
except BaseException as e: # noqa: BLE001
if not _is_transient_net_error(e):
raise
net_streak += 1
wait = min(sleep_for + min(net_streak, 5), 20)
log(
f"oauth poll network blip ({net_streak}/{max_net_streak}): {e} "
f"— retry in {wait}s"
)
if net_streak >= max_net_streak:
raise OAuthDeviceError(
f"device auth aborted after {net_streak} network errors: {e}"
) from e
time.sleep(wait)
continue
if status == 200 and isinstance(body, dict) and body.get("access_token"):
access = str(body["access_token"]).strip()
refresh = str(body.get("refresh_token") or "").strip()
if not refresh:
raise OAuthDeviceError("token response missing refresh_token")
return TokenResult(
access_token=access,
refresh_token=refresh,
id_token=(str(body["id_token"]).strip() if body.get("id_token") else None),
token_type=str(body.get("token_type") or "Bearer"),
expires_in=int(body.get("expires_in") or 21600),
raw=body,
)
err = ""
desc = ""
if isinstance(body, dict):
err = str(body.get("error") or "")
desc = str(body.get("error_description") or "")
if err in ("authorization_pending", "slow_down"):
if err == "slow_down":
sleep_for = min(sleep_for + 5, 30)
log(f"oauth poll: {err} (sleep {sleep_for}s)")
time.sleep(sleep_for)
continue
# Hard terminal errors — dump status/body keys for invalid_grant diagnosis.
# Never log access_token / refresh_token even if present on odd responses.
body_keys: list[str] = []
safe_body: dict[str, Any] = {}
if isinstance(body, dict):
body_keys = sorted(str(k) for k in body.keys())
for k, v in body.items():
lk = str(k).lower()
if any(x in lk for x in ("token", "secret", "password", "code")) and lk not in (
"error",
"error_code",
"error_description",
):
safe_body[str(k)] = f"<{type(v).__name__}>"
else:
safe_body[str(k)] = v if not isinstance(v, (dict, list)) else type(v).__name__
if err in ("expired_token", "access_denied"):
log(
f"oauth poll HARD: status={status} err={err} desc={desc!r} "
f"keys={body_keys} body={safe_body!r}"
)
raise OAuthDeviceError(f"device auth failed: {err}: {desc}")
if status == 400 and err:
# Taxonomy for operators: after browser lands on device/done,
# invalid_grant Access denied is server-side policy on the token
# exchange (same body as dead refresh_token), not a missed Allow click.
tax = "server_policy" if err == "invalid_grant" else "token_error"
log(
f"oauth poll HARD 400: status={status} err={err} desc={desc!r} "
f"tax={tax} keys={body_keys} body={safe_body!r}"
)
if err == "invalid_grant":
raise OAuthDeviceError(
f"device auth token error: {err}: {desc or body} "
f"[tax=server_policy; consent may have succeeded — "
f"token endpoint denied exchange]"
)
raise OAuthDeviceError(f"device auth token error: {err}: {desc or body}")
# 5xx / empty / proxy HTML — treat as soft error and keep polling
if status >= 500 or status in (502, 503, 504) or not isinstance(body, dict):
net_streak += 1
wait = min(sleep_for + 2, 20)
log(f"oauth poll soft HTTP {status}: {body!r} — retry in {wait}s")
if net_streak >= max_net_streak:
raise OAuthDeviceError(
f"device auth aborted after soft HTTP failures status={status}"
)
time.sleep(wait)
continue
log(f"oauth poll unexpected HTTP {status}: {body!r}")
time.sleep(sleep_for)
raise OAuthDeviceError("device auth timed out waiting for user approval")
+631
View File
@@ -0,0 +1,631 @@
"""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)("<id>",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'<script[^>]*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`` <script src> and look for the reference
whose last argument is the ``submitOAuth2Consent`` action name, which
disambiguates it from other page actions (getSession etc.). Returns None
when no chunk yields it (bounded by ``timeout`` per request).
"""
if not page_html or not session:
return None
for src in _SCRIPT_SRC_RE.findall(page_html):
url = urljoin(ACCOUNTS_ORIGIN, src)
try:
resp = session.get(url, timeout=timeout)
text = resp.text or ""
except Exception:
continue
m = _SERVER_REF_CONSENT_RE.search(text)
if m:
return m.group(1)
return None
def _create_cookie_setter_link(session: Any, success_url: str) -> str:
msg = grpcweb.encode_string(1, success_url) + grpcweb.encode_string(2, f"{ACCOUNTS_ORIGIN}/sign-in")
resp = session.post(
CREATE_COOKIE_SETTER_RPC,
headers=_grpc_headers(f"{ACCOUNTS_ORIGIN}/sign-in?redirect=oauth2-provider"),
data=grpcweb.frame_request(msg),
timeout=45,
)
hdrs = {k.lower(): v for k, v in resp.headers.items()}
header_status, header_msg = _parse_grpc_error(hdrs, resp.content)
try:
parsed = grpcweb.parse_response(resp.content)
except Exception:
parsed = {"messages": [], "trailers": {}, "grpc_status": None}
grpc_status = parsed.get("grpc_status")
if grpc_status is None:
grpc_status = header_status
grpc_msg = header_msg or unquote(str((parsed.get("trailers") or {}).get("grpc-message") or ""))
fields = parsed["messages"][0] if parsed.get("messages") else []
urls = _extract_urls_from_fields(fields)
cookie_setter = next((u for u in urls if "set-cookie" in u), None) or (urls[0] if urls else "")
if grpc_status not in (None, 0) or not cookie_setter:
raise PKCEMintError(
grpc_msg or "CreateCookieSetterLink failed",
code="cookie_setter",
retryable=True,
)
return cookie_setter
def _submit_consent(
session: Any,
*,
page_url: str,
page_html: str,
client_id: str,
redirect_uri: str,
scope: str,
state: str,
code_challenge: str,
nonce: str,
) -> str:
extracted = _extract_action_id_from_html(page_html)
used_hardcoded = extracted is None
action_id = extracted or SUBMIT_OAUTH2_CONSENT_ACTION
router_tree = (
'["",{"children":["(app)",{"children":["(auth)",{"children":["oauth2",'
'{"children":["consent",{"children":["__PAGE__",{}]}]}]}]}]},'
'"$undefined","$undefined",16]'
)
payload = [
{
"action": "allow",
"clientId": client_id,
"redirectUri": redirect_uri,
"scope": scope,
"state": state,
"codeChallenge": code_challenge,
"codeChallengeMethod": "S256",
"nonce": nonce,
"principalType": "User",
"principalId": "",
"referrer": "",
}
]
def _post(url: str, aid: str):
headers = {
"accept": "text/x-component",
"content-type": "text/plain;charset=UTF-8",
"next-action": aid,
"next-router-state-tree": quote(router_tree, safe=""),
"origin": ACCOUNTS_ORIGIN,
"referer": page_url,
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
}
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
return session.post(url, headers=headers, data=body, timeout=45)
def _code_from_resp(resp: Any) -> str | None:
text = resp.text or ""
match = re.search(r'"code"\s*:\s*"([^"]+)"', text)
if match:
return match.group(1)
match = re.search(r"code=([A-Za-z0-9._~\-]+)", text)
if match and "error" not in match.group(0):
return match.group(1)
loc = resp.headers.get("location") or resp.headers.get("Location") or ""
if "code=" in loc:
return _code_from_url(urljoin(page_url, loc), state)
return None
post_url = page_url.split("?")[0] if "consent" in page_url else page_url
resp = _post(post_url, action_id)
text = resp.text or ""
code = _code_from_resp(resp)
if code:
return code
# Retry full page_url if strip-query POST failed
if resp.status_code >= 400 or ("error" in text[:200].lower() and "code" not in text):
resp = _post(page_url, action_id)
text = resp.text or ""
code = _code_from_resp(resp)
if code:
return code
# 404 "Server action not found": the consent action id is missing/stale.
# Recovery order: (1) re-fetch HTML + re-extract (SSR-era inline ids),
# (2) bundle-scan the referenced JS chunks (current CSR page keeps the id
# only in a chunk: createServerReference)("<id>") single-arg form).
not_found = resp.status_code == 404 or "server action not found" in text.lower()
if not_found:
def _try_aid(candidate: str, url: str) -> str | None:
"""POST consent with a candidate action id; return code or None."""
pu = url.split("?")[0] if "consent" in url else url
r = _post(pu, candidate)
c = _code_from_resp(r)
if c:
return c
if r.status_code >= 400:
r = _post(url, candidate)
c = _code_from_resp(r)
if c:
return c
return None
refreshed_html = ""
tried = {action_id}
try:
refresh = session.get(page_url, allow_redirects=True, timeout=45)
refreshed_html = refresh.text or ""
refresh_url = str(getattr(refresh, "url", None) or page_url)
new_aid = _extract_action_id_from_html(refreshed_html)
if new_aid and new_aid not in tried:
tried.add(new_aid)
code = _try_aid(new_aid, refresh_url)
if code:
return code
except Exception:
pass
scan_html = refreshed_html or page_html
try:
bundle_aid = _extract_consent_action_id_from_bundles(session, scan_html)
except Exception:
bundle_aid = None
if bundle_aid and bundle_aid not in tried:
code = _try_aid(bundle_aid, page_url)
if code:
return code
if used_hardcoded:
raise PKCEMintError(
"submitOAuth2Consent failed HTTP 404: Server action not found "
"(consent HTML + JS bundles missing consent action id; "
"stale hardcoded fallback rejected by Next.js)",
code="consent_action_missing",
retryable=False,
)
raise PKCEMintError(
f"submitOAuth2Consent failed HTTP {resp.status_code}: {text[:300]} "
f"(action_id={action_id[:12]}… extracted from page)",
code="consent_action_rejected",
retryable=False,
)
raise PKCEMintError(
f"submitOAuth2Consent failed HTTP {resp.status_code}: {text[:300]}",
code="consent_submit",
retryable=True,
)
def _exchange_code_for_token(
session: Any,
*,
code: str,
verifier: str,
redirect_uri: str,
client_id: str,
) -> dict[str, Any]:
resp = session.post(
TOKEN_ENDPOINT,
data={
"grant_type": "authorization_code",
"client_id": client_id,
"code": code,
"redirect_uri": redirect_uri,
"code_verifier": verifier,
},
headers={"Content-Type": "application/x-www-form-urlencoded"},
timeout=45,
)
if resp.status_code != 200:
raise PKCEMintError(
f"token exchange failed HTTP {resp.status_code}: {resp.text[:300]}",
code="token_exchange",
retryable=True,
)
token = resp.json()
if "expires_in" in token and "expires_at" not in token:
try:
token["expires_at"] = int(time.time()) + int(token["expires_in"])
except Exception:
pass
if not token.get("access_token") or not token.get("refresh_token"):
raise PKCEMintError(
"token exchange response missing access_token/refresh_token",
code="token_exchange",
retryable=True,
)
return token
def mint_with_sso_pkce(
*,
sso_cookie: str,
email: str = "",
proxy: str | None = None,
timeout: float = 30.0,
log: LogFn | None = None,
cancel: Callable[[], bool] | None = None,
client_id: str = CLIENT_ID,
scope: str = SCOPE,
redirect_uri: str = DEFAULT_REDIRECT_URI,
) -> dict[str, Any]:
"""Mint authorization-code OAuth tokens from an existing accounts.x.ai SSO cookie."""
log = log or _noop_log
resolved = resolve_proxy(proxy)
set_runtime_proxy(resolved or None)
session = _session(resolved or None)
_set_sso_cookie(session, sso_cookie)
state = secrets.token_hex(16)
nonce = secrets.token_hex(16)
verifier = _code_verifier()
challenge = _code_challenge(verifier)
auth_url = _build_authorization_url(
client_id=client_id,
redirect_uri=redirect_uri,
state=state,
nonce=nonce,
code_challenge=challenge,
scope=scope,
)
consent_url = (
f"{ACCOUNTS_ORIGIN}/oauth2/consent?"
+ urlencode(
{
"response_type": "code",
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": scope,
"state": state,
"code_challenge": challenge,
"code_challenge_method": "S256",
"nonce": nonce,
}
)
)
if cancel and cancel():
raise PKCEMintError("cancelled", code="cancelled", retryable=False)
session.get(auth_url, allow_redirects=False, timeout=timeout)
setter = _create_cookie_setter_link(session, consent_url)
log("pkce cookie-setter link ok")
current = setter
for _ in range(6):
if cancel and cancel():
raise PKCEMintError("cancelled", code="cancelled", retryable=False)
if "code=" in current and (current.startswith(redirect_uri) or "127.0.0.1" in current):
code = _code_from_url(current, state)
break
if "set-cookie" not in current:
break
resp = session.get(current, allow_redirects=False, timeout=timeout)
loc = resp.headers.get("location") or resp.headers.get("Location") or ""
log(f"pkce set-cookie HTTP {resp.status_code}")
if not loc:
break
current = urljoin(current, loc)
else:
code = ""
if "code" not in locals():
if "consent" not in current:
raise PKCEMintError(
f"cookie-setter did not reach consent/code: {current[:180]}",
code="cookie_setter_path",
retryable=True,
)
page = session.get(current, allow_redirects=False, timeout=timeout)
loc = page.headers.get("location") or page.headers.get("Location") or ""
if loc and "code=" in loc:
code = _code_from_url(urljoin(current, loc), state)
else:
page_html = page.text or ""
page_url = current
# Follow non-code redirect, or re-fetch with redirects when action id missing
# (empty SPA shell after set-cookie 303 is the smoke-era 404 root cause).
if loc and "code=" not in loc:
page_url = urljoin(current, loc)
page = session.get(page_url, allow_redirects=True, timeout=timeout)
page_html = page.text or ""
page_url = str(getattr(page, "url", None) or page_url)
loc2 = page.headers.get("location") or page.headers.get("Location") or ""
if loc2 and "code=" in loc2:
code = _code_from_url(urljoin(page_url, loc2), state)
if "code" not in locals() or not locals().get("code"):
if not _extract_action_id_from_html(page_html):
page = session.get(page_url, allow_redirects=True, timeout=timeout)
page_html = page.text or ""
page_url = str(getattr(page, "url", None) or page_url)
loc3 = page.headers.get("location") or page.headers.get("Location") or ""
if loc3 and "code=" in loc3:
code = _code_from_url(urljoin(page_url, loc3), state)
if "code" not in locals() or not locals().get("code"):
code = _submit_consent(
session,
page_url=page_url,
page_html=page_html,
client_id=client_id,
redirect_uri=redirect_uri,
scope=scope,
state=state,
code_challenge=challenge,
nonce=nonce,
)
log(f"pkce authorization code ok{f' email={email}' if email else ''}")
token = _exchange_code_for_token(
session,
code=code,
verifier=verifier,
redirect_uri=redirect_uri,
client_id=client_id,
)
return {
"access_token": str(token["access_token"]).strip(),
"refresh_token": str(token["refresh_token"]).strip(),
"id_token": str(token.get("id_token") or "").strip() or None,
"token_type": str(token.get("token_type") or "Bearer"),
"expires_in": int(token.get("expires_in") or 21600),
"mint_method": "pkce",
}
+596
View File
@@ -0,0 +1,596 @@
"""Probe free Grok 4.5 via cli-chat-proxy (direct) or tebi CPA mid-tier."""
from __future__ import annotations
import json
import re
import ssl
import urllib.error
import urllib.request
from typing import Any, Mapping
from .proxyutil import resolve_proxy
from .schema import DEFAULT_BASE_URL, DEFAULT_CLIENT_HEADERS
# Free Build chat 403: account has no L1 entitlement (not a network flake).
_ENTITLEMENT_CODE_RE = re.compile(
r"permission[-_ ]?denied|permission_error|not[_\s-]?allowed|"
r"access[_\s-]?denied|entitlement|insufficient[_\s-]?permission",
re.I,
)
_TRANSIENT_STATUS = frozenset({0, 408, 425, 429, 500, 502, 503, 504})
# Product default pin header name for CPA per-credential routing (if supported).
DEFAULT_CPA_PIN_HEADER = "X-CPA-Credential"
def build_probe_transport(
*,
via: str,
upstream_base_url: str = DEFAULT_BASE_URL,
cpa_base_url: str = "",
cpa_api_key: str = "",
access_token: str = "", # noqa: ARG001 — reserved for callers / future pin modes
credential_pin: str = "",
pin_header: str = DEFAULT_CPA_PIN_HEADER,
) -> dict[str, Any]:
"""Build a probe transport dict for direct bearer or CPA OpenAI-compatible.
mode=direct: Authorization Bearer = xAI access_token + CLI headers.
mode=cpa: Authorization Bearer = CPA API key; optional credential pin header.
"""
_ = access_token # accepted for API symmetry with callers
mode = (via or "direct").strip().lower()
if mode not in {"direct", "cpa"}:
mode = "direct"
upstream = (upstream_base_url or DEFAULT_BASE_URL).rstrip("/")
if mode == "cpa":
base = (cpa_base_url or "").strip().rstrip("/")
if not base:
# Misconfigured CPA → fail closed to direct (same host as auth write).
return {
"mode": "direct",
"base_url": upstream,
"api_key": "",
"credential_pin": "",
"pin_header": "",
"upstream_base_url": upstream,
}
return {
"mode": "cpa",
"base_url": base,
"api_key": (cpa_api_key or "").strip(),
"credential_pin": (credential_pin or "").strip(),
"pin_header": (pin_header or DEFAULT_CPA_PIN_HEADER).strip(),
"upstream_base_url": upstream,
}
return {
"mode": "direct",
"base_url": upstream,
"api_key": "",
"credential_pin": "",
"pin_header": "",
"upstream_base_url": upstream,
}
def resolve_gate_probe_policy(
*,
via: str,
cpa_base_url: str = "",
cpa_api_key: str = "",
credential_pin: str = "",
allow_unpinned_cpa_gate: bool = False,
) -> dict[str, Any]:
"""Decide which path stamps chat_ok (gate) vs optional CPA smoke.
Spec: unpinned CPA pool must not stamp chat_ok. Hybrid keeps gate=direct and
may run observational CPA smoke that never replaces chat_ok for inject.
"""
v = (via or "direct").strip().lower()
if v not in {"direct", "cpa", "hybrid"}:
v = "direct"
pin = (credential_pin or "").strip()
has_cpa = bool((cpa_base_url or "").strip() and (cpa_api_key or "").strip())
if v == "direct" or not has_cpa:
return {
"gate_via": "direct",
"cpa_smoke": False,
"reason": "direct" if v == "direct" else "cpa_config_missing",
}
if v == "hybrid":
return {"gate_via": "direct", "cpa_smoke": True, "reason": "hybrid"}
# via == cpa
if pin or allow_unpinned_cpa_gate:
return {
"gate_via": "cpa",
"cpa_smoke": False,
"reason": "cpa_pinned" if pin else "cpa_unpinned_allowed",
}
return {"gate_via": "direct", "cpa_smoke": True, "reason": "unpinned_cpa_hybrid"}
def probe_request_headers(
transport: Mapping[str, Any],
*,
access_token: str,
) -> dict[str, str]:
"""HTTP headers for models/responses based on transport mode."""
mode = str(transport.get("mode") or "direct")
if mode == "cpa":
key = str(transport.get("api_key") or "").strip()
headers = {
"Authorization": f"Bearer {key}",
"Content-Type": "application/json",
"Accept": "application/json",
}
pin = str(transport.get("credential_pin") or "").strip()
pin_h = str(transport.get("pin_header") or DEFAULT_CPA_PIN_HEADER).strip()
if pin and pin_h:
headers[pin_h] = pin
return headers
return {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
"Accept": "application/json",
**DEFAULT_CLIENT_HEADERS,
}
def remap_cpa_gateway_failure(
raw: Mapping[str, Any],
classified: Mapping[str, Any],
) -> dict[str, Any]:
"""CPA API-key / gateway failures must not stamp entitlement_denied.
Direct cli-chat-proxy 403 remains entitlement. CPA transport 401/ambiguous 403
are ops/config or mid-tier errors unless body clearly is free-Build permission.
"""
out = dict(classified)
if str(raw.get("transport_mode") or "") != "cpa":
return out
status = int(raw.get("status") or 0)
err = str(raw.get("error") or "").lower()
# Clear upstream free-Build denial through CPA still counts as entitlement.
# Tolerate hyphen / underscore / whitespace forms (permission-denied,
# permission_denied, "permission denied") and the console.x.ai marker.
if "permission" in err and "denied" in err and (
"console.x.ai" in err or _ENTITLEMENT_CODE_RE.search(err) is not None
):
out["upstream_entitlement"] = True
# mint hard gate reads entitlement_denied; keep it non-retryable so we
# fail-fast (skip remint/retry) instead of falling to ambiguous-retryable.
out["entitlement_denied"] = True
out["retryable"] = False
out["reason"] = "upstream_entitlement"
out["error_code"] = str(raw.get("error_code") or "permission_denied")
return out
if status == 401 or "api key" in err or "unauthorized" in err or "invalid key" in err:
out["entitlement_denied"] = False
out["retryable"] = False
out["reason"] = "cpa_gateway_auth"
out["error_code"] = str(raw.get("error_code") or status or "unauthorized")
return out
# Ambiguous CPA 403 (no clear free-Build body): not account entitlement.
if status == 403:
out["entitlement_denied"] = False
out["retryable"] = True
out["reason"] = "cpa_gateway_error"
out["error_code"] = str(raw.get("error_code") or "403")
return out
def _ssl_context() -> ssl.SSLContext | None:
try:
import certifi # type: ignore
return ssl.create_default_context(cafile=certifi.where())
except Exception:
return None
def _opener(proxy: str | None = None) -> urllib.request.OpenerDirector:
p = resolve_proxy(proxy)
handlers: list[Any] = []
ctx = _ssl_context()
if ctx is not None:
handlers.append(urllib.request.HTTPSHandler(context=ctx))
if p:
handlers.append(urllib.request.ProxyHandler({"http": p, "https": p}))
return urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener()
def _extract_error_code(error_text: str) -> str:
"""Best-effort parse of API error code/type from JSON or plain text."""
raw = (error_text or "").strip()
if not raw:
return ""
try:
data = json.loads(raw)
except Exception:
data = None
if isinstance(data, dict):
err = data.get("error")
if isinstance(err, dict):
for key in ("code", "type", "error", "message"):
val = err.get(key)
if val is not None and str(val).strip():
if key in ("code", "type", "error"):
return str(val).strip()
msg = err.get("message")
if msg is not None:
return str(msg).strip()[:120]
for key in ("code", "type", "error"):
val = data.get(key)
if val is not None and str(val).strip():
return str(val).strip()
# plain-text fallback: first token-ish match
m = _ENTITLEMENT_CODE_RE.search(raw)
if m:
return m.group(0).lower().replace(" ", "_")
return ""
def classify_chat_probe(result: dict[str, Any] | None) -> dict[str, Any]:
"""Classify /v1/responses probe outcome for product gating.
Returns keys:
ok, entitlement_denied, retryable, error_code, reason
"""
r = result or {}
if r.get("ok"):
return {
"ok": True,
"entitlement_denied": False,
"retryable": False,
"error_code": "",
"reason": "chat_ok",
}
status = int(r.get("status") or 0)
err_text = str(r.get("error") or "")
code = str(r.get("error_code") or _extract_error_code(err_text) or "").strip()
blob = f"{code} {err_text}".lower()
# Free Build /v1/responses: any HTTP 403 is L1 entitlement (models may still 200).
# Observed default is permission-denied; other 403 bodies are still non-retryable.
if status == 403:
return {
"ok": False,
"entitlement_denied": True,
"retryable": False,
"error_code": code or "permission_denied",
"reason": "entitlement_denied",
}
# Explicit permission wording on other statuses (rare) still counts as entitlement.
if _ENTITLEMENT_CODE_RE.search(blob) and status in (400, 401, 404):
return {
"ok": False,
"entitlement_denied": True,
"retryable": False,
"error_code": code or "permission_denied",
"reason": "entitlement_denied",
}
# Client/protocol misconfig — not fixed by remint of same account.
if status in (401, 426):
return {
"ok": False,
"entitlement_denied": False,
"retryable": False,
"error_code": code or str(status),
"reason": "auth_or_protocol",
}
# Free Build quota exhausted (rolling ~24h). Not currently usable — do not inject.
# Not entitlement (will recover after window); not remint-fixed either.
if status == 429 and (
"free-usage-exhausted" in blob
or "free_usage_exhausted" in blob
or "usage-exhausted" in blob
or "usage_exhausted" in blob
):
return {
"ok": False,
"entitlement_denied": False,
"retryable": False,
"error_code": code or "free-usage-exhausted",
"reason": "usage_exhausted",
}
if status in _TRANSIENT_STATUS or status >= 500:
return {
"ok": False,
"entitlement_denied": False,
"retryable": True,
"error_code": code or str(status or "network"),
"reason": "transient",
}
return {
"ok": False,
"entitlement_denied": False,
"retryable": False,
"error_code": code or str(status or "unknown"),
"reason": "chat_failed",
}
# x.ai does not stabilize the Grok-4 model id across accounts/deploys: a live
# account may list grok-4.5, grok-4.6, or a dated grok-4-<build>. The model
# gate accepts any Grok-4 family member; the chat probe targets the listed one.
MODELS_MISSING_ERROR = "token ok but no grok-4 model listed"
MODELS_MISSING_REASON = "models_missing_grok_45"
def is_grok4_model(model_id: Any) -> bool:
"""True for any Grok-4 generation id (grok-4, grok-4.5, grok-4.6, grok-4-*)."""
if not isinstance(model_id, str):
return False
mid = model_id.strip().lower()
return mid == "grok-4" or mid.startswith("grok-4.") or mid.startswith("grok-4-")
def pick_chat_probe_model(model_ids, fallback: str = "grok-4.5") -> str:
"""Return the first listed Grok-4 member for the chat probe, else fallback."""
for i in model_ids or []:
if is_grok4_model(i):
return i
return fallback
def probe_models(
access_token: str,
*,
base_url: str = DEFAULT_BASE_URL,
timeout: float = 30.0,
proxy: str | None = None,
transport: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
t = dict(
transport
or build_probe_transport(
via="direct",
upstream_base_url=base_url,
access_token=access_token,
)
)
base = str(t.get("base_url") or base_url).rstrip("/")
url = f"{base}/models"
headers = probe_request_headers(t, access_token=access_token)
headers.setdefault("Accept", "application/json")
opener = _opener(proxy)
req = urllib.request.Request(url, headers=headers, method="GET")
mode = str(t.get("mode") or "direct")
try:
with opener.open(req, timeout=timeout) as resp:
body = json.loads(resp.read().decode("utf-8"))
ids = [x.get("id") for x in body.get("data") or [] if isinstance(x, dict)]
return {
"ok": True,
"status": getattr(resp, "status", 200),
"model_ids": ids,
"has_grok_45": any(is_grok4_model(i) for i in ids),
"transport_mode": mode,
}
except urllib.error.HTTPError as e:
err_body = e.read().decode("utf-8", errors="replace")[:500]
out = {
"ok": False,
"status": e.code,
"error": err_body,
"error_code": _extract_error_code(err_body),
"model_ids": [],
"has_grok_45": False,
"transport_mode": mode,
}
return out
except Exception as e: # noqa: BLE001
return {
"ok": False,
"status": 0,
"error": str(e),
"model_ids": [],
"has_grok_45": False,
"transport_mode": mode,
}
def probe_chat_with_retries(
access_token: str,
*,
base_url: str = DEFAULT_BASE_URL,
proxy: str | None = None,
max_attempts: int = 3,
timeout: float = 60.0,
sleep_fn: Any | None = None,
log: Any | None = None,
transport: Mapping[str, Any] | None = None,
model: str = "grok-4.5",
) -> dict[str, Any]:
"""Probe /v1/responses with classification + transient retries.
Shared by mint and historical backfill so retry/classification stay aligned.
Returns the last probe dict (includes classify_chat_probe fields) plus
``attempts`` count.
"""
import time as _time
_sleep = sleep_fn or _time.sleep
_log = log or (lambda _m: None)
max_attempts = max(1, int(max_attempts or 1))
ch: dict[str, Any] = {}
for attempt in range(1, max_attempts + 1):
ch = probe_mini_response(
access_token,
base_url=base_url,
proxy=proxy,
timeout=timeout,
transport=transport,
model=model,
)
# probe_mini_response already attaches classification; re-apply for safety.
cls = classify_chat_probe(ch)
for k, v in cls.items():
ch.setdefault(k, v)
# CPA gateway remap must win over raw 403→entitlement classification.
if str(ch.get("transport_mode") or "") == "cpa":
remapped = remap_cpa_gateway_failure(ch, ch)
for k, v in remapped.items():
ch[k] = v
_log(
f"probe chat attempt={attempt}/{max_attempts}: ok={ch.get('ok')} "
f"status={ch.get('status')} entitlement_denied={ch.get('entitlement_denied')} "
f"retryable={ch.get('retryable')} code={ch.get('error_code')!r} "
f"mode={ch.get('transport_mode')!r} model={ch.get('model')} text={ch.get('text')!r}"
)
if ch.get("ok") or ch.get("entitlement_denied") or not ch.get("retryable"):
ch["attempts"] = attempt
return ch
if attempt < max_attempts:
_sleep(1.5 * attempt)
ch["attempts"] = max_attempts
return ch
def apply_chat_probe_to_result(
result: dict[str, Any],
ch: dict[str, Any] | None,
*,
models_missing: bool = False,
models_status: int | None = None,
) -> dict[str, Any]:
"""Mutate mint/backfill result with chat probe classification fields.
Keeps mint + backfill outcome fields identical for stamp/remint consumers.
"""
if models_missing:
result["ok"] = False
result["chat_ok"] = False
result["usable"] = False
result["entitlement_denied"] = False
result["chat_retryable"] = bool(
models_status in (0, 408, 429, 500, 502, 503, 504)
)
result["fail_reason"] = MODELS_MISSING_REASON
if not result.get("error"):
result["error"] = MODELS_MISSING_ERROR
return result
ch = ch or {}
result["probe_chat"] = ch
result["chat_attempts"] = int(ch.get("attempts") or 0)
result["chat_ok"] = bool(ch.get("ok"))
result["entitlement_denied"] = bool(ch.get("entitlement_denied"))
result["chat_retryable"] = bool(ch.get("retryable")) and not bool(ch.get("ok"))
result["chat_error_code"] = ch.get("error_code") or ""
if ch.get("ok"):
result["ok"] = True
result["usable"] = True
result["chat_retryable"] = False
result["entitlement_denied"] = False
result["fail_reason"] = ""
result.pop("error", None)
return result
result["ok"] = False
result["usable"] = False
if ch.get("entitlement_denied"):
result["error"] = (
"chat entitlement denied (permission-denied): "
"account has no free Build chat grant; do not remint"
)
result["non_retryable"] = True
result["chat_retryable"] = False
result["fail_reason"] = "entitlement_denied"
else:
result["error"] = (
f"chat probe failed: status={ch.get('status')} "
f"code={ch.get('error_code') or ''} "
f"{(ch.get('error') or '')[:200]}"
)
result["non_retryable"] = not bool(ch.get("retryable"))
result["fail_reason"] = str(ch.get("reason") or "chat_failed")
if ch.get("retryable"):
result["chat_retryable"] = True
return result
def probe_mini_response(
access_token: str,
*,
base_url: str = DEFAULT_BASE_URL,
model: str = "grok-4.5",
timeout: float = 60.0,
proxy: str | None = None,
transport: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
t = dict(
transport
or build_probe_transport(
via="direct",
upstream_base_url=base_url,
access_token=access_token,
)
)
base = str(t.get("base_url") or base_url).rstrip("/")
url = f"{base}/responses"
payload = {
"model": model,
"stream": False,
"input": "Reply with exactly MINT_OK",
"reasoning": {"effort": "low"},
}
headers = probe_request_headers(t, access_token=access_token)
headers.setdefault("Content-Type", "application/json")
headers.setdefault("Accept", "application/json")
opener = _opener(proxy)
req = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers=headers,
method="POST",
)
mode = str(t.get("mode") or "direct")
try:
with opener.open(req, timeout=timeout) as resp:
body = json.loads(resp.read().decode("utf-8"))
texts: list[str] = []
for item in body.get("output") or []:
if item.get("type") == "message":
for c in item.get("content") or []:
if c.get("type") == "output_text":
texts.append(c.get("text") or "")
out = {
"ok": True,
"status": getattr(resp, "status", 200),
"model": body.get("model"),
"text": "\n".join(texts),
"usage": body.get("usage"),
"transport_mode": mode,
}
out.update(classify_chat_probe(out))
return out
except urllib.error.HTTPError as e:
err_body = e.read().decode("utf-8", errors="replace")[:800]
out = {
"ok": False,
"status": e.code,
"error": err_body,
"error_code": _extract_error_code(err_body),
"transport_mode": mode,
}
cls = classify_chat_probe(out)
out.update(remap_cpa_gateway_failure(out, cls))
return out
except Exception as e: # noqa: BLE001
out = {
"ok": False,
"status": 0,
"error": str(e),
"transport_mode": mode,
}
out.update(classify_chat_probe(out))
return out
+290
View File
@@ -0,0 +1,290 @@
"""Pure-HTTP SSO cookie → OIDC tokens (device flow, no browser).
Uses curl_cffi (Chrome TLS fingerprint) + SSO cookie to:
1. Validate session on accounts.x.ai
2. Request device code (stdlib / oauth_device)
3. GET verification_uri_complete
4. POST /oauth2/device/verify
5. POST /oauth2/device/approve
6. Poll token endpoint
On any failure raise ProtocolMintError so callers can fall back to browser mint.
"""
from __future__ import annotations
from typing import Any, Callable
from urllib.parse import urlparse
from .oauth_device import (
CLIENT_ID,
ISSUER,
OAuthDeviceError,
SCOPE,
poll_device_token,
request_device_code,
)
from .proxyutil import proxy_log_label, resolve_proxy, set_runtime_proxy
LogFn = Callable[[str], None]
VERIFY_URL = f"{ISSUER}/oauth2/device/verify"
APPROVE_URL = f"{ISSUER}/oauth2/device/approve"
class ProtocolMintError(RuntimeError):
"""Protocol path failed; caller may fall back to browser mint."""
def _noop_log(_: str) -> None:
return None
def extract_sso_from_cookies(cookies: Any) -> str:
"""Pull sso / sso-rw value from a cookie list/dict (normalized)."""
from .accounts import normalize_sso_cookie
raw = ""
if not cookies:
return ""
if isinstance(cookies, str):
raw = cookies.strip()
elif isinstance(cookies, dict):
for name in ("sso", "sso-rw"):
v = cookies.get(name)
if v:
raw = str(v).strip()
break
elif isinstance(cookies, (list, tuple)):
# Prefer bare "sso" over "sso-rw"
found_rw = ""
for c in cookies:
if not isinstance(c, dict):
continue
name = str(c.get("name") or c.get("Name") or "")
value = c.get("value") if "value" in c else c.get("Value")
if not value:
continue
if name == "sso":
raw = str(value).strip()
break
if name == "sso-rw" and not found_rw:
found_rw = str(value).strip()
else:
raw = found_rw
return normalize_sso_cookie(raw)
def _session(proxy: str | None, log: LogFn):
try:
from curl_cffi import requests as cf_requests
except ImportError as e:
raise ProtocolMintError(
"curl_cffi not installed; cannot run protocol mint"
) from e
s = cf_requests.Session()
resolved = resolve_proxy(proxy)
if resolved:
s.proxies = {"http": resolved, "https": resolved}
log(f"protocol proxy={proxy_log_label(resolved)}")
return s
def _set_sso_cookie(session: Any, sso_cookie: str) -> None:
from .accounts import normalize_sso_cookie
sso_cookie = normalize_sso_cookie(sso_cookie)
if not sso_cookie:
raise ProtocolMintError("empty sso cookie")
for domain in (".x.ai", "accounts.x.ai", "auth.x.ai", ".accounts.x.ai"):
try:
session.cookies.set("sso", sso_cookie, domain=domain)
except Exception:
try:
session.cookies.set("sso", sso_cookie, domain=domain, path="/")
except Exception:
pass
try:
session.cookies.set("sso-rw", sso_cookie, domain=domain)
except Exception:
pass
def _url_path(url: str) -> str:
try:
return urlparse(url or "").path or ""
except Exception:
return url or ""
def mint_with_sso_protocol(
*,
sso_cookie: str,
email: str = "",
proxy: str | None = None,
timeout: float = 30.0,
poll_timeout_sec: float = 90.0,
log: LogFn | None = None,
cancel: Callable[[], bool] | None = None,
) -> dict[str, Any]:
"""SSO cookie → OIDC token dict (access/refresh/id/expires_in).
Raises ProtocolMintError on failure.
"""
from .accounts import normalize_sso_cookie
log = log or _noop_log
sso_cookie = normalize_sso_cookie(sso_cookie)
if not sso_cookie:
raise ProtocolMintError("missing sso cookie")
resolved = resolve_proxy(proxy)
set_runtime_proxy(resolved or None)
session = _session(resolved or None, log)
_set_sso_cookie(session, sso_cookie)
# 1) Validate SSO
try:
r = session.get(
"https://accounts.x.ai/",
impersonate="chrome",
timeout=timeout,
allow_redirects=True,
)
except Exception as e: # noqa: BLE001
raise ProtocolMintError(f"accounts.x.ai network error: {e}") from e
final_url = getattr(r, "url", "") or ""
if "sign-in" in final_url or "sign-up" in final_url:
raise ProtocolMintError(f"sso invalid (landed {final_url[:120]})")
log(f"protocol sso valid url={final_url[:120]}")
# 2) Device code
try:
sess = request_device_code(proxy=resolved or None, timeout=timeout)
except OAuthDeviceError as e:
raise ProtocolMintError(f"device code: {e}") from e
except Exception as e: # noqa: BLE001
raise ProtocolMintError(f"device code: {e}") from e
log(f"protocol user_code={sess.user_code}")
if cancel and cancel():
raise ProtocolMintError("cancelled")
# 3) Open verification URI (sets session state / CSRF)
try:
r = session.get(
sess.verification_uri_complete,
impersonate="chrome",
timeout=timeout,
allow_redirects=True,
)
log(f"protocol verify-uri status={getattr(r, 'status_code', '?')} url={getattr(r, 'url', '')[:140]}")
except Exception as e: # noqa: BLE001
raise ProtocolMintError(f"verification_uri get failed: {e}") from e
if cancel and cancel():
raise ProtocolMintError("cancelled")
# 4) POST device/verify
try:
r = session.post(
VERIFY_URL,
data={"user_code": sess.user_code},
headers={"Content-Type": "application/x-www-form-urlencoded"},
impersonate="chrome",
timeout=timeout,
allow_redirects=True,
)
except Exception as e: # noqa: BLE001
raise ProtocolMintError(f"device/verify exception: {e}") from e
verify_url = getattr(r, "url", "") or ""
status = getattr(r, "status_code", 0)
path = _url_path(verify_url)
body_snip = ""
try:
body_snip = (r.text or "")[:200]
except Exception:
pass
if "consent" not in verify_url and "consent" not in path:
# Some flows land on consent via relative redirect body; accept soft signals
soft_ok = (
"consent" in (body_snip or "").lower()
or "authorize grok build" in (body_snip or "").lower()
or "授权 grok build" in (body_snip or "").lower()
)
if not soft_ok:
raise ProtocolMintError(
f"device/verify failed status={status} url={verify_url[:160]}"
)
log(f"protocol verify ok status={status} url={verify_url[:140]}")
if cancel and cancel():
raise ProtocolMintError("cancelled")
# 5) POST device/approve
try:
r = session.post(
APPROVE_URL,
data={
"user_code": sess.user_code,
"action": "allow",
"principal_type": "User",
"principal_id": "",
},
headers={"Content-Type": "application/x-www-form-urlencoded"},
impersonate="chrome",
timeout=timeout,
allow_redirects=True,
)
except Exception as e: # noqa: BLE001
raise ProtocolMintError(f"device/approve exception: {e}") from e
approve_url = getattr(r, "url", "") or ""
status = getattr(r, "status_code", 0)
if "done" not in approve_url and "device/done" not in _url_path(approve_url):
# Accept success page markers in body
try:
text = r.text or ""
except Exception:
text = ""
if "设备已授权" not in text and "device authorized" not in text.lower() and "done" not in text.lower():
raise ProtocolMintError(
f"device/approve failed status={status} url={approve_url[:160]}"
)
log(f"protocol approve ok status={status} url={approve_url[:140]}")
# 6) Poll tokens
poll_expires = min(int(sess.expires_in), max(int(poll_timeout_sec), 30))
try:
tr = poll_device_token(
sess.device_code,
interval=max(int(sess.interval), 2),
expires_in=poll_expires,
timeout=timeout,
log=log,
cancel=cancel,
proxy=resolved or None,
)
except OAuthDeviceError as e:
raise ProtocolMintError(f"token poll: {e}") from e
except Exception as e: # noqa: BLE001
raise ProtocolMintError(f"token poll: {e}") from e
log(
f"protocol token ok expires_in={tr.expires_in}"
+ (f" email={email}" if email else "")
)
return {
"access_token": tr.access_token,
"refresh_token": tr.refresh_token,
"id_token": tr.id_token,
"token_type": tr.token_type,
"expires_in": tr.expires_in,
"user_code": sess.user_code,
"mint_method": "protocol",
}
+71
View File
@@ -0,0 +1,71 @@
"""Resolve outbound proxy for CPA mint HTTP + browser.
Priority (highest first):
1. explicit argument
2. thread-local runtime pin (set_runtime_proxy)
3. environment https_proxy / HTTPS_PROXY / http_proxy / HTTP_PROXY
Thread-local pin avoids cross-talk when multiple mint workers run with
different proxies in the same process.
"""
from __future__ import annotations
import os
import threading
from urllib.parse import urlparse
_thread = threading.local()
def set_runtime_proxy(proxy: str | None) -> None:
"""Pin proxy for the *current thread*. Empty clears pin."""
p = (proxy or "").strip()
_thread.proxy = p or None
def get_runtime_proxy() -> str | None:
return getattr(_thread, "proxy", None)
def resolve_proxy(explicit: str | None = None) -> str:
for cand in (
(explicit or "").strip(),
(get_runtime_proxy() or "").strip(),
(os.environ.get("https_proxy") or "").strip(),
(os.environ.get("HTTPS_PROXY") or "").strip(),
(os.environ.get("http_proxy") or "").strip(),
(os.environ.get("HTTP_PROXY") or "").strip(),
):
if cand:
return cand
return ""
def proxy_for_chromium(proxy: str) -> str:
"""Chromium --proxy-server cannot embed user:pass; host:port only."""
p = (proxy or "").strip()
if not p:
return ""
u = urlparse(p if "://" in p else f"http://{p}")
host = u.hostname or ""
if not host:
return ""
port = u.port or (443 if (u.scheme or "http") == "https" else 80)
scheme = u.scheme or "http"
return f"{scheme}://{host}:{port}"
def proxy_log_label(proxy: str) -> str:
"""Redact userinfo for logs."""
p = (proxy or "").strip()
if not p:
return ""
try:
u = urlparse(p if "://" in p else f"http://{p}")
host = u.hostname or "?"
port = u.port or ""
auth = "user:***@" if u.username else ""
return f"{u.scheme or 'http'}://{auth}{host}{(':' + str(port)) if port else ''}"
except Exception:
return "(proxy)"
+564
View File
@@ -0,0 +1,564 @@
"""Refresh CPA xAI OAuth tokens and persist rotation immediately.
xAI refresh responses may rotate ``refresh_token``. Once the server issues a new
RT, the previous RT is **revoked**. Callers that probe or import MUST:
1. Prefer a still-valid access_token (no refresh) — avoid unnecessary rotation.
2. When refresh is required, write the new RT to the real auth path in the same
step, then **re-read and verify** the on-disk RT matches.
3. Never treat ``ok`` as success if ``refresh_rotated`` and ``persisted`` is false.
Backups taken *before* a lost rotation cannot revive a revoked RT — recovery is
only possible if the *new* RT was persisted (or never rotated).
"""
from __future__ import annotations
import json
import os
import ssl
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from .proxyutil import resolve_proxy
from .schema import (
CLIENT_ID,
DEFAULT_CLIENT_HEADERS,
DEFAULT_TOKEN_ENDPOINT,
build_cpa_xai_auth,
expired_from_access_token,
jwt_payload,
)
from .writer import patch_cpa_xai_auth, write_cpa_xai_auth
# Refresh only when access expires within this many seconds (clock skew / race).
ACCESS_SKEW_SECONDS = 120
# Side-ledger of rotated RTs (append-only). Not a substitute for on-disk auth,
# but gives an audit trail if a write race is suspected.
RT_ROTATION_LEDGER = "rt_rotation.jsonl"
def _ssl_context() -> ssl.SSLContext | None:
try:
import certifi # type: ignore
return ssl.create_default_context(cafile=certifi.where())
except Exception:
return None
def _opener(proxy: str | None = None) -> urllib.request.OpenerDirector:
p = resolve_proxy(proxy)
handlers: list[Any] = []
ctx = _ssl_context()
if ctx is not None:
handlers.append(urllib.request.HTTPSHandler(context=ctx))
if p:
handlers.append(urllib.request.ProxyHandler({"http": p, "https": p}))
return urllib.request.build_opener(*handlers) if handlers else urllib.request.build_opener()
def access_token_seconds_left(access_token: str, *, now: float | None = None) -> float | None:
"""Return seconds until JWT exp, or None if token is not a decodable JWT."""
try:
pl = jwt_payload(access_token)
exp = float(pl["exp"])
except Exception:
return None
t = time.time() if now is None else float(now)
return exp - t
def access_token_usable(
access_token: str,
*,
skew_seconds: int = ACCESS_SKEW_SECONDS,
now: float | None = None,
) -> bool:
"""True when access_token is present and not near/past JWT exp."""
at = (access_token or "").strip()
if not at:
return False
left = access_token_seconds_left(at, now=now)
if left is None:
# Non-JWT / opaque: treat as usable if non-empty; caller may still 401.
return True
return left > float(skew_seconds)
def _append_rt_rotation_ledger(
auth_path: Path,
*,
email: str,
old_rt: str,
new_rt: str,
rotated: bool,
) -> str | None:
"""Append one RT rotation audit line next to the auth file. Best-effort path return."""
if not rotated or not old_rt or not new_rt or old_rt == new_rt:
return None
try:
ledger = auth_path.parent / RT_ROTATION_LEDGER
rec = {
"ts": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"email": (email or "").strip().lower(),
"auth_file": auth_path.name,
"auth_path": str(auth_path),
"old_rt_prefix": old_rt[:12],
"new_rt_prefix": new_rt[:12],
"old_rt": old_rt,
"new_rt": new_rt,
}
with open(ledger, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
f.flush()
os.fsync(f.fileno())
try:
os.chmod(ledger, 0o600)
except OSError:
pass
return str(ledger)
except Exception:
return None
def _write_pre_rotate_snapshot(auth_path: Path, data: dict[str, Any]) -> str | None:
"""Atomic copy of auth JSON before refresh. Recoverable only if server did not rotate yet."""
try:
snap_dir = auth_path.parent / ".rt_prerotate"
snap_dir.mkdir(parents=True, exist_ok=True)
try:
os.chmod(snap_dir, 0o700)
except OSError:
pass
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
dest = snap_dir / f"{auth_path.stem}.{ts}.json"
payload = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
fd, tmp_name = tempfile.mkstemp(prefix=".pre-", suffix=".tmp", dir=str(snap_dir))
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(payload)
f.flush()
os.fsync(f.fileno())
os.chmod(tmp_name, 0o600)
os.replace(tmp_name, dest)
os.chmod(dest, 0o600)
finally:
if os.path.exists(tmp_name):
try:
os.unlink(tmp_name)
except OSError:
pass
return str(dest)
except Exception:
return None
def _verify_persisted_tokens(
path: Path,
*,
expect_access: str,
expect_refresh: str,
) -> dict[str, Any]:
"""Re-read auth file; require access + refresh match post-refresh values."""
try:
disk = json.loads(path.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
return {"ok": False, "error": f"re-read failed: {e}"}
if not isinstance(disk, dict):
return {"ok": False, "error": "re-read root not object"}
got_at = str(disk.get("access_token") or "").strip()
got_rt = str(disk.get("refresh_token") or "").strip()
if got_rt != expect_refresh:
return {
"ok": False,
"error": (
f"persist verify failed: disk RT mismatch "
f"(want prefix {expect_refresh[:12]!r} got {got_rt[:12]!r})"
),
"disk_rt_prefix": got_rt[:12],
"want_rt_prefix": expect_refresh[:12],
}
if got_at != expect_access:
return {
"ok": False,
"error": (
f"persist verify failed: disk access mismatch "
f"(want prefix {expect_access[:16]!r} got {got_at[:16]!r})"
),
}
return {"ok": True, "disk": disk}
def refresh_xai_tokens(
*,
refresh_token: str,
client_id: str = CLIENT_ID,
token_endpoint: str = DEFAULT_TOKEN_ENDPOINT,
proxy: str | None = None,
timeout: float = 45.0,
) -> dict[str, Any]:
"""Exchange refresh_token for a new access_token (and possibly new refresh).
Returns:
ok, status, access_token, refresh_token, id_token?, expires_in?, error?
"""
rt = (refresh_token or "").strip()
if not rt:
return {"ok": False, "status": 0, "error": "missing_refresh_token"}
endpoint = (token_endpoint or DEFAULT_TOKEN_ENDPOINT).strip()
data = urllib.parse.urlencode(
{
"grant_type": "refresh_token",
"refresh_token": rt,
"client_id": client_id or CLIENT_ID,
}
).encode("utf-8")
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
**DEFAULT_CLIENT_HEADERS,
}
req = urllib.request.Request(endpoint, data=data, headers=headers, method="POST")
try:
with _opener(proxy).open(req, timeout=timeout) as resp:
body = json.loads(resp.read().decode("utf-8"))
access = str(body.get("access_token") or "").strip()
if not access:
return {
"ok": False,
"status": getattr(resp, "status", 200),
"error": "token response missing access_token",
}
new_rt = str(body.get("refresh_token") or "").strip() or rt
return {
"ok": True,
"status": getattr(resp, "status", 200),
"access_token": access,
"refresh_token": new_rt,
"refresh_rotated": new_rt != rt,
"id_token": str(body.get("id_token") or "").strip(),
"expires_in": body.get("expires_in"),
"token_type": body.get("token_type") or "Bearer",
}
except urllib.error.HTTPError as e:
err = e.read().decode("utf-8", errors="replace")[:500]
return {
"ok": False,
"status": e.code,
"error": err,
"error_code": "invalid_grant" if e.code == 400 and "invalid_grant" in err else str(e.code),
}
except Exception as e: # noqa: BLE001
return {"ok": False, "status": 0, "error": str(e)[:300]}
def refresh_auth_file(
path: str | Path,
*,
proxy: str | None = None,
persist: bool = True,
timeout: float = 45.0,
require_persist_on_rotate: bool = True,
) -> dict[str, Any]:
"""Refresh one xai-*.json auth file and optionally persist rotated tokens.
When ``persist=True`` (default), writes access/refresh/id/expired back to
the same path immediately after a successful refresh — before any probe —
then re-reads the file to verify the new RT is on disk.
If the server rotated the RT and persist is off or fails, returns
``ok=False`` (fail-closed) when ``require_persist_on_rotate`` is True —
silent success with a dead on-disk RT is never allowed.
"""
p = Path(path).expanduser().resolve()
if not p.is_file():
return {"ok": False, "error": f"missing auth file: {p}", "path": str(p)}
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
return {"ok": False, "error": f"invalid json: {e}", "path": str(p)}
if not isinstance(data, dict):
return {"ok": False, "error": "auth root must be object", "path": str(p)}
email = str(data.get("email") or "").strip()
old_rt = str(data.get("refresh_token") or "").strip()
prerotate = _write_pre_rotate_snapshot(p, data)
ref = refresh_xai_tokens(
refresh_token=old_rt,
token_endpoint=str(data.get("token_endpoint") or DEFAULT_TOKEN_ENDPOINT),
proxy=proxy,
timeout=timeout,
)
out: dict[str, Any] = {
"path": str(p),
"email": email,
"ok": bool(ref.get("ok")),
"status": ref.get("status"),
"refresh_rotated": bool(ref.get("refresh_rotated")),
"prerotate_snapshot": prerotate,
"source": "refresh",
}
if not ref.get("ok"):
out["error"] = ref.get("error")
out["error_code"] = ref.get("error_code")
return out
access = str(ref["access_token"])
refresh = str(ref["refresh_token"])
id_token = str(ref.get("id_token") or data.get("id_token") or "")
rotated = bool(ref.get("refresh_rotated")) or (refresh != old_rt)
out["refresh_rotated"] = rotated
try:
expired, expires_in, sub = expired_from_access_token(access)
except Exception:
expired = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
expires_in = int(ref.get("expires_in") or 0) or 21600
sub = str(data.get("sub") or "")
updates = {
"access_token": access,
"refresh_token": refresh,
"expired": expired,
"expires_in": expires_in or int(ref.get("expires_in") or 0) or 21600,
"last_refresh": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"token_type": ref.get("token_type") or data.get("token_type") or "Bearer",
}
if id_token:
updates["id_token"] = id_token
if sub and not data.get("sub"):
updates["sub"] = sub
out.update(
{
"access_token": access,
"refresh_token": refresh,
"id_token": id_token,
"expired": expired,
"expires_in": updates["expires_in"],
"sub": sub or data.get("sub"),
}
)
# Fail-closed: rotation without persist is permanent credential loss.
if rotated and not persist and require_persist_on_rotate:
out["ok"] = False
out["persisted"] = False
out["error"] = (
"refresh rotated RT but persist=False; refusing to return ok "
"(old RT is revoked — would leave unrecoverable credential)"
)
out["error_code"] = "rt_rotate_persist_required"
out["fatal_rt_loss_risk"] = True
# Still try to force-persist to save the new RT even when caller asked not to.
try:
patch_cpa_xai_auth(p, updates)
verify = _verify_persisted_tokens(p, expect_access=access, expect_refresh=refresh)
if verify.get("ok"):
out["ok"] = True
out["persisted"] = True
out["persist_forced"] = True
out["error"] = None
out["fatal_rt_loss_risk"] = False
_append_rt_rotation_ledger(
p, email=email, old_rt=old_rt, new_rt=refresh, rotated=True
)
return out
out["error"] = f"forced persist after rotate failed verify: {verify.get('error')}"
except Exception as e: # noqa: BLE001
out["error"] = f"forced persist after rotate failed: {e}"
return out
if persist:
try:
patch_cpa_xai_auth(p, updates)
verify = _verify_persisted_tokens(p, expect_access=access, expect_refresh=refresh)
if not verify.get("ok"):
# One more full rewrite attempt before fail-closed.
payload = build_cpa_xai_auth(
email=email,
access_token=access,
refresh_token=refresh,
id_token=id_token,
sub=str(sub or data.get("sub") or ""),
base_url=str(data.get("base_url") or ""),
priority=int(data.get("priority") or 1000),
disabled=bool(data.get("disabled")),
)
for k in (
"chat_ok",
"usable",
"entitlement_denied",
"chat_retryable",
"import_gate",
"fail_reason",
"chat_error_code",
"headers",
):
if k in data:
payload[k] = data[k]
write_cpa_xai_auth(p.parent, payload, filename=p.name)
verify = _verify_persisted_tokens(p, expect_access=access, expect_refresh=refresh)
out["persist_fallback"] = True
if not verify.get("ok"):
out["ok"] = False
out["persisted"] = False
out["error"] = (
f"refresh ok but persist verify failed: {verify.get('error')}"
)
out["error_code"] = "rt_persist_verify_failed"
out["fatal_rt_loss_risk"] = bool(rotated)
return out
out["persisted"] = True
if rotated:
ledger = _append_rt_rotation_ledger(
p, email=email, old_rt=old_rt, new_rt=refresh, rotated=True
)
out["rt_rotation_ledger"] = ledger
except Exception as e: # noqa: BLE001
try:
payload = build_cpa_xai_auth(
email=email,
access_token=access,
refresh_token=refresh,
id_token=id_token,
sub=str(sub or data.get("sub") or ""),
base_url=str(data.get("base_url") or ""),
priority=int(data.get("priority") or 1000),
disabled=bool(data.get("disabled")),
)
for k in (
"chat_ok",
"usable",
"entitlement_denied",
"chat_retryable",
"import_gate",
"fail_reason",
"chat_error_code",
"headers",
):
if k in data:
payload[k] = data[k]
write_cpa_xai_auth(p.parent, payload, filename=p.name)
verify = _verify_persisted_tokens(p, expect_access=access, expect_refresh=refresh)
if not verify.get("ok"):
out["ok"] = False
out["persisted"] = False
out["error"] = (
f"refresh ok but persist failed: {e}; verify={verify.get('error')}"
)
out["error_code"] = "rt_persist_failed"
out["fatal_rt_loss_risk"] = bool(rotated)
return out
out["persisted"] = True
out["persist_fallback"] = True
if rotated:
ledger = _append_rt_rotation_ledger(
p, email=email, old_rt=old_rt, new_rt=refresh, rotated=True
)
out["rt_rotation_ledger"] = ledger
except Exception as e2: # noqa: BLE001
out["ok"] = False
out["error"] = f"refresh ok but persist failed: {e}; {e2}"
out["persisted"] = False
out["error_code"] = "rt_persist_failed"
out["fatal_rt_loss_risk"] = bool(rotated)
return out
else:
out["persisted"] = False
return out
def ensure_auth_tokens(
path: str | Path,
*,
proxy: str | None = None,
skew_seconds: int = ACCESS_SKEW_SECONDS,
force_refresh: bool = False,
timeout: float = 45.0,
) -> dict[str, Any]:
"""Return usable access+refresh for an auth file, refreshing only when needed.
Default policy (access-first):
- If access_token is still valid past skew → return disk tokens, **no**
network refresh (avoids RT rotation).
- Else → ``refresh_auth_file(..., persist=True)`` with verify.
``force_refresh=True`` always hits the token endpoint (import ops that
explicitly need a brand-new access for remote CPA).
"""
p = Path(path).expanduser().resolve()
if not p.is_file():
return {
"ok": False,
"error": f"missing auth file: {p}",
"path": str(p),
"source": "missing",
}
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception as e: # noqa: BLE001
return {
"ok": False,
"error": f"invalid json: {e}",
"path": str(p),
"source": "invalid",
}
if not isinstance(data, dict):
return {
"ok": False,
"error": "auth root must be object",
"path": str(p),
"source": "invalid",
}
email = str(data.get("email") or "").strip()
access = str(data.get("access_token") or "").strip()
refresh = str(data.get("refresh_token") or "").strip()
id_token = str(data.get("id_token") or "").strip()
left = access_token_seconds_left(access)
base: dict[str, Any] = {
"path": str(p),
"email": email,
"access_token": access,
"refresh_token": refresh,
"id_token": id_token,
"sub": data.get("sub"),
"access_seconds_left": left,
"refresh_rotated": False,
"persisted": False,
}
if not refresh:
base.update({"ok": False, "error": "missing_refresh_token", "source": "disk"})
return base
if not force_refresh and access_token_usable(access, skew_seconds=skew_seconds):
base.update(
{
"ok": True,
"source": "access_reuse",
"expired": data.get("expired"),
"expires_in": data.get("expires_in"),
}
)
return base
if not force_refresh and access and left is None:
# Opaque access token with no exp — reuse; import will 401 → then refresh.
base.update({"ok": True, "source": "access_reuse_opaque"})
return base
ref = refresh_auth_file(p, proxy=proxy, persist=True, timeout=timeout)
ref.setdefault("source", "refresh")
return ref
+155
View File
@@ -0,0 +1,155 @@
"""CPA xAI auth JSON schema aligned with CLIProxyAPI internal/auth/xai."""
from __future__ import annotations
import base64
import json
import re
from datetime import datetime, timezone
from typing import Any
# Must match CLIProxyAPI internal/auth/xai/types.go
CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
ISSUER = "https://auth.x.ai"
DEFAULT_TOKEN_ENDPOINT = "https://auth.x.ai/oauth2/token"
DEFAULT_REDIRECT_URI = "http://127.0.0.1:56121/callback"
# Free Build promo path (NOT api.x.ai)
DEFAULT_BASE_URL = "https://cli-chat-proxy.grok.com/v1"
# Aligned with grokbuild-proxy internal/upstream/client.go defaults:
# DefaultClientIdentifier="grok-pager", DefaultUserAgent dual-tag,
# DefaultClientVersion="0.2.93", DefaultTokenAuth="xai-grok-cli".
# Carrying the official CLI identity eliminates the 426 "version (none)
# outdated" gateway response on cli-chat-proxy.grok.com. A 403 from
# /v1/responses is account-side entitlement (no free Build chat grant),
# not a header mismatch.
DEFAULT_CLIENT_HEADERS: dict[str, str] = {
"x-grok-client-version": "0.2.93",
"x-xai-token-auth": "xai-grok-cli",
"x-grok-client-identifier": "grok-pager",
"User-Agent": "grok-pager/0.2.93 grok-shell/0.2.93 (linux; x86_64)",
}
def _sanitize_file_segment(value: str) -> str:
"""Mirror CPA CredentialFileName sanitize rules."""
value = (value or "").strip()
if not value:
return ""
out: list[str] = []
for ch in value:
if (
("a" <= ch <= "z")
or ("A" <= ch <= "Z")
or ("0" <= ch <= "9")
or ch in {"@", ".", "_", "-"}
):
out.append(ch)
else:
out.append("-")
return "".join(out).strip("-")
def credential_file_name(email: str = "", sub: str = "") -> str:
"""Return CPA auth filename: xai-<email>.json."""
email_s = _sanitize_file_segment(email)
if email_s:
return f"xai-{email_s}.json"
sub_s = _sanitize_file_segment(sub)
if sub_s:
return f"xai-{sub_s}.json"
ts = int(datetime.now(tz=timezone.utc).timestamp() * 1000)
return f"xai-{ts}.json"
def jwt_payload(token: str) -> dict[str, Any]:
parts = token.split(".")
if len(parts) < 2:
raise ValueError("not a JWT")
pad = "=" * (-len(parts[1]) % 4)
return json.loads(base64.urlsafe_b64decode(parts[1] + pad))
def expired_from_access_token(access_token: str) -> tuple[str, int, str]:
"""Return (expired_rfc3339_z, expires_in, sub)."""
pl = jwt_payload(access_token)
exp = int(pl["exp"])
iat = int(pl["iat"]) if pl.get("iat") is not None else exp - 21600
expired = datetime.fromtimestamp(exp, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
sub = str(pl.get("sub") or pl.get("principal_id") or "").strip()
return expired, max(exp - iat, 0), sub
def build_cpa_xai_auth(
*,
email: str,
access_token: str,
refresh_token: str,
sub: str | None = None,
id_token: str | None = None,
expires_in: int | None = None,
expired: str | None = None,
last_refresh: str | None = None,
base_url: str = DEFAULT_BASE_URL,
token_endpoint: str = DEFAULT_TOKEN_ENDPOINT,
redirect_uri: str = DEFAULT_REDIRECT_URI,
headers: dict[str, str] | None = None,
disabled: bool = False,
priority: int = 1000,
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Build a CPA-importable xAI OAuth auth object."""
access_token = (access_token or "").strip()
refresh_token = (refresh_token or "").strip()
if not access_token:
raise ValueError("access_token is required")
if not refresh_token:
raise ValueError("refresh_token is required (CPA cannot renew without it)")
try:
exp_s, exp_in, sub_jwt = expired_from_access_token(access_token)
except Exception:
exp_s, exp_in, sub_jwt = "", 21600, ""
if not expired:
expired = exp_s
if expires_in is None:
expires_in = exp_in or 21600
if not sub:
sub = sub_jwt
if not last_refresh:
last_refresh = datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
# Free promo must hit cli-chat-proxy; refuse silent api.x.ai default for free path.
base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
if not re.search(r"/v1$", base_url):
# CPA joins baseURL + "/responses"
if base_url.endswith("cli-chat-proxy.grok.com"):
base_url = base_url + "/v1"
payload: dict[str, Any] = {
"type": "xai",
"auth_kind": "oauth",
"access_token": access_token,
"refresh_token": refresh_token,
"token_type": "Bearer",
"expires_in": int(expires_in),
"expired": expired,
"last_refresh": last_refresh,
"email": (email or "").strip(),
"sub": (sub or "").strip(),
"base_url": base_url,
"token_endpoint": token_endpoint,
"redirect_uri": redirect_uri,
"disabled": bool(disabled),
"priority": int(priority),
"headers": dict(headers or DEFAULT_CLIENT_HEADERS),
}
if id_token:
payload["id_token"] = id_token.strip()
if extra:
for k, v in extra.items():
if k not in payload:
payload[k] = v
return payload
+333
View File
@@ -0,0 +1,333 @@
"""Atomic write of CPA xAI auth files (mode 0600)."""
from __future__ import annotations
import json
import os
import tempfile
from pathlib import Path
from typing import Any
from .schema import credential_file_name
ENTITLEMENT_DENIED_LEDGER = "entitlement_denied.jsonl"
def write_cpa_xai_auth(
auth_dir: str | Path,
payload: dict[str, Any],
*,
filename: str | None = None,
) -> Path:
"""Write payload to auth_dir/xai-<email>.json atomically. Returns final path."""
auth_dir = Path(auth_dir).expanduser().resolve()
auth_dir.mkdir(parents=True, exist_ok=True)
if not filename:
filename = credential_file_name(
str(payload.get("email") or ""),
str(payload.get("sub") or ""),
)
if not filename.endswith(".json"):
filename = filename + ".json"
dest = auth_dir / filename
data = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
fd, tmp_name = tempfile.mkstemp(prefix=".xai-", suffix=".tmp", dir=str(auth_dir))
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
os.chmod(tmp_name, 0o600)
os.replace(tmp_name, dest)
os.chmod(dest, 0o600)
finally:
if os.path.exists(tmp_name):
try:
os.unlink(tmp_name)
except OSError:
pass
return dest
def patch_cpa_xai_auth(path: str | Path, updates: dict[str, Any]) -> dict[str, Any]:
"""Merge updates into an existing auth JSON file (atomic). Returns full payload."""
p = Path(path).expanduser().resolve()
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception:
data = {}
if not isinstance(data, dict):
data = {}
data.update(updates or {})
write_cpa_xai_auth(
p.parent,
data,
filename=p.name,
)
return data
def entitlement_denied_ledger_path(auth_dir: str | Path) -> Path:
return Path(auth_dir).expanduser().resolve() / ENTITLEMENT_DENIED_LEDGER
def load_entitlement_denied_emails(auth_dir: str | Path) -> set[str]:
"""Emails permanently without free Build chat (from ledger + stamped auth files)."""
root = Path(auth_dir).expanduser().resolve()
out: set[str] = set()
ledger = root / ENTITLEMENT_DENIED_LEDGER
if ledger.is_file():
try:
for line in ledger.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except Exception:
# plain email line
em = line.split("----", 1)[0].strip().lower()
if "@" in em:
out.add(em)
continue
if isinstance(rec, dict):
em = str(rec.get("email") or "").strip().lower()
if em:
out.add(em)
except Exception:
pass
for p in root.glob("xai-*.json"):
if "_selftest" in p.name:
continue
try:
d = json.loads(p.read_text(encoding="utf-8"))
except Exception:
continue
if not isinstance(d, dict):
continue
if is_entitlement_denied_auth(d):
em = str(d.get("email") or "").strip().lower()
if em:
out.add(em)
return out
def record_entitlement_denied(
auth_dir: str | Path,
email: str,
*,
extra: dict[str, Any] | None = None,
) -> Path:
"""Append one ledger line; idempotent for same email (still appends for audit)."""
from datetime import datetime, timezone
root = Path(auth_dir).expanduser().resolve()
root.mkdir(parents=True, exist_ok=True)
path = root / ENTITLEMENT_DENIED_LEDGER
rec = {
"email": (email or "").strip().lower(),
"ts": datetime.now(timezone.utc).isoformat(),
"reason": "entitlement_denied",
}
if extra:
for k, v in extra.items():
if k not in rec and v is not None:
rec[k] = v
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
try:
os.chmod(path, 0o600)
except OSError:
pass
return path
def is_entitlement_denied_auth(payload: dict[str, Any] | None) -> bool:
"""True when auth is known permanent free-Build chat denial (do not remint)."""
d = payload or {}
if d.get("entitlement_denied") is True:
return True
if d.get("fail_reason") == "entitlement_denied":
return True
if d.get("import_gate") == "entitlement_denied":
return True
return False
def is_chat_retryable_auth(payload: dict[str, Any] | None) -> bool:
"""True when local auth exists but chat probe was transient-failed (re-probe candidate)."""
d = payload or {}
if is_entitlement_denied_auth(d):
return False
if d.get("chat_ok") is True and d.get("usable") is not False:
return False
if d.get("chat_retryable") is True:
return True
if d.get("fail_reason") == "transient":
return True
return False
def build_chat_stamp_from_result(result: dict[str, Any] | None) -> dict[str, Any]:
"""Build auth-file stamp fields from a mint/export result dict.
Used by mint after probe and by export after finalize/gate so disk stamps
always match product chat_ok / entitlement classification.
Never writes ``chat_ok`` / ``usable`` as JSON null — omit those keys until a
real probe outcome exists (keeps inventory ``chat_ok_missing`` accurate).
"""
r = result or {}
chat_ok = r.get("chat_ok")
if chat_ok is None:
ch = r.get("probe_chat") or {}
if isinstance(ch, dict) and ch:
if "ok" in ch:
chat_ok = bool(ch.get("ok"))
elif ch.get("entitlement_denied"):
chat_ok = False
entitlement_denied = bool(r.get("entitlement_denied"))
if not entitlement_denied and isinstance(r.get("probe_chat"), dict):
entitlement_denied = bool((r.get("probe_chat") or {}).get("entitlement_denied"))
usable = r.get("usable")
if usable is None and chat_ok is True and not entitlement_denied:
usable = True
elif usable is None and (chat_ok is False or entitlement_denied):
usable = False
elif usable is None and r.get("ok") is True and chat_ok is None and not entitlement_denied:
# models-only success path without chat probe — do not invent usable=true
usable = None
chat_retryable = bool(r.get("chat_retryable")) and not entitlement_denied
if not chat_retryable and chat_ok is not True and not entitlement_denied:
ch = r.get("probe_chat") or {}
if isinstance(ch, dict) and ch.get("retryable") and not ch.get("ok"):
chat_retryable = True
fail_reason = str(r.get("fail_reason") or "").strip()
if not fail_reason and entitlement_denied:
fail_reason = "entitlement_denied"
if not fail_reason and isinstance(r.get("probe_chat"), dict):
pr = r.get("probe_chat") or {}
if pr.get("reason") and not pr.get("ok"):
fail_reason = str(pr.get("reason") or "")
chat_error_code = str(r.get("chat_error_code") or "").strip()
if not chat_error_code and isinstance(r.get("probe_chat"), dict):
chat_error_code = str((r.get("probe_chat") or {}).get("error_code") or "").strip()
if entitlement_denied:
import_gate = "entitlement_denied"
elif chat_ok is True and usable is not False:
import_gate = "chat_ok"
elif r.get("import_gate"):
import_gate = str(r.get("import_gate"))
elif chat_retryable:
import_gate = fail_reason or "transient"
elif chat_ok is False:
import_gate = fail_reason or "chat_not_ok"
else:
import_gate = fail_reason or ("ok" if r.get("ok") else "not_ready")
stamp: dict[str, Any] = {
"entitlement_denied": entitlement_denied,
"chat_retryable": chat_retryable and not entitlement_denied,
"import_gate": import_gate,
}
# Only persist booleans — never null (null pollutes inventory as "stamped").
if chat_ok is True or chat_ok is False:
stamp["chat_ok"] = bool(chat_ok)
if usable is True or usable is False:
stamp["usable"] = bool(usable)
if fail_reason:
stamp["fail_reason"] = fail_reason
if chat_error_code:
stamp["chat_error_code"] = chat_error_code
# Mint path observability (not product gates): which grant produced tokens.
# Dual stamp contract: mint.py writes mint_method/protocol_error at create
# (build_cpa_xai_auth extra=) and again after probe via stamp_auth_chat_fields
# so chat patches never drop residual-path labels (protocol_device, etc.).
mint_method = str(r.get("mint_method") or "").strip()
if mint_method:
stamp["mint_method"] = mint_method
protocol_error = str(r.get("protocol_error") or "").strip()
if protocol_error:
# Cap size so auth JSON stays ops-friendly when PKCE dumps long HTML errors.
stamp["protocol_error"] = protocol_error[:500]
return stamp
def stamp_auth_chat_fields(
path: str | Path,
result: dict[str, Any] | None = None,
*,
updates: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Merge chat stamp from result/updates into auth file. Returns full payload.
Omits null ``chat_ok``/``usable`` from the patch so incomplete results do not
mark historical files as stamped. Explicit ``updates`` may still set booleans
(including False); null values in updates are ignored for those keys.
"""
stamp = build_chat_stamp_from_result(result) if result is not None else {}
if updates:
for k, v in updates.items():
if k in ("chat_ok", "usable"):
if v is True or v is False:
stamp[k] = bool(v)
# skip None — never write null chat_ok/usable
continue
if v is not None:
stamp[k] = v
if not stamp:
return {}
return patch_cpa_xai_auth(path, stamp)
def inventory_chat_stamps(auth_dir: str | Path) -> dict[str, Any]:
"""Count chat stamp coverage in an auth dir (ops / backfill planning)."""
root = Path(auth_dir).expanduser().resolve()
stats = {
"total": 0,
"chat_ok_true": 0,
"chat_ok_false": 0,
"chat_ok_missing": 0,
"entitlement_denied": 0,
"chat_retryable": 0,
"usable_true": 0,
"usable_false": 0,
"import_gate": {},
}
for p in root.glob("xai-*.json"):
if "_selftest" in p.name:
continue
try:
d = json.loads(p.read_text(encoding="utf-8"))
except Exception:
continue
if not isinstance(d, dict):
continue
stats["total"] += 1
if "chat_ok" not in d:
stats["chat_ok_missing"] += 1
elif d.get("chat_ok") is True:
stats["chat_ok_true"] += 1
else:
stats["chat_ok_false"] += 1
if is_entitlement_denied_auth(d):
stats["entitlement_denied"] += 1
if is_chat_retryable_auth(d):
stats["chat_retryable"] += 1
if d.get("usable") is True:
stats["usable_true"] += 1
elif d.get("usable") is False:
stats["usable_false"] += 1
gate = str(d.get("import_gate") or ("missing" if "chat_ok" not in d else "unset"))
stats["import_gate"][gate] = int(stats["import_gate"].get(gate, 0)) + 1
return stats