Add files via upload
This commit is contained in:
1 parent
b85a53e334
commit
4a169ac39c
8 files changed
+2364
-2
No files matched your search
@@ -0,0 +1,81 @@
|
||||
"""PKCE OAuth 客户端 - 用于获取 ChatGPT access_token / refresh_token"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import base64
|
||||
import secrets
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from curl_cffi import requests as cffi_requests
|
||||
|
||||
# ── PKCE / Codex OAuth 配置 ──
|
||||
CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
|
||||
REDIRECT_URI = "http://localhost:1455/auth/callback"
|
||||
AUTH_BASE = "https://auth.openai.com"
|
||||
TOKEN_URL = f"{AUTH_BASE}/oauth/token"
|
||||
AUTHORIZE_URL = f"{AUTH_BASE}/oauth/authorize"
|
||||
SCOPE = "openid email profile offline_access"
|
||||
AUDIENCE = "https://api.openai.com/v1"
|
||||
|
||||
|
||||
def generate_pkce() -> dict:
|
||||
"""生成 PKCE code_verifier + code_challenge"""
|
||||
verifier = secrets.token_urlsafe(32)
|
||||
digest = hashlib.sha256(verifier.encode()).digest()
|
||||
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
|
||||
return {"code_verifier": verifier, "code_challenge": challenge}
|
||||
|
||||
|
||||
def build_authorize_url(pkce: dict, state: str | None = None) -> str:
|
||||
"""构建 /oauth/authorize URL"""
|
||||
if state is None:
|
||||
state = secrets.token_urlsafe(24)
|
||||
params = {
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"response_type": "code",
|
||||
"scope": SCOPE,
|
||||
"audience": AUDIENCE,
|
||||
"code_challenge": pkce["code_challenge"],
|
||||
"code_challenge_method": "S256",
|
||||
"state": state,
|
||||
}
|
||||
return f"{AUTHORIZE_URL}?{urlencode(params)}"
|
||||
|
||||
|
||||
def exchange_code(code: str, code_verifier: str, proxy: str | None = None) -> dict:
|
||||
"""用 authorization code 换取 access_token + refresh_token"""
|
||||
payload = {
|
||||
"grant_type": "authorization_code",
|
||||
"client_id": CLIENT_ID,
|
||||
"code": code,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"code_verifier": code_verifier,
|
||||
}
|
||||
r = cffi_requests.post(
|
||||
TOKEN_URL,
|
||||
json=payload,
|
||||
impersonate="chrome136",
|
||||
proxy=proxy,
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
|
||||
|
||||
def refresh(refresh_token: str, proxy: str | None = None) -> dict:
|
||||
"""用 refresh_token 刷新 access_token"""
|
||||
payload = {
|
||||
"grant_type": "refresh_token",
|
||||
"client_id": CLIENT_ID,
|
||||
"refresh_token": refresh_token,
|
||||
}
|
||||
r = cffi_requests.post(
|
||||
TOKEN_URL,
|
||||
json=payload,
|
||||
impersonate="chrome136",
|
||||
proxy=proxy,
|
||||
timeout=30,
|
||||
)
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
Reference in new issue
Block a user