from __future__ import annotations import json import os import re import sys import time import base64 import hashlib import uuid from typing import Any from curl_ca_bundle import curl_session_kwargs, is_ca_bundle_error try: from curl_cffi.requests import Session except ImportError: # pragma: no cover - dependency is declared in requirements.txt Session = None # type: ignore[assignment] ACCOUNT_FILE = "/opt/reg153/success_accounts.jsonl" UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0" SET_DEFAULT_PROXY_REUSE_ATTEMPTS = max( 1, min( 10, int( os.getenv("SET_DEFAULT_PROXY_REUSE_ATTEMPTS") or os.getenv("CARD_BIND_PROXY_REUSE_ATTEMPTS") or "3" ), ), ) SET_DEFAULT_REQUEST_TIMEOUT = max( 5, min(60, int(os.getenv("SET_DEFAULT_REQUEST_TIMEOUT", "25"))) ) class UpstreamResponseError(RuntimeError): def __init__(self, error: str, status: int, detail: str = "") -> None: super().__init__(detail or f"HTTP {status}") self.error = error self.status = status self.detail = detail def safe_detail(value: object) -> str: text = str(value or "") text = re.sub(r"(?i)((?:https?|socks5h?)://)[^/@\s]+@", r"\1***@", text) text = re.sub( r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", "AT_REDACTED", text, ) return text[:500] def retryable_transport_error(exc: Exception) -> bool: if is_ca_bundle_error(exc): return False detail = f"{type(exc).__name__}: {exc}".lower() return any( marker in detail for marker in ( "connectionerror", "connecterror", "could not connect", "failed to connect", "connection closed", "connection reset", "proxyerror", "timeout", "timed out", "ssl", "tls", "curl: (7)", "curl: (28)", "curl: (35)", "curl: (52)", "curl: (55)", "curl: (56)", ) ) def helper_error_payload(exc: Exception) -> dict[str, Any]: if isinstance(exc, UpstreamResponseError): return { "ok": False, "error": exc.error, "status": exc.status, "detail": safe_detail(exc.detail), } detail = safe_detail(f"{type(exc).__name__}: {exc}") lowered = detail.lower() if is_ca_bundle_error(exc): error = "SET_DEFAULT_TLS_CA_BUNDLE_ERROR" elif isinstance(exc, ModuleNotFoundError): error = "SET_DEFAULT_DEPENDENCY_MISSING" elif retryable_transport_error(exc) or "proxy_retry_exhausted" in lowered: error = "SET_DEFAULT_UPSTREAM_NETWORK_ERROR" else: error = "SET_DEFAULT_HELPER_ERROR" return {"ok": False, "error": error, "detail": detail} def proxy_variants(proxy: str) -> list[str]: value = str(proxy or "").strip() variants = [value] lowered = value.lower() if lowered.startswith("socks5h://"): variants.append("socks5://" + value[len("socks5h://") :]) elif lowered.startswith("socks5://"): variants.append("socks5h://" + value[len("socks5://") :]) return variants class RotatingDefaultSession: def __init__( self, proxy: str, cookies: dict, *, retry_attempts: int = SET_DEFAULT_PROXY_REUSE_ATTEMPTS, retry_delay: float = 0.5, ) -> None: self.proxy = str(proxy or "").strip() self.cookies = dict(cookies or {}) self.retry_attempts = max(1, min(10, int(retry_attempts))) self.retry_delay = max(0.0, min(5.0, float(retry_delay))) def _open(self, proxy: str): if Session is None: raise ModuleNotFoundError("curl_cffi is not installed") http = Session(impersonate="firefox144", **curl_session_kwargs()) http.trust_env = False if proxy and proxy.upper() != "DIRECT": http.proxies = {"http": proxy, "https": proxy} for name, value in self.cookies.items(): try: http.cookies.set(str(name), str(value), domain="chatgpt.com") except Exception: pass return http def request(self, method: str, url: str, **kwargs: Any): failures: list[str] = [] last_error: Exception | None = None variants = proxy_variants(self.proxy) for attempt in range(1, self.retry_attempts + 1): for candidate_proxy in variants: http = None dns_mode = ( "remote_dns" if candidate_proxy.lower().startswith("socks5h://") else "local_dns" if candidate_proxy.lower().startswith("socks5://") else "default" ) try: http = self._open(candidate_proxy) response = getattr(http, method)(url, **kwargs) return response, f"curl_firefox144_{dns_mode}_round_{attempt}" except Exception as exc: if is_ca_bundle_error(exc): raise RuntimeError( f"SET_DEFAULT_TLS_CA_BUNDLE_ERROR: {safe_detail(exc)}" ) from exc if not retryable_transport_error(exc): raise last_error = exc failures.append( f"round_{attempt}_{dns_mode}={type(exc).__name__}" ) finally: try: if http is not None: http.close() except Exception: pass if attempt < self.retry_attempts and self.retry_delay: time.sleep(self.retry_delay) assert last_error is not None raise RuntimeError( "SET_DEFAULT_PROXY_RETRY_EXHAUSTED: " f"{self.retry_attempts} fresh connection round(s); " + "; ".join(failures) + f"; last={safe_detail(f'{type(last_error).__name__}: {last_error}')}" ) from last_error def get(self, url: str, **kwargs: Any): return self.request("get", url, **kwargs) def post(self, url: str, **kwargs: Any): return self.request("post", url, **kwargs) def response_detail(response: object) -> str: try: payload = response.json() except Exception: return safe_detail(getattr(response, "text", "")) if isinstance(payload, dict): value = payload.get("detail") or payload.get("message") or payload.get("error") if isinstance(value, dict): value = value.get("message") or value.get("code") or value return safe_detail(value) return safe_detail(payload) def load_account(email: str): match = None with open(ACCOUNT_FILE, encoding="utf-8", errors="ignore") as handle: for line in handle: try: item = json.loads(line) except Exception: continue if str(item.get("email") or "").strip().lower() == email: match = item return match def list_payment_method_ids( http: RotatingDefaultSession, headers: dict, account_id: str ) -> tuple[set[str], str]: response, transport = http.get( "https://chatgpt.com/backend-api/payments/payment_methods", params={"account_id": account_id}, headers=headers, timeout=SET_DEFAULT_REQUEST_TIMEOUT, ) if response.status_code != 200: raise UpstreamResponseError( "PAYMENT_METHOD_LOOKUP_FAILED", response.status_code, response_detail(response), ) try: payload = response.json() except Exception as exc: raise RuntimeError("PAYMENT_METHOD_LOOKUP_INVALID_RESPONSE") from exc if isinstance(payload, list): items = payload elif isinstance(payload, dict): items = payload.get("data") or payload.get("payment_methods") or [] else: items = [] return ( {str(item.get("id") or "") for item in items if isinstance(item, dict)}, transport, ) def main() -> int: email = str(sys.argv[1] if len(sys.argv) > 1 else "").strip().lower() payment_method_id = str(sys.argv[2] if len(sys.argv) > 2 else "").strip() if not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id): print(json.dumps({"ok": False, "error": "INVALID_PAYMENT_METHOD"})) return 2 access_token_override = str(sys.argv[4] if len(sys.argv) > 4 else "").strip() account = None if access_token_override else load_account(email) if access_token_override: try: segment = access_token_override.split(".")[1] segment += "=" * (-len(segment) % 4) claims = json.loads(base64.urlsafe_b64decode(segment.encode()).decode()) auth = claims.get("https://api.openai.com/auth") or {} profile = claims.get("https://api.openai.com/profile") or {} account_id_value = str(auth.get("chatgpt_account_id") or claims.get("account_id") or "").strip() token_hash = hashlib.sha256(access_token_override.encode()).hexdigest() decoded_email = str(profile.get("email") or claims.get("email") or email or f"external-{token_hash[:16]}@example.com").strip().lower() device_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "reg153-external-at:" + account_id_value)) account = {"email": decoded_email, "account_id": account_id_value, "access_token": access_token_override, "session_cookies": {"oai-did": device_id}, "proxy": "DIRECT"} except Exception: account = None if not account: print(json.dumps({"ok": False, "error": "ACCOUNT_NOT_FOUND"})) return 3 if access_token_override: account = dict(account) account["access_token"] = access_token_override account_id = str(account.get("account_id") or "") access_token = str(account.get("access_token") or "") if not account_id or not access_token: print(json.dumps({"ok": False, "error": "ACCOUNT_SESSION_INCOMPLETE"})) return 4 proxy = str(sys.argv[3] if len(sys.argv) > 3 else account.get("proxy") or "").strip() cookies = account.get("session_cookies") or {} if isinstance(cookies, str): try: cookies = json.loads(cookies) except Exception: cookies = {} headers = { "Authorization": "Bearer " + access_token, "ChatGPT-Account-Id": account_id, "OAI-Device-Id": str(cookies.get("oai-did") or ""), "User-Agent": UA, "Accept": "application/json", "Origin": "https://chatgpt.com", "Referer": "https://chatgpt.com/", "Content-Type": "application/json", } http = RotatingDefaultSession(proxy, dict(cookies)) response, set_transport = http.post( "https://chatgpt.com/backend-api/payments/payment_method/default", json={"account_id": account_id, "payment_method_id": payment_method_id}, headers=headers, timeout=SET_DEFAULT_REQUEST_TIMEOUT, ) if response.status_code not in (200, 204): print( json.dumps( { "ok": False, "error": "SET_DEFAULT_FAILED", "status": response.status_code, "detail": response_detail(response), "transport": set_transport, }, ensure_ascii=True, ) ) return 5 # Wait until the default endpoint's attachment is visible before Checkout. last_transport = set_transport for attempt in range(1, 13): payment_method_ids, last_transport = list_payment_method_ids( http, headers, account_id ) if payment_method_id in payment_method_ids: print( json.dumps( { "ok": True, "attached": True, "attempt": attempt, "transport": last_transport, }, ensure_ascii=True, ) ) return 0 time.sleep(1.0) print( json.dumps( { "ok": False, "error": "PAYMENT_METHOD_NOT_ATTACHED", "transport": last_transport, }, ensure_ascii=True, ) ) return 6 if __name__ == "__main__": try: raise SystemExit(main()) except SystemExit: raise except Exception as exc: print(json.dumps(helper_error_payload(exc), ensure_ascii=True)) raise SystemExit(10)