|
| 1 | +import base64 |
| 2 | +import hashlib |
| 3 | +import json |
| 4 | +import secrets |
| 5 | +from datetime import UTC, datetime, timedelta |
| 6 | +from typing import Any |
| 7 | +from urllib.parse import parse_qs, urlencode, urlparse |
| 8 | + |
| 9 | +import httpx |
| 10 | + |
| 11 | +OPENAI_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann" |
| 12 | +OPENAI_OAUTH_AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize" |
| 13 | +OPENAI_OAUTH_TOKEN_URL = "https://auth.openai.com/oauth/token" |
| 14 | +OPENAI_OAUTH_REDIRECT_URI = "http://localhost:1455/auth/callback" |
| 15 | +OPENAI_OAUTH_SCOPE = "openid profile email offline_access" |
| 16 | +OPENAI_OAUTH_TIMEOUT = 20.0 |
| 17 | +OPENAI_OAUTH_ACCOUNT_CLAIM_PATH = "https://api.openai.com/auth" |
| 18 | + |
| 19 | + |
| 20 | +def create_pkce_flow() -> dict[str, str]: |
| 21 | + state = secrets.token_hex(16) |
| 22 | + verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).decode().rstrip("=") |
| 23 | + challenge = base64.urlsafe_b64encode( |
| 24 | + hashlib.sha256(verifier.encode()).digest() |
| 25 | + ).decode().rstrip("=") |
| 26 | + return { |
| 27 | + "state": state, |
| 28 | + "verifier": verifier, |
| 29 | + "challenge": challenge, |
| 30 | + "authorize_url": build_authorize_url(state, challenge), |
| 31 | + } |
| 32 | + |
| 33 | + |
| 34 | +def build_authorize_url(state: str, challenge: str) -> str: |
| 35 | + query = urlencode( |
| 36 | + { |
| 37 | + "response_type": "code", |
| 38 | + "client_id": OPENAI_OAUTH_CLIENT_ID, |
| 39 | + "redirect_uri": OPENAI_OAUTH_REDIRECT_URI, |
| 40 | + "scope": OPENAI_OAUTH_SCOPE, |
| 41 | + "code_challenge": challenge, |
| 42 | + "code_challenge_method": "S256", |
| 43 | + "state": state, |
| 44 | + "id_token_add_organizations": "true", |
| 45 | + "codex_cli_simplified_flow": "true", |
| 46 | + "originator": "codex_cli_rs", |
| 47 | + } |
| 48 | + ) |
| 49 | + return f"{OPENAI_OAUTH_AUTHORIZE_URL}?{query}" |
| 50 | + |
| 51 | + |
| 52 | +def parse_authorization_input(raw: str) -> tuple[str, str]: |
| 53 | + value = (raw or "").strip() |
| 54 | + if not value: |
| 55 | + raise ValueError("empty input") |
| 56 | + if "#" in value: |
| 57 | + code, state = value.split("#", 1) |
| 58 | + return code.strip(), state.strip() |
| 59 | + if "code=" in value: |
| 60 | + parsed = urlparse(value) |
| 61 | + if parsed.query: |
| 62 | + query = parse_qs(parsed.query) |
| 63 | + return query.get("code", [""])[0].strip(), query.get("state", [""])[0].strip() |
| 64 | + query = parse_qs(value) |
| 65 | + return query.get("code", [""])[0].strip(), query.get("state", [""])[0].strip() |
| 66 | + return value, "" |
| 67 | + |
| 68 | + |
| 69 | +def parse_oauth_credential_json(raw: str) -> dict[str, Any] | None: |
| 70 | + value = (raw or "").strip() |
| 71 | + if not value.startswith("{"): |
| 72 | + return None |
| 73 | + try: |
| 74 | + data = json.loads(value) |
| 75 | + except Exception as exc: |
| 76 | + raise ValueError(f"OAuth JSON 凭据解析失败: {exc}") from exc |
| 77 | + if not isinstance(data, dict): |
| 78 | + raise ValueError("OAuth JSON 凭据必须是对象") |
| 79 | + access_token = str(data.get("access_token") or "").strip() |
| 80 | + if not access_token: |
| 81 | + raise ValueError("OAuth JSON 凭据缺少 access_token") |
| 82 | + refresh_token = str(data.get("refresh_token") or "").strip() |
| 83 | + expires_at = _normalize_expires_at( |
| 84 | + data.get("expired") or data.get("expires_at") or data.get("expires"), |
| 85 | + ) |
| 86 | + account_id = str(data.get("account_id") or "").strip() or extract_account_id_from_jwt(access_token) |
| 87 | + email = str(data.get("email") or "").strip() or extract_email_from_jwt(access_token) |
| 88 | + return { |
| 89 | + "access_token": access_token, |
| 90 | + "refresh_token": refresh_token, |
| 91 | + "expires_at": expires_at, |
| 92 | + "email": email, |
| 93 | + "account_id": account_id, |
| 94 | + "raw": data, |
| 95 | + } |
| 96 | + |
| 97 | + |
| 98 | +async def exchange_authorization_code( |
| 99 | + code: str, |
| 100 | + verifier: str, |
| 101 | + proxy_url: str = "", |
| 102 | +) -> dict[str, Any]: |
| 103 | + payload = { |
| 104 | + "grant_type": "authorization_code", |
| 105 | + "client_id": OPENAI_OAUTH_CLIENT_ID, |
| 106 | + "code": code.strip(), |
| 107 | + "code_verifier": verifier.strip(), |
| 108 | + "redirect_uri": OPENAI_OAUTH_REDIRECT_URI, |
| 109 | + } |
| 110 | + return await _request_token(payload, proxy_url) |
| 111 | + |
| 112 | + |
| 113 | +async def refresh_access_token( |
| 114 | + refresh_token: str, |
| 115 | + proxy_url: str = "", |
| 116 | +) -> dict[str, Any]: |
| 117 | + payload = { |
| 118 | + "grant_type": "refresh_token", |
| 119 | + "client_id": OPENAI_OAUTH_CLIENT_ID, |
| 120 | + "refresh_token": refresh_token.strip(), |
| 121 | + } |
| 122 | + return await _request_token(payload, proxy_url) |
| 123 | + |
| 124 | + |
| 125 | +async def _request_token(payload: dict[str, str], proxy_url: str = "") -> dict[str, Any]: |
| 126 | + async with httpx.AsyncClient(proxy=proxy_url or None, timeout=OPENAI_OAUTH_TIMEOUT) as client: |
| 127 | + response = await client.post( |
| 128 | + OPENAI_OAUTH_TOKEN_URL, |
| 129 | + data=payload, |
| 130 | + headers={ |
| 131 | + "Accept": "application/json", |
| 132 | + "Content-Type": "application/x-www-form-urlencoded", |
| 133 | + }, |
| 134 | + ) |
| 135 | + data = response.json() |
| 136 | + if response.status_code < 200 or response.status_code >= 300: |
| 137 | + raise ValueError(f"oauth token request failed: status={response.status_code}, body={data}") |
| 138 | + access_token = (data.get("access_token") or "").strip() |
| 139 | + refresh_token = (data.get("refresh_token") or "").strip() |
| 140 | + expires_in = int(data.get("expires_in") or 0) |
| 141 | + if not access_token or not refresh_token or expires_in <= 0: |
| 142 | + raise ValueError("oauth token response missing required fields") |
| 143 | + expires_at = datetime.now(UTC) + timedelta(seconds=expires_in) |
| 144 | + return { |
| 145 | + "access_token": access_token, |
| 146 | + "refresh_token": refresh_token, |
| 147 | + "expires_at": expires_at.isoformat(), |
| 148 | + "email": extract_email_from_jwt(access_token), |
| 149 | + "account_id": extract_account_id_from_jwt(access_token), |
| 150 | + "raw": data, |
| 151 | + } |
| 152 | + |
| 153 | + |
| 154 | +def extract_email_from_jwt(token: str) -> str: |
| 155 | + claims = decode_jwt_claims(token) |
| 156 | + email = claims.get("email") |
| 157 | + return email.strip() if isinstance(email, str) else "" |
| 158 | + |
| 159 | + |
| 160 | +def extract_account_id_from_jwt(token: str) -> str: |
| 161 | + claims = decode_jwt_claims(token) |
| 162 | + raw = claims.get(OPENAI_OAUTH_ACCOUNT_CLAIM_PATH) |
| 163 | + if not isinstance(raw, dict): |
| 164 | + return "" |
| 165 | + account_id = raw.get("chatgpt_account_id") |
| 166 | + return account_id.strip() if isinstance(account_id, str) else "" |
| 167 | + |
| 168 | + |
| 169 | +def decode_jwt_claims(token: str) -> dict[str, Any]: |
| 170 | + parts = token.split(".") |
| 171 | + if len(parts) < 2: |
| 172 | + return {} |
| 173 | + payload = parts[1] |
| 174 | + padding = "=" * (-len(payload) % 4) |
| 175 | + try: |
| 176 | + decoded = base64.urlsafe_b64decode(payload + padding) |
| 177 | + obj = json.loads(decoded.decode()) |
| 178 | + return obj if isinstance(obj, dict) else {} |
| 179 | + except Exception: |
| 180 | + return {} |
| 181 | + |
| 182 | + |
| 183 | +def _normalize_expires_at(value: Any) -> str: |
| 184 | + if value is None: |
| 185 | + return "" |
| 186 | + if isinstance(value, (int, float)): |
| 187 | + try: |
| 188 | + return datetime.fromtimestamp(float(value), UTC).isoformat() |
| 189 | + except Exception: |
| 190 | + return "" |
| 191 | + if isinstance(value, str): |
| 192 | + stripped = value.strip() |
| 193 | + if not stripped: |
| 194 | + return "" |
| 195 | + try: |
| 196 | + if stripped.endswith("Z"): |
| 197 | + stripped = stripped[:-1] + "+00:00" |
| 198 | + return datetime.fromisoformat(stripped).isoformat() |
| 199 | + except Exception: |
| 200 | + return value.strip() |
| 201 | + return "" |
0 commit comments