opllplus / card_bind_session.py
axm0121's picture
Deploy Flask protocol card binding Space
3ec0f02 verified
Raw History Blame Contribute Delete
8.1 kB
from __future__ import annotations
import json, sys, random, re, base64, hashlib, uuid, os
from curl_ca_bundle import curl_session_kwargs, is_ca_bundle_error
try:
from requests import Session as RequestsSession
except ImportError:
RequestsSession=None
try:
from curl_cffi.requests import Session as CurlSession
CURL_CFFI_AVAILABLE=True
except ImportError:
CurlSession=None
CURL_CFFI_AVAILABLE=False
ACCOUNT_FILE=os.getenv("ACCOUNT_FILE", "./data/accounts.jsonl")
PK_RE=re.compile(r"pk_(?:live|test)_[A-Za-z0-9]{24,}")
def find_publishable_key(value):
if isinstance(value,dict):
for key in ("publishable_key","public_key","stripe_publishable_key","key"):
candidate=str(value.get(key) or "").strip()
if PK_RE.fullmatch(candidate): return candidate
for item in value.values():
found=find_publishable_key(item)
if found:return found
elif isinstance(value,list):
for item in value:
found=find_publishable_key(item)
if found:return found
elif isinstance(value,str):
match=PK_RE.search(value)
if match:return match.group(0)
return ""
UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"
def auto_us_billing(email):
try:
sys.path.insert(0,"/opt/paypal-pay")
from paypal import models
try:
address=models._generate_address_from_online_map("US")
except Exception:
address=None
if not address:
address=models.generate_address("US")
line1=" ".join(x for x in [str(address.house_number or ""),str(address.street or "")] if x).strip()
line2=str(address.district or "")
city=str(address.city or "")
state=str(address.state or "")
postal_code=str(address.postal_code or "")
except Exception:
line1="1600 Pennsylvania Avenue NW"
line2=""
city="Washington"
state="DC"
postal_code="20500"
names=["James Wilson","Michael Brown","Daniel Miller","David Anderson","Robert Taylor","William Thomas"]
return {
"name":random.choice(names),
"email":str(email or ""),
"phone":"+1202555%04d" % random.randint(100,9999),
"address":{
"country":"US",
"line1":line1,
"line2":line2,
"city":city,
"state":state,
"postal_code":postal_code,
}
}
def helper_error_payload(exc):
detail=re.sub(r"(?i)((?:https?|socks5h?)://)[^/@\s]+@",r"\1***@",f"{type(exc).__name__}: {exc}")[:300]
lowered=detail.lower()
if is_ca_bundle_error(exc):
error="CARD_BIND_TLS_CA_BUNDLE_ERROR"
elif isinstance(exc,ModuleNotFoundError):
error="CARD_BIND_DEPENDENCY_MISSING"
elif isinstance(exc,FileNotFoundError):
error="CARD_BIND_RUNTIME_FILE_MISSING"
elif any(marker in lowered for marker in ("curl:","could not connect","connectionerror","proxyerror","timed out","timeout","tls","ssl")):
error="CARD_BIND_UPSTREAM_NETWORK_ERROR"
elif "missing dependencies" in lowered or "socks support" in lowered:
error="CARD_BIND_DEPENDENCY_MISSING"
else:
error="CARD_BIND_HELPER_ERROR"
return {"ok":False,"error":error,"detail":detail}
def proxy_variants(proxy):
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
def request_payment_method(account,proxy,cookies,headers):
candidates=[]
if CURL_CFFI_AVAILABLE:
candidates.extend([
("curl_firefox144",lambda:CurlSession(impersonate="firefox144",**curl_session_kwargs())),
("curl_chrome146",lambda:CurlSession(impersonate="chrome146",**curl_session_kwargs())),
])
if RequestsSession is not None:
candidates.append(("requests_openssl",RequestsSession))
if not candidates:
raise ModuleNotFoundError("Neither curl_cffi nor requests is installed")
failures=[];last_detail=""
for candidate_proxy in proxy_variants(proxy):
dns_mode="remote_dns" if candidate_proxy.lower().startswith("socks5h://") else "local_dns" if candidate_proxy.lower().startswith("socks5://") else "default"
for transport,factory in candidates:
label=transport if dns_mode=="default" else f"{transport}_{dns_mode}"
http=factory();http.trust_env=False
if candidate_proxy and candidate_proxy.upper()!="DIRECT":http.proxies={"http":candidate_proxy,"https":candidate_proxy}
for name,value in dict(cookies).items():
try:http.cookies.set(str(name),str(value),domain="chatgpt.com")
except:pass
try:
response=http.post("https://chatgpt.com/backend-api/payments/payment_method",json={"account_id":account.get("account_id")},headers=headers,timeout=45)
return response,label
except Exception as exc:
failure=helper_error_payload(exc)
if failure["error"]!="CARD_BIND_UPSTREAM_NETWORK_ERROR":raise
failures.append(f"{label}={type(exc).__name__}")
last_detail=failure["detail"]
finally:http.close()
raise RuntimeError("TRANSPORT_FALLBACK_EXHAUSTED: "+"; ".join(failures)+"; last="+last_detail)
def main():
email=str(sys.argv[1] if len(sys.argv)>1 else "").strip().lower(); account=None
access_token_override=str(sys.argv[3] if len(sys.argv)>3 else "").strip()
email_candidate=None
if os.path.isfile(ACCOUNT_FILE):
with open(ACCOUNT_FILE,encoding="utf-8",errors="ignore") as h:
for line in h:
try:item=json.loads(line)
except:continue
if access_token_override and str(item.get("access_token") or "").strip()==access_token_override:
account=item
break
if str(item.get("email") or "").strip().lower()==email:
email_candidate=item
if not account and 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=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();record_id=hashlib.sha256(("external-at:"+account_id).encode()).hexdigest()[:12];device_id=str(uuid.uuid5(uuid.NAMESPACE_URL,"reg153-external-at:"+account_id));account={"id":record_id,"email":decoded_email,"account_id":account_id,"access_token":access_token_override,"session_cookies":{"oai-did":device_id},"proxy":"DIRECT"}
except Exception:
account=None
if not account: account=email_candidate
if not account: print(json.dumps({"ok":False,"error":"ACCOUNT_NOT_FOUND"})); return 2
if access_token_override:
account=dict(account);account["access_token"]=access_token_override
proxy=str(sys.argv[2] if len(sys.argv)>2 else account.get("proxy") or "").strip()
cookies=account.get("session_cookies") or {}
if isinstance(cookies,str):
try:cookies=json.loads(cookies)
except:cookies={}
headers={"Authorization":"Bearer "+str(account.get("access_token") or ""),"ChatGPT-Account-Id":str(account.get("account_id") or ""),"OAI-Device-Id":str(cookies.get("oai-did") or ""),"User-Agent":UA,"Accept":"*/*","Origin":"https://chatgpt.com","Referer":"https://chatgpt.com/","Content-Type":"application/json"}
response,transport=request_payment_method(account,proxy,cookies,headers)
try:data=response.json() or {}
except:data={}
secret=str(data.get("client_secret") or "")
if response.status_code!=200 or not secret.startswith("seti_"):
detail=data.get("detail") or data.get("error") or ""
print(json.dumps({"ok":False,"error":"SETUP_INTENT_FAILED","status":response.status_code,"detail":str(detail)[:300],"transport":transport})); return 3
billing=auto_us_billing(email)
print(json.dumps({"ok":True,"client_secret":secret,"publishable_key":find_publishable_key(data),"record_id":str(account.get("id") or ""),"account_email":email,"billing_details":billing,"transport":transport})); return 0
if __name__=="__main__":
try:
raise SystemExit(main())
except SystemExit:
raise
except Exception as exc:
print(json.dumps(helper_error_payload(exc)))
raise SystemExit(10)