axm0121 commited on
Commit
3ec0f02
·
verified ·
1 Parent(s): ad8fe46

Deploy Flask protocol card binding Space

Browse files

Replace the previous Space contents with the staged Flask/Gunicorn deployment. The parent revision is pinned to the recorded pre-deploy baseline.

.dockerignore CHANGED
@@ -1,11 +1,12 @@
1
- .git
2
- .gitignore
3
- .venv
4
- __pycache__
5
- *.py[cod]
6
- artifacts
7
- tests
8
- task_plan.md
9
- findings.md
10
- progress.md
11
- fingerprint_profiles.json*
 
 
1
+ .env
2
+ .env.*
3
+ !.env.example
4
+ .git
5
+ .git/**
6
+ __pycache__
7
+ **/__pycache__
8
+ *.py[cod]
9
+ .pytest_cache
10
+ .artifacts
11
+ artifacts
12
+ tests
.env.example ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Fill on deployment host
2
+ PH_SHORT_BRIDGE_KEY=REPLACE_ME
3
+ # Must match the key configured by the local PAY153 bridge at PAY153_INTERNAL_BASE.
4
+ PAY153_INTERNAL_KEY=REPLACE_ME
5
+ PAY153_INTERNAL_BASE=http://127.0.0.1:18096
6
+ CARD_BIND_PUBLISHABLE_KEY=REPLACE_WITH_STRIPE_PUBLISHABLE_KEY
7
+ # Fresh connections to retry for each reusable rotating proxy endpoint (1-10).
8
+ CARD_BIND_PROXY_REUSE_ATTEMPTS=3
9
+ # Fresh Stripe connections for the same reusable rotating proxy endpoint (1-10).
10
+ STRIPE_PROXY_REUSE_ATTEMPTS=3
11
+ # Fresh connections for setting and verifying the default payment method (1-10).
12
+ SET_DEFAULT_PROXY_REUSE_ATTEMPTS=3
13
+ # Per-request network timeout and total helper timeout in seconds.
14
+ SET_DEFAULT_REQUEST_TIMEOUT=25
15
+ SET_DEFAULT_HELPER_TIMEOUT_SECONDS=360
16
+ # Maximum number of final payments released in one simultaneous batch (1-200).
17
+ PH_PORTAL_MAX_BATCH_CONCURRENCY=200
18
+ # Post-payment Plus verification retries and delay between checks.
19
+ PLUS_VERIFY_ATTEMPTS=15
20
+ PLUS_VERIFY_DELAY_SECONDS=2
21
+ # Optional ASCII-only directory for the native curl CA bundle cache on Windows.
22
+ CURL_CA_ASCII_DIR=
23
+ REG_CONSOLE_BASE=http://127.0.0.1:18081
24
+ ACCOUNT_FILE=./data/accounts.jsonl
25
+ FLASK_SECRET_KEY=REPLACE_ME
Dockerfile CHANGED
@@ -1,16 +1,14 @@
1
- FROM python:3.11-slim
2
-
3
- ENV PYTHONDONTWRITEBYTECODE=1 \
4
- PYTHONUNBUFFERED=1 \
5
- HOST=0.0.0.0 \
6
- PORT=7860
7
-
8
- WORKDIR /app
9
-
10
- COPY requirements.txt ./
11
- RUN pip install --no-cache-dir -r requirements.txt
12
-
13
- COPY . ./
14
-
15
- EXPOSE 7860
16
- CMD ["python", "serve_direct.py"]
 
1
+ FROM python:3.12-slim
2
+
3
+ ENV PYTHONDONTWRITEBYTECODE=1
4
+ ENV PYTHONUNBUFFERED=1
5
+ ENV PORT=7860
6
+
7
+ WORKDIR /app
8
+ COPY requirements.txt ./
9
+ RUN python -m pip install --no-cache-dir --upgrade pip \
10
+ && python -m pip install --no-cache-dir -r requirements.txt
11
+ COPY . ./
12
+
13
+ EXPOSE 7860
14
+ CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--workers", "1", "--threads", "8", "--timeout", "120", "app:app"]
 
 
README.md CHANGED
@@ -1,75 +1,46 @@
1
- ---
2
- title: Standalone Direct Bind
3
- colorFrom: blue
4
- colorTo: green
5
- sdk: docker
6
- app_port: 7860
7
- pinned: false
8
- ---
9
-
10
- <img width="2436" height="1281" alt="image" src="https://github.com/user-attachments/assets/5b08cc03-af0c-4269-9ffa-b39a82747f03" />
11
- # 直绑独立服务
12
-
13
- 该目录是独立的 5601 服务:
14
-
15
- - 不读取外部项目数据库
16
- - 不导入外部项目目录
17
- - 自带 HTTP 核心、配置、静态页面和测试
18
- - 首次启动自动创建本地 `.venv`
19
-
20
- ## 启动
21
-
22
- 前台启动:
23
-
24
- ```bat
25
- start_standalone.cmd
26
- ```
27
-
28
- 后台启动:
29
-
30
- ```bat
31
- run_direct.vbs
32
- ```
33
-
34
- 重启:
35
-
36
- ```bat
37
- restart_standalone.cmd
38
- ```
39
-
40
- 页面:`http://127.0.0.1:5601/`
41
-
42
- ## 配置
43
-
44
- 编辑 `standalone_config.json`:
45
-
46
- - `country` / `currency`:提链区域与币种
47
- - `bind_country` / `bind_currency`:绑卡区域与币种
48
- - `promo_campaign`:优惠活动
49
- - `timeout`:HTTP 任务超时
50
- - `billing`:账单资料默认值
51
-
52
- 服务端不会把 AT、PaymentMethod 或代理池写入数据库。页面会将当前账号列表和代理草稿保存在浏览器本地存储;发布前清理迁移会自动删除旧私有版本的数据。
53
-
54
- ## API
55
-
56
- - `GET /health`
57
- - `GET /api/standalone/info`
58
- - `POST /api/card-bind/session`
59
- - `POST /api/standalone-flow/quick-checkout`
60
- - `GET /api/standalone-flow/task/{task_id}`
61
- - `POST /api/standalone-flow/tasks/clear`
62
-
63
- ## 测试
64
-
65
- ```bat
66
- python -m unittest discover -s tests -v
67
- ```
68
-
69
- ## 免责声明
70
-
71
- 本项目仅用于技术研究、接口调试、自动化测试和个人开发。使用者应确保对所使用的账号、支付方式、代理、访问凭证、接口及网络环境拥有相应使用权限,并遵守所在地法律法规、平台服务条款及相关第三方规则。
72
-
73
- 严禁将本项目用于未经许可的支付操作、欺诈、盗刷、批量滥用、规避平台限制、侵犯他人权益或其他不当活动。因使用、修改、分发或部署本项目产生的账号限制、资金损失、数据泄露、服务中断、争议或责任,均由使用者自行承担。
74
-
75
- 本项目按“现状”提供,不承诺功能完整性、稳定性、准确性、适用性或持续可用性。作者及贡献者不对任何直接或间接损失承担责任。下载、安装、运行或使用本项目,即表示使用者已阅读并同意本免责声明。
 
1
+ ---
2
+ title: Protocol Card Binding
3
+ emoji: 🔗
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ # Protocol Card Binding
12
+
13
+ # Protocol Card Binding - Sanitized Source
14
+
15
+ Current card-binding, default-payment-method, temporary Checkout initialization, concurrent batch extraction and protocol-payment source.
16
+
17
+ ## Modules
18
+ - `app.py`: API, jobs, concurrency, cancellation and retry.
19
+ - `card_bind_session.py`: SetupIntent and Stripe publishable-key resolution.
20
+ - `card_set_default.py`: Attach and set the default PaymentMethod.
21
+ - `card_checkout_context.py`: Checkout and CustomerSession context.
22
+ - `server_confirmation_token.py`: ConfirmationToken helper.
23
+ - `ph_checkout_protocol.py`: Short-checkout protocol flow.
24
+ - `static/`, `templates/`: Binding and protocol-payment frontend.
25
+
26
+ ## Flow
27
+ 1. Create SetupIntent with an account access token.
28
+ 2. If Stripe context/key is missing, create one temporary Checkout.
29
+ 3. Fetch a fresh SetupIntent and key.
30
+ 4. Confirm binding through Stripe.js.
31
+ 5. Set the PaymentMethod as default.
32
+ 6. Run binding and extraction with concurrency up to 200.
33
+ 7. Release final payments in simultaneous waves of up to 200 accounts.
34
+ 8. Verify every paid account against the Plus subscription endpoint.
35
+ 9. Failed rows cancel their old child task and retry independently.
36
+
37
+ ## Deployment
38
+ Install `requirements.txt`, copy `.env.example` to `.env`, configure the local account archive and internal service endpoints, then run behind Flask/Gunicorn.
39
+
40
+ ## Sanitization
41
+ Excluded `.env`, accounts, tasks, logs, screenshots, runtime data, backups, caches and virtual environments. Deployment hostnames, server IPs, tokens and keys were removed or replaced.
42
+
43
+
44
+ ## Spaces runtime
45
+
46
+ This Space listens on port `7860` and starts with Gunicorn. Configure runtime values as Space Variables/Secrets; do not commit a live `.env` file.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
The diff for this file is too large to render. See raw diff
 
card_bind_session.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json, sys, random, re, base64, hashlib, uuid, os
3
+ from curl_ca_bundle import curl_session_kwargs, is_ca_bundle_error
4
+ try:
5
+ from requests import Session as RequestsSession
6
+ except ImportError:
7
+ RequestsSession=None
8
+ try:
9
+ from curl_cffi.requests import Session as CurlSession
10
+ CURL_CFFI_AVAILABLE=True
11
+ except ImportError:
12
+ CurlSession=None
13
+ CURL_CFFI_AVAILABLE=False
14
+ ACCOUNT_FILE=os.getenv("ACCOUNT_FILE", "./data/accounts.jsonl")
15
+ PK_RE=re.compile(r"pk_(?:live|test)_[A-Za-z0-9]{24,}")
16
+ def find_publishable_key(value):
17
+ if isinstance(value,dict):
18
+ for key in ("publishable_key","public_key","stripe_publishable_key","key"):
19
+ candidate=str(value.get(key) or "").strip()
20
+ if PK_RE.fullmatch(candidate): return candidate
21
+ for item in value.values():
22
+ found=find_publishable_key(item)
23
+ if found:return found
24
+ elif isinstance(value,list):
25
+ for item in value:
26
+ found=find_publishable_key(item)
27
+ if found:return found
28
+ elif isinstance(value,str):
29
+ match=PK_RE.search(value)
30
+ if match:return match.group(0)
31
+ return ""
32
+ UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"
33
+
34
+ def auto_us_billing(email):
35
+ try:
36
+ sys.path.insert(0,"/opt/paypal-pay")
37
+ from paypal import models
38
+ try:
39
+ address=models._generate_address_from_online_map("US")
40
+ except Exception:
41
+ address=None
42
+ if not address:
43
+ address=models.generate_address("US")
44
+ line1=" ".join(x for x in [str(address.house_number or ""),str(address.street or "")] if x).strip()
45
+ line2=str(address.district or "")
46
+ city=str(address.city or "")
47
+ state=str(address.state or "")
48
+ postal_code=str(address.postal_code or "")
49
+ except Exception:
50
+ line1="1600 Pennsylvania Avenue NW"
51
+ line2=""
52
+ city="Washington"
53
+ state="DC"
54
+ postal_code="20500"
55
+ names=["James Wilson","Michael Brown","Daniel Miller","David Anderson","Robert Taylor","William Thomas"]
56
+ return {
57
+ "name":random.choice(names),
58
+ "email":str(email or ""),
59
+ "phone":"+1202555%04d" % random.randint(100,9999),
60
+ "address":{
61
+ "country":"US",
62
+ "line1":line1,
63
+ "line2":line2,
64
+ "city":city,
65
+ "state":state,
66
+ "postal_code":postal_code,
67
+ }
68
+ }
69
+
70
+ def helper_error_payload(exc):
71
+ detail=re.sub(r"(?i)((?:https?|socks5h?)://)[^/@\s]+@",r"\1***@",f"{type(exc).__name__}: {exc}")[:300]
72
+ lowered=detail.lower()
73
+ if is_ca_bundle_error(exc):
74
+ error="CARD_BIND_TLS_CA_BUNDLE_ERROR"
75
+ elif isinstance(exc,ModuleNotFoundError):
76
+ error="CARD_BIND_DEPENDENCY_MISSING"
77
+ elif isinstance(exc,FileNotFoundError):
78
+ error="CARD_BIND_RUNTIME_FILE_MISSING"
79
+ elif any(marker in lowered for marker in ("curl:","could not connect","connectionerror","proxyerror","timed out","timeout","tls","ssl")):
80
+ error="CARD_BIND_UPSTREAM_NETWORK_ERROR"
81
+ elif "missing dependencies" in lowered or "socks support" in lowered:
82
+ error="CARD_BIND_DEPENDENCY_MISSING"
83
+ else:
84
+ error="CARD_BIND_HELPER_ERROR"
85
+ return {"ok":False,"error":error,"detail":detail}
86
+
87
+ def proxy_variants(proxy):
88
+ value=str(proxy or "").strip()
89
+ variants=[value]
90
+ lowered=value.lower()
91
+ if lowered.startswith("socks5h://"):
92
+ variants.append("socks5://"+value[len("socks5h://"):])
93
+ elif lowered.startswith("socks5://"):
94
+ variants.append("socks5h://"+value[len("socks5://"):])
95
+ return variants
96
+
97
+ def request_payment_method(account,proxy,cookies,headers):
98
+ candidates=[]
99
+ if CURL_CFFI_AVAILABLE:
100
+ candidates.extend([
101
+ ("curl_firefox144",lambda:CurlSession(impersonate="firefox144",**curl_session_kwargs())),
102
+ ("curl_chrome146",lambda:CurlSession(impersonate="chrome146",**curl_session_kwargs())),
103
+ ])
104
+ if RequestsSession is not None:
105
+ candidates.append(("requests_openssl",RequestsSession))
106
+ if not candidates:
107
+ raise ModuleNotFoundError("Neither curl_cffi nor requests is installed")
108
+ failures=[];last_detail=""
109
+ for candidate_proxy in proxy_variants(proxy):
110
+ dns_mode="remote_dns" if candidate_proxy.lower().startswith("socks5h://") else "local_dns" if candidate_proxy.lower().startswith("socks5://") else "default"
111
+ for transport,factory in candidates:
112
+ label=transport if dns_mode=="default" else f"{transport}_{dns_mode}"
113
+ http=factory();http.trust_env=False
114
+ if candidate_proxy and candidate_proxy.upper()!="DIRECT":http.proxies={"http":candidate_proxy,"https":candidate_proxy}
115
+ for name,value in dict(cookies).items():
116
+ try:http.cookies.set(str(name),str(value),domain="chatgpt.com")
117
+ except:pass
118
+ try:
119
+ response=http.post("https://chatgpt.com/backend-api/payments/payment_method",json={"account_id":account.get("account_id")},headers=headers,timeout=45)
120
+ return response,label
121
+ except Exception as exc:
122
+ failure=helper_error_payload(exc)
123
+ if failure["error"]!="CARD_BIND_UPSTREAM_NETWORK_ERROR":raise
124
+ failures.append(f"{label}={type(exc).__name__}")
125
+ last_detail=failure["detail"]
126
+ finally:http.close()
127
+ raise RuntimeError("TRANSPORT_FALLBACK_EXHAUSTED: "+"; ".join(failures)+"; last="+last_detail)
128
+
129
+ def main():
130
+ email=str(sys.argv[1] if len(sys.argv)>1 else "").strip().lower(); account=None
131
+ access_token_override=str(sys.argv[3] if len(sys.argv)>3 else "").strip()
132
+ email_candidate=None
133
+ if os.path.isfile(ACCOUNT_FILE):
134
+ with open(ACCOUNT_FILE,encoding="utf-8",errors="ignore") as h:
135
+ for line in h:
136
+ try:item=json.loads(line)
137
+ except:continue
138
+ if access_token_override and str(item.get("access_token") or "").strip()==access_token_override:
139
+ account=item
140
+ break
141
+ if str(item.get("email") or "").strip().lower()==email:
142
+ email_candidate=item
143
+ if not account and access_token_override:
144
+ try:
145
+ 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"}
146
+ except Exception:
147
+ account=None
148
+ if not account: account=email_candidate
149
+ if not account: print(json.dumps({"ok":False,"error":"ACCOUNT_NOT_FOUND"})); return 2
150
+ if access_token_override:
151
+ account=dict(account);account["access_token"]=access_token_override
152
+ proxy=str(sys.argv[2] if len(sys.argv)>2 else account.get("proxy") or "").strip()
153
+ cookies=account.get("session_cookies") or {}
154
+ if isinstance(cookies,str):
155
+ try:cookies=json.loads(cookies)
156
+ except:cookies={}
157
+ 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"}
158
+ response,transport=request_payment_method(account,proxy,cookies,headers)
159
+ try:data=response.json() or {}
160
+ except:data={}
161
+ secret=str(data.get("client_secret") or "")
162
+ if response.status_code!=200 or not secret.startswith("seti_"):
163
+ detail=data.get("detail") or data.get("error") or ""
164
+ print(json.dumps({"ok":False,"error":"SETUP_INTENT_FAILED","status":response.status_code,"detail":str(detail)[:300],"transport":transport})); return 3
165
+ billing=auto_us_billing(email)
166
+ 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
167
+ if __name__=="__main__":
168
+ try:
169
+ raise SystemExit(main())
170
+ except SystemExit:
171
+ raise
172
+ except Exception as exc:
173
+ print(json.dumps(helper_error_payload(exc)))
174
+ raise SystemExit(10)
card_checkout_context.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ import uuid
6
+
7
+ import ph_checkout_protocol as protocol
8
+
9
+
10
+ def main() -> int:
11
+ snapshot = json.loads(sys.stdin.read() or "{}")
12
+ short_url = str(snapshot.get("short_url") or "")
13
+ parts = short_url.split("/")
14
+ if len(parts) < 6:
15
+ raise ValueError("Checkout URL is invalid")
16
+
17
+ payload = {
18
+ "short_url": short_url,
19
+ "processor_entity": parts[4],
20
+ "checkout_session_id": str(snapshot.get("checkout_session_id") or parts[5]),
21
+ "access_token": snapshot.get("access_token"),
22
+ "chatgpt_account_id": snapshot.get("chatgpt_account_id"),
23
+ "session_cookies": snapshot.get("session_cookies") or {},
24
+ "user_agent": snapshot.get("user_agent"),
25
+ "checkout_device_id": snapshot.get("checkout_device_id"),
26
+ "checkout_chatgpt_session_id": snapshot.get("checkout_chatgpt_session_id"),
27
+ "email": snapshot.get("email"),
28
+ "proxy": snapshot.get("checkout_proxy") or snapshot.get("proxy"),
29
+ }
30
+ proxy = protocol.normalize_proxy(str(payload.get("proxy") or ""))
31
+ if not proxy:
32
+ raise ValueError("Checkout proxy is missing")
33
+ cookies = dict(payload.get("session_cookies") or {})
34
+ device_id = str(payload.get("checkout_device_id") or cookies.get("oai-did") or uuid.uuid4())
35
+ http = protocol.build_identity_http(proxy, str(payload.get("user_agent") or ""))
36
+ protocol.install_cookies(http, cookies, device_id)
37
+ state = protocol.resolve_oaics_checkout(
38
+ http,
39
+ payload,
40
+ str(payload["processor_entity"]),
41
+ str(payload["checkout_session_id"]),
42
+ device_id,
43
+ )
44
+ amount, currency = protocol.oaics_total(state)
45
+ methods = [str(item).lower() for item in (state.get("payment_method_types") or [])]
46
+ customer_session = str(state.get("customer_session_client_secret") or "")
47
+ publishable_key = str(state.get("publishable_key") or "")
48
+ if not publishable_key.startswith("pk_") or not customer_session.startswith("cuss_secret_"):
49
+ raise RuntimeError("Checkout customer context is incomplete")
50
+ result = {
51
+ "ok": True,
52
+ "task_id": str(snapshot.get("task_id") or ""),
53
+ "publishable_key": publishable_key,
54
+ "customer_session_client_secret": customer_session,
55
+ "mode": "subscription",
56
+ "amount": int(amount),
57
+ "currency": str(currency).lower(),
58
+ "payment_method_types": methods or ["card"],
59
+ "setup_future_usage": "off_session",
60
+ "return_url": str(state.get("confirm_return_url") or short_url),
61
+ }
62
+ print(json.dumps(result, ensure_ascii=True))
63
+ return 0
64
+
65
+
66
+ if __name__ == "__main__":
67
+ raise SystemExit(main())
card_set_default.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ import os
4
+ import re
5
+ import sys
6
+ import time
7
+ import base64
8
+ import hashlib
9
+ import uuid
10
+ from typing import Any
11
+
12
+ from curl_ca_bundle import curl_session_kwargs, is_ca_bundle_error
13
+
14
+ try:
15
+ from curl_cffi.requests import Session
16
+ except ImportError: # pragma: no cover - dependency is declared in requirements.txt
17
+ Session = None # type: ignore[assignment]
18
+
19
+ ACCOUNT_FILE = "/opt/reg153/success_accounts.jsonl"
20
+ UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"
21
+ SET_DEFAULT_PROXY_REUSE_ATTEMPTS = max(
22
+ 1,
23
+ min(
24
+ 10,
25
+ int(
26
+ os.getenv("SET_DEFAULT_PROXY_REUSE_ATTEMPTS")
27
+ or os.getenv("CARD_BIND_PROXY_REUSE_ATTEMPTS")
28
+ or "3"
29
+ ),
30
+ ),
31
+ )
32
+ SET_DEFAULT_REQUEST_TIMEOUT = max(
33
+ 5, min(60, int(os.getenv("SET_DEFAULT_REQUEST_TIMEOUT", "25")))
34
+ )
35
+
36
+
37
+ class UpstreamResponseError(RuntimeError):
38
+ def __init__(self, error: str, status: int, detail: str = "") -> None:
39
+ super().__init__(detail or f"HTTP {status}")
40
+ self.error = error
41
+ self.status = status
42
+ self.detail = detail
43
+
44
+
45
+ def safe_detail(value: object) -> str:
46
+ text = str(value or "")
47
+ text = re.sub(r"(?i)((?:https?|socks5h?)://)[^/@\s]+@", r"\1***@", text)
48
+ text = re.sub(
49
+ r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+",
50
+ "AT_REDACTED",
51
+ text,
52
+ )
53
+ return text[:500]
54
+
55
+
56
+ def retryable_transport_error(exc: Exception) -> bool:
57
+ if is_ca_bundle_error(exc):
58
+ return False
59
+ detail = f"{type(exc).__name__}: {exc}".lower()
60
+ return any(
61
+ marker in detail
62
+ for marker in (
63
+ "connectionerror",
64
+ "connecterror",
65
+ "could not connect",
66
+ "failed to connect",
67
+ "connection closed",
68
+ "connection reset",
69
+ "proxyerror",
70
+ "timeout",
71
+ "timed out",
72
+ "ssl",
73
+ "tls",
74
+ "curl: (7)",
75
+ "curl: (28)",
76
+ "curl: (35)",
77
+ "curl: (52)",
78
+ "curl: (55)",
79
+ "curl: (56)",
80
+ )
81
+ )
82
+
83
+
84
+ def helper_error_payload(exc: Exception) -> dict[str, Any]:
85
+ if isinstance(exc, UpstreamResponseError):
86
+ return {
87
+ "ok": False,
88
+ "error": exc.error,
89
+ "status": exc.status,
90
+ "detail": safe_detail(exc.detail),
91
+ }
92
+ detail = safe_detail(f"{type(exc).__name__}: {exc}")
93
+ lowered = detail.lower()
94
+ if is_ca_bundle_error(exc):
95
+ error = "SET_DEFAULT_TLS_CA_BUNDLE_ERROR"
96
+ elif isinstance(exc, ModuleNotFoundError):
97
+ error = "SET_DEFAULT_DEPENDENCY_MISSING"
98
+ elif retryable_transport_error(exc) or "proxy_retry_exhausted" in lowered:
99
+ error = "SET_DEFAULT_UPSTREAM_NETWORK_ERROR"
100
+ else:
101
+ error = "SET_DEFAULT_HELPER_ERROR"
102
+ return {"ok": False, "error": error, "detail": detail}
103
+
104
+
105
+ def proxy_variants(proxy: str) -> list[str]:
106
+ value = str(proxy or "").strip()
107
+ variants = [value]
108
+ lowered = value.lower()
109
+ if lowered.startswith("socks5h://"):
110
+ variants.append("socks5://" + value[len("socks5h://") :])
111
+ elif lowered.startswith("socks5://"):
112
+ variants.append("socks5h://" + value[len("socks5://") :])
113
+ return variants
114
+
115
+
116
+ class RotatingDefaultSession:
117
+ def __init__(
118
+ self,
119
+ proxy: str,
120
+ cookies: dict,
121
+ *,
122
+ retry_attempts: int = SET_DEFAULT_PROXY_REUSE_ATTEMPTS,
123
+ retry_delay: float = 0.5,
124
+ ) -> None:
125
+ self.proxy = str(proxy or "").strip()
126
+ self.cookies = dict(cookies or {})
127
+ self.retry_attempts = max(1, min(10, int(retry_attempts)))
128
+ self.retry_delay = max(0.0, min(5.0, float(retry_delay)))
129
+
130
+ def _open(self, proxy: str):
131
+ if Session is None:
132
+ raise ModuleNotFoundError("curl_cffi is not installed")
133
+ http = Session(impersonate="firefox144", **curl_session_kwargs())
134
+ http.trust_env = False
135
+ if proxy and proxy.upper() != "DIRECT":
136
+ http.proxies = {"http": proxy, "https": proxy}
137
+ for name, value in self.cookies.items():
138
+ try:
139
+ http.cookies.set(str(name), str(value), domain="chatgpt.com")
140
+ except Exception:
141
+ pass
142
+ return http
143
+
144
+ def request(self, method: str, url: str, **kwargs: Any):
145
+ failures: list[str] = []
146
+ last_error: Exception | None = None
147
+ variants = proxy_variants(self.proxy)
148
+ for attempt in range(1, self.retry_attempts + 1):
149
+ for candidate_proxy in variants:
150
+ http = None
151
+ dns_mode = (
152
+ "remote_dns"
153
+ if candidate_proxy.lower().startswith("socks5h://")
154
+ else "local_dns"
155
+ if candidate_proxy.lower().startswith("socks5://")
156
+ else "default"
157
+ )
158
+ try:
159
+ http = self._open(candidate_proxy)
160
+ response = getattr(http, method)(url, **kwargs)
161
+ return response, f"curl_firefox144_{dns_mode}_round_{attempt}"
162
+ except Exception as exc:
163
+ if is_ca_bundle_error(exc):
164
+ raise RuntimeError(
165
+ f"SET_DEFAULT_TLS_CA_BUNDLE_ERROR: {safe_detail(exc)}"
166
+ ) from exc
167
+ if not retryable_transport_error(exc):
168
+ raise
169
+ last_error = exc
170
+ failures.append(
171
+ f"round_{attempt}_{dns_mode}={type(exc).__name__}"
172
+ )
173
+ finally:
174
+ try:
175
+ if http is not None:
176
+ http.close()
177
+ except Exception:
178
+ pass
179
+ if attempt < self.retry_attempts and self.retry_delay:
180
+ time.sleep(self.retry_delay)
181
+ assert last_error is not None
182
+ raise RuntimeError(
183
+ "SET_DEFAULT_PROXY_RETRY_EXHAUSTED: "
184
+ f"{self.retry_attempts} fresh connection round(s); "
185
+ + "; ".join(failures)
186
+ + f"; last={safe_detail(f'{type(last_error).__name__}: {last_error}')}"
187
+ ) from last_error
188
+
189
+ def get(self, url: str, **kwargs: Any):
190
+ return self.request("get", url, **kwargs)
191
+
192
+ def post(self, url: str, **kwargs: Any):
193
+ return self.request("post", url, **kwargs)
194
+
195
+
196
+ def response_detail(response: object) -> str:
197
+ try:
198
+ payload = response.json()
199
+ except Exception:
200
+ return safe_detail(getattr(response, "text", ""))
201
+ if isinstance(payload, dict):
202
+ value = payload.get("detail") or payload.get("message") or payload.get("error")
203
+ if isinstance(value, dict):
204
+ value = value.get("message") or value.get("code") or value
205
+ return safe_detail(value)
206
+ return safe_detail(payload)
207
+
208
+
209
+ def load_account(email: str):
210
+ match = None
211
+ with open(ACCOUNT_FILE, encoding="utf-8", errors="ignore") as handle:
212
+ for line in handle:
213
+ try:
214
+ item = json.loads(line)
215
+ except Exception:
216
+ continue
217
+ if str(item.get("email") or "").strip().lower() == email:
218
+ match = item
219
+ return match
220
+
221
+
222
+ def list_payment_method_ids(
223
+ http: RotatingDefaultSession, headers: dict, account_id: str
224
+ ) -> tuple[set[str], str]:
225
+ response, transport = http.get(
226
+ "https://chatgpt.com/backend-api/payments/payment_methods",
227
+ params={"account_id": account_id},
228
+ headers=headers,
229
+ timeout=SET_DEFAULT_REQUEST_TIMEOUT,
230
+ )
231
+ if response.status_code != 200:
232
+ raise UpstreamResponseError(
233
+ "PAYMENT_METHOD_LOOKUP_FAILED",
234
+ response.status_code,
235
+ response_detail(response),
236
+ )
237
+ try:
238
+ payload = response.json()
239
+ except Exception as exc:
240
+ raise RuntimeError("PAYMENT_METHOD_LOOKUP_INVALID_RESPONSE") from exc
241
+ if isinstance(payload, list):
242
+ items = payload
243
+ elif isinstance(payload, dict):
244
+ items = payload.get("data") or payload.get("payment_methods") or []
245
+ else:
246
+ items = []
247
+ return (
248
+ {str(item.get("id") or "") for item in items if isinstance(item, dict)},
249
+ transport,
250
+ )
251
+
252
+
253
+ def main() -> int:
254
+ email = str(sys.argv[1] if len(sys.argv) > 1 else "").strip().lower()
255
+ payment_method_id = str(sys.argv[2] if len(sys.argv) > 2 else "").strip()
256
+ if not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id):
257
+ print(json.dumps({"ok": False, "error": "INVALID_PAYMENT_METHOD"}))
258
+ return 2
259
+
260
+ access_token_override = str(sys.argv[4] if len(sys.argv) > 4 else "").strip()
261
+ account = None if access_token_override else load_account(email)
262
+ if access_token_override:
263
+ try:
264
+ segment = access_token_override.split(".")[1]
265
+ segment += "=" * (-len(segment) % 4)
266
+ claims = json.loads(base64.urlsafe_b64decode(segment.encode()).decode())
267
+ auth = claims.get("https://api.openai.com/auth") or {}
268
+ profile = claims.get("https://api.openai.com/profile") or {}
269
+ account_id_value = str(auth.get("chatgpt_account_id") or claims.get("account_id") or "").strip()
270
+ token_hash = hashlib.sha256(access_token_override.encode()).hexdigest()
271
+ decoded_email = str(profile.get("email") or claims.get("email") or email or f"external-{token_hash[:16]}@example.com").strip().lower()
272
+ device_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "reg153-external-at:" + account_id_value))
273
+ account = {"email": decoded_email, "account_id": account_id_value, "access_token": access_token_override, "session_cookies": {"oai-did": device_id}, "proxy": "DIRECT"}
274
+ except Exception:
275
+ account = None
276
+ if not account:
277
+ print(json.dumps({"ok": False, "error": "ACCOUNT_NOT_FOUND"}))
278
+ return 3
279
+ if access_token_override:
280
+ account = dict(account)
281
+ account["access_token"] = access_token_override
282
+
283
+ account_id = str(account.get("account_id") or "")
284
+ access_token = str(account.get("access_token") or "")
285
+ if not account_id or not access_token:
286
+ print(json.dumps({"ok": False, "error": "ACCOUNT_SESSION_INCOMPLETE"}))
287
+ return 4
288
+
289
+ proxy = str(sys.argv[3] if len(sys.argv) > 3 else account.get("proxy") or "").strip()
290
+ cookies = account.get("session_cookies") or {}
291
+ if isinstance(cookies, str):
292
+ try:
293
+ cookies = json.loads(cookies)
294
+ except Exception:
295
+ cookies = {}
296
+ headers = {
297
+ "Authorization": "Bearer " + access_token,
298
+ "ChatGPT-Account-Id": account_id,
299
+ "OAI-Device-Id": str(cookies.get("oai-did") or ""),
300
+ "User-Agent": UA,
301
+ "Accept": "application/json",
302
+ "Origin": "https://chatgpt.com",
303
+ "Referer": "https://chatgpt.com/",
304
+ "Content-Type": "application/json",
305
+ }
306
+
307
+ http = RotatingDefaultSession(proxy, dict(cookies))
308
+ response, set_transport = http.post(
309
+ "https://chatgpt.com/backend-api/payments/payment_method/default",
310
+ json={"account_id": account_id, "payment_method_id": payment_method_id},
311
+ headers=headers,
312
+ timeout=SET_DEFAULT_REQUEST_TIMEOUT,
313
+ )
314
+ if response.status_code not in (200, 204):
315
+ print(
316
+ json.dumps(
317
+ {
318
+ "ok": False,
319
+ "error": "SET_DEFAULT_FAILED",
320
+ "status": response.status_code,
321
+ "detail": response_detail(response),
322
+ "transport": set_transport,
323
+ },
324
+ ensure_ascii=True,
325
+ )
326
+ )
327
+ return 5
328
+
329
+ # Wait until the default endpoint's attachment is visible before Checkout.
330
+ last_transport = set_transport
331
+ for attempt in range(1, 13):
332
+ payment_method_ids, last_transport = list_payment_method_ids(
333
+ http, headers, account_id
334
+ )
335
+ if payment_method_id in payment_method_ids:
336
+ print(
337
+ json.dumps(
338
+ {
339
+ "ok": True,
340
+ "attached": True,
341
+ "attempt": attempt,
342
+ "transport": last_transport,
343
+ },
344
+ ensure_ascii=True,
345
+ )
346
+ )
347
+ return 0
348
+ time.sleep(1.0)
349
+
350
+ print(
351
+ json.dumps(
352
+ {
353
+ "ok": False,
354
+ "error": "PAYMENT_METHOD_NOT_ATTACHED",
355
+ "transport": last_transport,
356
+ },
357
+ ensure_ascii=True,
358
+ )
359
+ )
360
+ return 6
361
+
362
+
363
+ if __name__ == "__main__":
364
+ try:
365
+ raise SystemExit(main())
366
+ except SystemExit:
367
+ raise
368
+ except Exception as exc:
369
+ print(json.dumps(helper_error_payload(exc), ensure_ascii=True))
370
+ raise SystemExit(10)
checkout_link_extractor.py ADDED
@@ -0,0 +1,1265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Standalone ChatGPT checkout short-link extractor.
3
+
4
+ Author: Simon
5
+
6
+ Default flow:
7
+
8
+ * checkout billing: PH / PHP
9
+ * checkout proxy country: US
10
+ * promotion update proxy country: TR
11
+ * payment locale: English
12
+ * proxy provider: Cliproxy-compatible username routing
13
+ * output: https://chatgpt.com/checkout/<processor_entity>/<oaics_id>
14
+
15
+ The script creates the checkout without a promotion, applies the promotion to
16
+ the same checkout through ``checkout/update``, and verifies the payable amount.
17
+ An explicit non-zero amount is rejected. If neither the update response nor the
18
+ checkout page exposes an amount, the result is returned as ``pending`` so a
19
+ payment client can verify it before payment.
20
+
21
+ Only ``curl_cffi`` is required::
22
+
23
+ python -m pip install "curl_cffi>=0.15.0"
24
+
25
+ Recommended usage keeps credentials out of the process list::
26
+
27
+ export CLIPROXY_HOST=proxy.example:8080
28
+ export CLIPROXY_USERNAME=your-user
29
+ export CLIPROXY_PASSWORD=your-password
30
+ python checkout_link_extractor_standalone.py --credential-file session.json --pretty
31
+
32
+ Use ``--credential-file -`` to read a token or session JSON from stdin.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import getpass
39
+ import json
40
+ import os
41
+ import random
42
+ import re
43
+ import sys
44
+ import time
45
+ import uuid
46
+ from concurrent.futures import ThreadPoolExecutor
47
+ from dataclasses import asdict, dataclass
48
+ from html import unescape as html_unescape
49
+ from pathlib import Path
50
+ from typing import Any, Callable
51
+ from urllib.parse import quote, unquote, urlsplit, urlunsplit
52
+
53
+ from curl_ca_bundle import curl_session_kwargs
54
+
55
+ try:
56
+ from curl_cffi.requests import Session as CurlSession
57
+ except ImportError: # pragma: no cover - exercised by the CLI error path
58
+ CurlSession = None # type: ignore[assignment]
59
+
60
+
61
+ VERSION = "1.0.0"
62
+ CHECKOUT_URL = "https://chatgpt.com/backend-api/payments/checkout"
63
+ UPDATE_PATH = "/backend-api/payments/checkout/update"
64
+ TRACE_URL = "https://www.cloudflare.com/cdn-cgi/trace"
65
+ DEFAULT_USER_AGENT = (
66
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
67
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
68
+ )
69
+ DEFAULT_CLIENT_VERSION = "prod-db390ebea64862bf1899c420a4c736e0cf639747"
70
+ DEFAULT_CLIENT_BUILD = "7904904"
71
+ PAYMENT_COOKIE_NAMES = frozenset(
72
+ {
73
+ "oai-did",
74
+ "oai-hlib",
75
+ "oai-sc",
76
+ "oaicom-stable-id",
77
+ "_account",
78
+ "_account_is_fedramp",
79
+ "__Secure-oai-is",
80
+ "__Secure-next-auth.session-token",
81
+ "__cf_bm",
82
+ "__cflb",
83
+ "_cfuvid",
84
+ "__oailb",
85
+ "cf_clearance",
86
+ }
87
+ )
88
+ RETRYABLE_STATUSES = frozenset({403, 429, 500, 502, 503, 504})
89
+ MAX_PAYLOAD_DEPTH = 128
90
+ MAX_PAYLOAD_NODES = 10_000
91
+
92
+
93
+ class ExtractorError(RuntimeError):
94
+ """Base error safe to expose in the CLI JSON response."""
95
+
96
+
97
+ class UpstreamError(ExtractorError):
98
+ def __init__(
99
+ self,
100
+ status_code: int,
101
+ message: str,
102
+ *,
103
+ retryable: bool = False,
104
+ cloudflare: bool = False,
105
+ ) -> None:
106
+ super().__init__(message)
107
+ self.status_code = status_code
108
+ self.retryable = retryable
109
+ self.cloudflare = cloudflare
110
+
111
+
112
+ class InvalidPromotionError(ExtractorError):
113
+ pass
114
+
115
+
116
+ class NonZeroAmountError(ExtractorError):
117
+ pass
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class Credentials:
122
+ access_token: str
123
+ session_cookie: str = ""
124
+
125
+
126
+ @dataclass(frozen=True)
127
+ class ExtractorConfig:
128
+ billing_country: str = "PH"
129
+ currency: str = "PHP"
130
+ payment_locale: str = "en"
131
+ checkout_proxy_country: str = "US"
132
+ update_proxy_country: str = "TR"
133
+ cliproxy_host: str = "127.0.0.1:19010"
134
+ cliproxy_username: str = ""
135
+ cliproxy_password: str = ""
136
+ checkout_proxy: str = ""
137
+ update_proxy: str = ""
138
+ plan_name: str = "chatgptplusplan"
139
+ promo_campaign_id: str = "plus-1-month-free"
140
+ checkout_ui_mode: str = "custom"
141
+ timeout: float = 45.0
142
+ checkout_attempts: int = 10
143
+ update_attempts: int = 15
144
+ full_attempts: int = 3
145
+ cf_same_identity_attempts: int = 5
146
+ cf_retry_delay: float = 3.0
147
+ verify_proxy_country: bool = True
148
+ user_agent: str = DEFAULT_USER_AGENT
149
+
150
+ def validate(self) -> None:
151
+ if not re.fullmatch(r"[A-Z]{2}", self.billing_country):
152
+ raise ExtractorError("billing country must be a two-letter code")
153
+ if not re.fullmatch(r"[A-Z]{3}", self.currency):
154
+ raise ExtractorError("currency must be a three-letter code")
155
+ for field_name, value in (
156
+ ("checkout proxy country", self.checkout_proxy_country),
157
+ ("update proxy country", self.update_proxy_country),
158
+ ):
159
+ if not re.fullmatch(r"[A-Z]{2}", value):
160
+ raise ExtractorError(f"{field_name} must be a two-letter code")
161
+ for field_name, value in (
162
+ ("checkout attempts", self.checkout_attempts),
163
+ ("update attempts", self.update_attempts),
164
+ ("full attempts", self.full_attempts),
165
+ ("CF same-identity attempts", self.cf_same_identity_attempts),
166
+ ):
167
+ if value < 1:
168
+ raise ExtractorError(f"{field_name} must be at least 1")
169
+
170
+
171
+ @dataclass(frozen=True)
172
+ class CheckoutResult:
173
+ ok: bool
174
+ long_url: str
175
+ cs_id: str
176
+ processor_entity: str
177
+ billing_country: str
178
+ currency: str
179
+ payment_locale: str
180
+ amount_verification: str
181
+ amount_minor: int | None
182
+ amount_currency: str
183
+
184
+
185
+ def find_value(payload: Any, keys: tuple[str, ...]) -> str:
186
+ stack: list[tuple[Any, int]] = [(payload, 0)]
187
+ visited: set[int] = set()
188
+ while stack and len(visited) < MAX_PAYLOAD_NODES:
189
+ current, depth = stack.pop()
190
+ if not isinstance(current, (dict, list)):
191
+ continue
192
+ identity = id(current)
193
+ if identity in visited:
194
+ continue
195
+ visited.add(identity)
196
+ if isinstance(current, dict):
197
+ for key in keys:
198
+ value = current.get(key)
199
+ if isinstance(value, str) and value.strip():
200
+ return value.strip()
201
+ children = list(current.values())
202
+ else:
203
+ children = current
204
+ if depth < MAX_PAYLOAD_DEPTH:
205
+ stack.extend((value, depth + 1) for value in reversed(children))
206
+ return ""
207
+
208
+
209
+ def parse_credentials(raw: str, explicit_session_cookie: str = "") -> Credentials:
210
+ raw = str(raw or "").strip()
211
+ if not raw:
212
+ raise ExtractorError("access token or session JSON is required")
213
+ payload: Any = None
214
+ if raw.startswith(("{", "[")):
215
+ try:
216
+ payload = json.loads(raw)
217
+ except json.JSONDecodeError as exc:
218
+ raise ExtractorError(f"credential JSON is invalid: {exc.msg}") from exc
219
+ access_token = find_value(payload, ("accessToken", "access_token", "token"))
220
+ else:
221
+ access_token = raw
222
+ if not access_token:
223
+ raise ExtractorError("credential payload does not contain an access token")
224
+ session_cookie = str(explicit_session_cookie or "").strip()
225
+ if not session_cookie and payload is not None:
226
+ session_cookie = find_value(
227
+ payload,
228
+ (
229
+ "chatgpt_session_cookie",
230
+ "chatgptSessionCookie",
231
+ "session_cookie",
232
+ "sessionCookie",
233
+ "sessionToken",
234
+ "__Secure-next-auth.session-token",
235
+ ),
236
+ )
237
+ return Credentials(access_token=access_token, session_cookie=session_cookie)
238
+
239
+
240
+ def cookie_header_value(cookie_header: str, name: str) -> str:
241
+ for item in str(cookie_header or "").split(";"):
242
+ key, separator, value = item.strip().partition("=")
243
+ if separator and key == name:
244
+ return value.strip()
245
+ return ""
246
+
247
+
248
+ def filter_payment_cookie_header(cookie_header: str) -> str:
249
+ values: dict[str, str] = {}
250
+ for item in str(cookie_header or "").split(";"):
251
+ name, separator, value = item.strip().partition("=")
252
+ if separator and name in PAYMENT_COOKIE_NAMES:
253
+ values[name] = value
254
+ return "; ".join(f"{name}={value}" for name, value in values.items())
255
+
256
+
257
+ def replace_cookie_value(cookie_header: str, name: str, value: str) -> str:
258
+ values: list[str] = []
259
+ replaced = False
260
+ for item in str(cookie_header or "").split(";"):
261
+ key, separator, _ = item.strip().partition("=")
262
+ if not separator:
263
+ continue
264
+ if key == name:
265
+ if not replaced:
266
+ values.append(f"{name}={value}")
267
+ replaced = True
268
+ else:
269
+ values.append(item.strip())
270
+ if not replaced:
271
+ values.insert(0, f"{name}={value}")
272
+ return "; ".join(values)
273
+
274
+
275
+ def initial_cookie_header(session_cookie: str, device_id: str) -> str:
276
+ raw_cookie = str(session_cookie or "").strip()
277
+ if raw_cookie and "=" not in raw_cookie.split(";", 1)[0]:
278
+ return f"oai-did={device_id}; __Secure-next-auth.session-token={raw_cookie}"
279
+ filtered = filter_payment_cookie_header(raw_cookie)
280
+ if not filtered:
281
+ return f"oai-did={device_id}"
282
+ return replace_cookie_value(filtered, "oai-did", device_id)
283
+
284
+
285
+ def merged_cookie_header(cookie_header: str, cookies: Any) -> str:
286
+ values: dict[str, str] = {}
287
+ for item in str(cookie_header or "").split(";"):
288
+ name, separator, value = item.strip().partition("=")
289
+ if separator and name:
290
+ values[name] = value
291
+ try:
292
+ for name, value in cookies.items():
293
+ if name:
294
+ values[str(name)] = str(value)
295
+ except Exception:
296
+ pass
297
+ return "; ".join(f"{name}={value}" for name, value in values.items())
298
+
299
+
300
+ def refresh_cookie_header(session: Any, fallback: str = "") -> None:
301
+ headers = getattr(session, "headers", None)
302
+ if headers is None:
303
+ return
304
+ cookie_header = filter_payment_cookie_header(
305
+ merged_cookie_header(
306
+ fallback or str(headers.get("Cookie") or ""),
307
+ getattr(session, "cookies", None),
308
+ )
309
+ )
310
+ if cookie_header:
311
+ headers["Cookie"] = cookie_header
312
+
313
+
314
+ def sync_cookies(target: Any, source: Any) -> None:
315
+ if target is source:
316
+ refresh_cookie_header(target)
317
+ return
318
+ try:
319
+ target.cookies.update(source.cookies)
320
+ except Exception:
321
+ pass
322
+ refresh_cookie_header(target, str(getattr(source, "headers", {}).get("Cookie") or ""))
323
+
324
+
325
+ def normalize_proxy_url(proxy: str) -> str:
326
+ proxy = str(proxy or "").strip()
327
+ if not proxy:
328
+ return ""
329
+ if "://" in proxy:
330
+ return proxy
331
+ parts = proxy.split(":", 3)
332
+ if len(parts) == 4 and parts[1].isdigit() and "@" not in proxy:
333
+ host, port, username, password = parts
334
+ return (
335
+ f"http://{quote(username, safe='-._~')}:"
336
+ f"{quote(password, safe='-._~')}@{host}:{port}"
337
+ )
338
+ return f"http://{proxy}"
339
+
340
+
341
+ def new_proxy_session_id() -> str:
342
+ return str(random.randint(10_000_000, 99_999_999))
343
+
344
+
345
+ def cliproxy_proxy_url(
346
+ host: str,
347
+ username: str,
348
+ password: str,
349
+ country: str,
350
+ session_id: str = "",
351
+ ) -> str:
352
+ host = re.sub(r"^https?://", "", str(host or "").strip()).strip("/")
353
+ username = str(username or "").strip()
354
+ password = str(password or "").strip()
355
+ country = str(country or "").strip().upper()
356
+ if not host or not username or not password:
357
+ raise ExtractorError(
358
+ "Cliproxy host, username and password are required unless both stage proxies are supplied"
359
+ )
360
+ if not re.fullmatch(r"[A-Z]{2}", country):
361
+ raise ExtractorError("Cliproxy country must be a two-letter code")
362
+ username_base = re.split(r"-region-[A-Za-z]{2}", username, maxsplit=1)[0]
363
+ routed_username = (
364
+ f"{username_base}-region-{country}-sid-{session_id or new_proxy_session_id()}"
365
+ )
366
+ return (
367
+ f"http://{quote(routed_username, safe='-._~')}:"
368
+ f"{quote(password, safe='-._~')}@{host}"
369
+ )
370
+
371
+
372
+ def rotate_proxy_session(proxy: str, country: str) -> str:
373
+ proxy = normalize_proxy_url(proxy)
374
+ if not proxy:
375
+ return proxy
376
+ parsed = urlsplit(proxy)
377
+ username = unquote(parsed.username or "")
378
+ password = unquote(parsed.password or "")
379
+ hostname = parsed.hostname or ""
380
+ if not username or not password or not hostname:
381
+ return proxy
382
+ rotated_username = re.sub(
383
+ r"region-[A-Za-z]{2}", f"region-{country.upper()}", username
384
+ )
385
+ if re.search(r"sid-[A-Za-z0-9]+", rotated_username):
386
+ rotated_username = re.sub(
387
+ r"sid-[A-Za-z0-9]+", f"sid-{new_proxy_session_id()}", rotated_username
388
+ )
389
+ elif re.search(r"region-[A-Za-z]{2}", rotated_username):
390
+ rotated_username += f"-sid-{new_proxy_session_id()}"
391
+ else:
392
+ return proxy
393
+ host = f"[{hostname}]" if ":" in hostname and not hostname.startswith("[") else hostname
394
+ if parsed.port:
395
+ host = f"{host}:{parsed.port}"
396
+ netloc = (
397
+ f"{quote(rotated_username, safe='-._~')}:"
398
+ f"{quote(password, safe='-._~')}@{host}"
399
+ )
400
+ return urlunsplit((parsed.scheme or "http", netloc, parsed.path, parsed.query, parsed.fragment))
401
+
402
+
403
+ def set_proxy(session: Any, proxy: str) -> None:
404
+ proxy = normalize_proxy_url(proxy)
405
+ session.proxies = {"http": proxy, "https": proxy} if proxy else {}
406
+
407
+
408
+ def safe_close(session: Any) -> None:
409
+ if session is None:
410
+ return
411
+ try:
412
+ session.close()
413
+ except Exception:
414
+ pass
415
+
416
+
417
+ def money_minor_units(value: Any) -> int | None:
418
+ stack: list[tuple[Any, int]] = [(value, 0)]
419
+ visited: set[int] = set()
420
+ while stack and len(visited) < MAX_PAYLOAD_NODES:
421
+ current, depth = stack.pop()
422
+ if isinstance(current, bool):
423
+ continue
424
+ if isinstance(current, int):
425
+ return current
426
+ if isinstance(current, str) and re.fullmatch(r"-?\d+", current.strip()):
427
+ return int(current.strip())
428
+ if not isinstance(current, dict):
429
+ continue
430
+ identity = id(current)
431
+ if identity in visited:
432
+ continue
433
+ visited.add(identity)
434
+ if depth < MAX_PAYLOAD_DEPTH:
435
+ children = [
436
+ current[key]
437
+ for key in ("minorUnitsAmount", "minor_units_amount", "amount")
438
+ if current.get(key) is not None
439
+ ]
440
+ stack.extend((child, depth + 1) for child in reversed(children))
441
+ return None
442
+
443
+
444
+ def nested_value(payload: Any, path: tuple[str, ...]) -> Any:
445
+ current = payload
446
+ for key in path:
447
+ if not isinstance(current, dict):
448
+ return None
449
+ current = current.get(key)
450
+ return current
451
+
452
+
453
+ def checkout_amount_minor(data: Any) -> int | None:
454
+ wrapper_keys = (
455
+ "checkout_session",
456
+ "checkoutSession",
457
+ "session",
458
+ "checkout",
459
+ "data",
460
+ "result",
461
+ "payload",
462
+ "response",
463
+ "checkout_state",
464
+ "checkoutState",
465
+ "checkout_snapshot",
466
+ "checkoutSnapshot",
467
+ )
468
+ amount_paths = (
469
+ ("checkout_amount_minor",),
470
+ ("total_summary", "due"),
471
+ ("totalSummary", "due"),
472
+ ("invoice", "amount_due"),
473
+ ("invoice", "amountDue"),
474
+ ("amount_due",),
475
+ ("amountDue",),
476
+ ("amount_total",),
477
+ ("amountTotal",),
478
+ ("total", "total"),
479
+ ("total", "due"),
480
+ ("total", "taxInclusive"),
481
+ ("total", "taxInclusiveAmount"),
482
+ )
483
+ visited: set[int] = set()
484
+
485
+ stack: list[tuple[Any, int]] = [(data, 0)]
486
+ while stack and len(visited) < MAX_PAYLOAD_NODES:
487
+ payload, depth = stack.pop()
488
+ if not isinstance(payload, dict) or id(payload) in visited:
489
+ continue
490
+ visited.add(id(payload))
491
+ for path in amount_paths:
492
+ amount = money_minor_units(nested_value(payload, path))
493
+ if amount is not None:
494
+ return amount
495
+ line_items = payload.get("lineItems") or payload.get("line_items")
496
+ if isinstance(line_items, list):
497
+ total = 0
498
+ found = False
499
+ for item in line_items:
500
+ if not isinstance(item, dict):
501
+ continue
502
+ for key in ("total", "subtotal", "unitAmount", "unit_amount"):
503
+ amount = money_minor_units(item.get(key))
504
+ if amount is not None:
505
+ total += amount
506
+ found = True
507
+ break
508
+ if found:
509
+ return total
510
+ if depth < MAX_PAYLOAD_DEPTH:
511
+ children = [payload.get(key) for key in wrapper_keys]
512
+ stack.extend((child, depth + 1) for child in reversed(children))
513
+ return None
514
+
515
+
516
+ def checkout_currency(data: Any) -> str:
517
+ visited: set[int] = set()
518
+ wrapper_keys = (
519
+ "checkout_state",
520
+ "checkoutState",
521
+ "checkout_snapshot",
522
+ "checkoutSnapshot",
523
+ "checkout_session",
524
+ "checkoutSession",
525
+ "session",
526
+ "checkout",
527
+ "data",
528
+ "result",
529
+ "payload",
530
+ "response",
531
+ "total",
532
+ "total_summary",
533
+ "totalSummary",
534
+ )
535
+ stack: list[tuple[Any, int]] = [(data, 0)]
536
+ while stack and len(visited) < MAX_PAYLOAD_NODES:
537
+ payload, depth = stack.pop()
538
+ if not isinstance(payload, dict) or id(payload) in visited:
539
+ continue
540
+ visited.add(id(payload))
541
+ for key in ("currency", "currency_code", "currencyCode"):
542
+ value = payload.get(key)
543
+ if isinstance(value, str) and re.fullmatch(r"[A-Za-z]{3}", value.strip()):
544
+ return value.strip().upper()
545
+ if depth < MAX_PAYLOAD_DEPTH:
546
+ children = [payload.get(key) for key in wrapper_keys]
547
+ stack.extend((child, depth + 1) for child in reversed(children))
548
+ return ""
549
+
550
+
551
+ def decode_react_router_payload(payload: Any) -> Any:
552
+ if not isinstance(payload, list):
553
+ return None
554
+ resolved: dict[int, Any] = {}
555
+
556
+ def resolve(reference: Any, depth: int = 0) -> Any:
557
+ if depth > MAX_PAYLOAD_DEPTH:
558
+ return None
559
+ if not isinstance(reference, int):
560
+ return reference
561
+ if reference < 0 or reference >= len(payload):
562
+ return None
563
+ if reference in resolved:
564
+ return resolved[reference]
565
+ value = payload[reference]
566
+ if isinstance(value, dict):
567
+ output: dict[str, Any] = {}
568
+ resolved[reference] = output
569
+ for encoded_key, encoded_value in value.items():
570
+ key_text = str(encoded_key)
571
+ if not key_text.startswith("_") or not key_text[1:].isdigit():
572
+ continue
573
+ key = resolve(int(key_text[1:]), depth + 1)
574
+ if key is not None:
575
+ output[str(key)] = resolve(encoded_value, depth + 1)
576
+ return output
577
+ if isinstance(value, list):
578
+ output_list: list[Any] = []
579
+ resolved[reference] = output_list
580
+ output_list.extend(resolve(item, depth + 1) for item in value)
581
+ return output_list
582
+ resolved[reference] = value
583
+ return value
584
+
585
+ return resolve(0)
586
+
587
+
588
+ def checkout_state_from_html(html: str) -> dict[str, Any]:
589
+ def find_state(payload: Any) -> dict[str, Any]:
590
+ stack: list[tuple[Any, int]] = [(payload, 0)]
591
+ visited: set[int] = set()
592
+ while stack and len(visited) < MAX_PAYLOAD_NODES:
593
+ current, depth = stack.pop()
594
+ if not isinstance(current, (dict, list)):
595
+ continue
596
+ identity = id(current)
597
+ if identity in visited:
598
+ continue
599
+ visited.add(identity)
600
+ if isinstance(current, dict):
601
+ for key in ("checkout_state", "checkoutState"):
602
+ state = current.get(key)
603
+ if isinstance(state, dict):
604
+ return state
605
+ if checkout_amount_minor(current) is not None and any(
606
+ key in current
607
+ for key in ("total", "total_summary", "totalSummary", "lineItems", "line_items")
608
+ ):
609
+ return current
610
+ children = list(current.values())
611
+ else:
612
+ children = current
613
+ if depth < MAX_PAYLOAD_DEPTH:
614
+ stack.extend((value, depth + 1) for value in reversed(children))
615
+ return {}
616
+
617
+ def state_from_serialized(serialized: str) -> dict[str, Any]:
618
+ try:
619
+ decoded: Any = json.loads(serialized)
620
+ except (json.JSONDecodeError, RecursionError, TypeError, ValueError):
621
+ return {}
622
+ if isinstance(decoded, list):
623
+ state = find_state(decode_react_router_payload(decoded))
624
+ if state:
625
+ return state
626
+ return find_state(decoded)
627
+
628
+ enqueue_pattern = re.compile(
629
+ r'window\.__reactRouterContext\.streamController\.enqueue\(("(?:\\.|[^"\\])*")\)',
630
+ re.DOTALL,
631
+ )
632
+ chunks: list[str] = []
633
+ for match in enqueue_pattern.finditer(str(html or "")):
634
+ try:
635
+ raw_payload = json.loads(match.group(1))
636
+ except (json.JSONDecodeError, TypeError, ValueError):
637
+ continue
638
+ if not isinstance(raw_payload, str):
639
+ continue
640
+ chunks.append(raw_payload)
641
+ state = state_from_serialized(raw_payload)
642
+ if state:
643
+ return state
644
+ if len(chunks) > 1:
645
+ state = state_from_serialized("".join(chunks))
646
+ if state:
647
+ return state
648
+ application_json_pattern = re.compile(
649
+ r"<script\b[^>]*\btype=(['\"])application/json\1[^>]*>(.*?)</script>",
650
+ re.IGNORECASE | re.DOTALL,
651
+ )
652
+ for match in application_json_pattern.finditer(str(html or "")):
653
+ state = state_from_serialized(html_unescape(match.group(2)).strip())
654
+ if state:
655
+ return state
656
+ return {}
657
+
658
+
659
+ def payload_has_invalid_promotion(payload: Any) -> bool:
660
+ stack: list[tuple[Any, int]] = [(payload, 0)]
661
+ visited: set[int] = set()
662
+ while stack and len(visited) < MAX_PAYLOAD_NODES:
663
+ current, depth = stack.pop()
664
+ if isinstance(current, str) and current.strip().lower() == "invalid_promotion":
665
+ return True
666
+ if not isinstance(current, (dict, list)):
667
+ continue
668
+ identity = id(current)
669
+ if identity in visited:
670
+ continue
671
+ visited.add(identity)
672
+ children = list(current.values()) if isinstance(current, dict) else current
673
+ if depth < MAX_PAYLOAD_DEPTH:
674
+ stack.extend((value, depth + 1) for value in reversed(children))
675
+ return False
676
+
677
+
678
+ def extract_processor_entity(payload: Any) -> str:
679
+ wrapper_keys = ("checkout_session", "checkoutSession", "session", "checkout", "data")
680
+ stack: list[tuple[Any, int]] = [(payload, 0)]
681
+ visited: set[int] = set()
682
+ while stack and len(visited) < MAX_PAYLOAD_NODES:
683
+ current, depth = stack.pop()
684
+ if not isinstance(current, dict) or id(current) in visited:
685
+ continue
686
+ visited.add(id(current))
687
+ direct = current.get("processor_entity") or current.get("processorEntity")
688
+ if direct:
689
+ return str(direct).strip()
690
+ if depth < MAX_PAYLOAD_DEPTH:
691
+ children = [current.get(key) for key in wrapper_keys]
692
+ stack.extend((child, depth + 1) for child in reversed(children))
693
+ return ""
694
+
695
+
696
+ def processor_entity_for_country(country: str, processor_entity: str = "") -> str:
697
+ if str(processor_entity or "").strip():
698
+ return str(processor_entity).strip()
699
+ return "openai_llc" if str(country or "").upper() == "US" else "openai_ie"
700
+
701
+
702
+ def checkout_short_url(cs_id: str, country: str, processor_entity: str = "") -> str:
703
+ entity = processor_entity_for_country(country, processor_entity)
704
+ return f"https://chatgpt.com/checkout/{entity}/{cs_id}"
705
+
706
+
707
+ def is_retryable_network_error(exc: Exception) -> bool:
708
+ retryable_names = {"ReadTimeout", "ConnectTimeout", "ConnectionError", "Timeout", "SSLError"}
709
+ if any(item.__name__ in retryable_names for item in type(exc).mro()):
710
+ return True
711
+ text = str(exc).lower()
712
+ return any(
713
+ marker in text
714
+ for marker in (
715
+ "read timed out",
716
+ "connect timed out",
717
+ "connection aborted",
718
+ "proxy connect aborted",
719
+ "curl: (56)",
720
+ "unexpected_eof",
721
+ "eof occurred in violation of protocol",
722
+ "max retries exceeded",
723
+ )
724
+ )
725
+
726
+
727
+ def response_error(response: Any, prefix: str) -> UpstreamError:
728
+ status = int(getattr(response, "status_code", 0) or 0)
729
+ headers = getattr(response, "headers", {}) or {}
730
+ content_type = str(headers.get("content-type") or "")
731
+ server = str(headers.get("server") or "")
732
+ body = str(getattr(response, "text", "") or "")
733
+ lowered = body[:4000].lower()
734
+ is_html = "html" in content_type.lower() or body.lstrip().lower().startswith(("<!doctype", "<html"))
735
+ cloudflare = status == 403 and (
736
+ "challenge-platform" in lowered
737
+ or "__cf$cv$params" in lowered
738
+ or "cloudflare" in server.lower()
739
+ or is_html
740
+ )
741
+ if is_html:
742
+ title_match = re.search(r"<title[^>]*>(.*?)</title>", body, re.IGNORECASE | re.DOTALL)
743
+ detail = re.sub(r"\s+", " ", title_match.group(1)).strip() if title_match else "HTML verification page"
744
+ else:
745
+ detail = re.sub(r"\s+", " ", body).strip()[:300] or "empty response"
746
+ return UpstreamError(
747
+ status,
748
+ f"{prefix}: HTTP {status}; {detail}",
749
+ retryable=status in RETRYABLE_STATUSES,
750
+ cloudflare=cloudflare,
751
+ )
752
+
753
+
754
+ class CheckoutExtractor:
755
+ def __init__(
756
+ self,
757
+ credentials: Credentials,
758
+ config: ExtractorConfig | None = None,
759
+ *,
760
+ session_factory: Callable[[], Any] | None = None,
761
+ sleeper: Callable[[float], None] = time.sleep,
762
+ logger: Callable[[str], None] | None = None,
763
+ ) -> None:
764
+ self.credentials = credentials
765
+ self.config = config or ExtractorConfig()
766
+ self.config.validate()
767
+ if session_factory is None:
768
+ if CurlSession is None:
769
+ raise ExtractorError(
770
+ 'curl_cffi is required; install it with: python -m pip install "curl_cffi>=0.15.0"'
771
+ )
772
+ session_factory = lambda: CurlSession(
773
+ impersonate="chrome136", **curl_session_kwargs()
774
+ )
775
+ self.session_factory = session_factory
776
+ self.sleep = sleeper
777
+ self.log = logger or (lambda message: print(message, file=sys.stderr, flush=True))
778
+ self.device_id = cookie_header_value(credentials.session_cookie, "oai-did") or str(uuid.uuid4())
779
+ self.chatgpt_session_id = str(uuid.uuid4())
780
+ self.last_session_cookies: dict[str, str] = {}
781
+ self.last_checkout_proxy = ""
782
+
783
+ def _new_identity_session(self, proxy: str) -> Any:
784
+ session = self.session_factory()
785
+ if hasattr(session, "trust_env"):
786
+ session.trust_env = False
787
+ session.headers.update(
788
+ {
789
+ "User-Agent": self.config.user_agent,
790
+ "Accept": "*/*",
791
+ "Accept-Language": "en-US,en;q=0.9",
792
+ "Authorization": f"Bearer {self.credentials.access_token}",
793
+ "Origin": "https://chatgpt.com",
794
+ "Referer": "https://chatgpt.com/",
795
+ "Content-Type": "application/json",
796
+ "oai-device-id": self.device_id,
797
+ "oai-language": "en-US",
798
+ "oai-session-id": self.chatgpt_session_id,
799
+ "oai-client-version": DEFAULT_CLIENT_VERSION,
800
+ "oai-client-build-number": DEFAULT_CLIENT_BUILD,
801
+ "sec-fetch-dest": "empty",
802
+ "sec-fetch-mode": "cors",
803
+ "sec-fetch-site": "same-origin",
804
+ "sec-ch-ua": '"Google Chrome";v="136", "Not.A/Brand";v="8", "Chromium";v="136"',
805
+ "sec-ch-ua-mobile": "?0",
806
+ "sec-ch-ua-platform": '"Windows"',
807
+ "Cookie": initial_cookie_header(self.credentials.session_cookie, self.device_id),
808
+ }
809
+ )
810
+ set_proxy(session, proxy)
811
+ return session
812
+
813
+ def _clone_session(self, source: Any, proxy: str) -> Any:
814
+ session = self.session_factory()
815
+ if hasattr(session, "trust_env"):
816
+ session.trust_env = False
817
+ session.headers.update(dict(getattr(source, "headers", {})))
818
+ try:
819
+ session.cookies.update(source.cookies)
820
+ except Exception:
821
+ pass
822
+ refresh_cookie_header(session, str(getattr(source, "headers", {}).get("Cookie") or ""))
823
+ set_proxy(session, proxy)
824
+ return session
825
+
826
+ def _stage_proxies(self) -> tuple[str, str]:
827
+ checkout_proxy = normalize_proxy_url(self.config.checkout_proxy)
828
+ update_proxy = normalize_proxy_url(self.config.update_proxy)
829
+ if not checkout_proxy:
830
+ checkout_proxy = cliproxy_proxy_url(
831
+ self.config.cliproxy_host,
832
+ self.config.cliproxy_username,
833
+ self.config.cliproxy_password,
834
+ self.config.checkout_proxy_country,
835
+ )
836
+ if not update_proxy:
837
+ update_proxy = cliproxy_proxy_url(
838
+ self.config.cliproxy_host,
839
+ self.config.cliproxy_username,
840
+ self.config.cliproxy_password,
841
+ self.config.update_proxy_country,
842
+ )
843
+ return checkout_proxy, update_proxy
844
+
845
+ def _probe_country(self, proxy: str, expected_country: str) -> None:
846
+ session = self.session_factory()
847
+ try:
848
+ set_proxy(session, proxy)
849
+ response = session.get(TRACE_URL, timeout=min(self.config.timeout, 12.0))
850
+ if int(getattr(response, "status_code", 0) or 0) >= 400:
851
+ raise response_error(response, "proxy country probe")
852
+ fields = dict(
853
+ line.split("=", 1)
854
+ for line in str(getattr(response, "text", "") or "").splitlines()
855
+ if "=" in line
856
+ )
857
+ observed = str(fields.get("loc") or "").upper()
858
+ if observed != expected_country:
859
+ raise ExtractorError(
860
+ f"proxy country mismatch: expected {expected_country}, observed {observed or 'unknown'}"
861
+ )
862
+ finally:
863
+ safe_close(session)
864
+
865
+ def _preflight(self, checkout_proxy: str, update_proxy: str) -> None:
866
+ if not self.config.verify_proxy_country:
867
+ return
868
+ with ThreadPoolExecutor(max_workers=2) as executor:
869
+ checkout_future = executor.submit(
870
+ self._probe_country, checkout_proxy, self.config.checkout_proxy_country
871
+ )
872
+ update_future = executor.submit(
873
+ self._probe_country, update_proxy, self.config.update_proxy_country
874
+ )
875
+ checkout_future.result()
876
+ update_future.result()
877
+ self.log(
878
+ f"Proxy check passed: checkout={self.config.checkout_proxy_country}, "
879
+ f"update={self.config.update_proxy_country}."
880
+ )
881
+
882
+ def _create_checkout(self, session: Any) -> dict[str, Any]:
883
+ refresh_cookie_header(session)
884
+ body = {
885
+ "entry_point": "all_plans_pricing_modal",
886
+ "plan_name": self.config.plan_name,
887
+ "billing_details": {
888
+ "country": self.config.billing_country,
889
+ "currency": self.config.currency,
890
+ },
891
+ "checkout_ui_mode": self.config.checkout_ui_mode,
892
+ }
893
+ response = session.post(
894
+ CHECKOUT_URL,
895
+ json=body,
896
+ headers={
897
+ "Referer": "https://chatgpt.com/",
898
+ "x-openai-target-path": "/backend-api/payments/checkout",
899
+ "x-openai-target-route": "/backend-api/payments/checkout",
900
+ },
901
+ timeout=self.config.timeout,
902
+ )
903
+ if int(getattr(response, "status_code", 0) or 0) >= 400:
904
+ try:
905
+ error_payload = response.json() or {}
906
+ except Exception:
907
+ error_payload = {}
908
+ if str(error_payload.get("detail") or "") == "User is already paid":
909
+ raise UpstreamError(400, "the account is already paid and cannot create a Plus checkout")
910
+ raise response_error(response, "checkout create failed")
911
+ try:
912
+ payload = response.json() or {}
913
+ except Exception as exc:
914
+ raise UpstreamError(502, "checkout create returned invalid JSON", retryable=True) from exc
915
+ cs_id = payload.get("checkout_session_id") or payload.get("session_id") or payload.get("id")
916
+ cs_id = str(cs_id or "").strip()
917
+ if not cs_id.startswith(("oaics_", "cs_")):
918
+ raise UpstreamError(502, "checkout response did not contain a supported session id")
919
+ return {
920
+ "cs_id": cs_id,
921
+ "processor_entity": extract_processor_entity(payload),
922
+ "billing_country": self.config.billing_country,
923
+ "currency": self.config.currency,
924
+ "checkout_amount_minor": checkout_amount_minor(payload),
925
+ }
926
+
927
+ def _create_checkout_with_retry(self, checkout_proxy: str) -> tuple[Any, dict[str, Any]]:
928
+ session = self._new_identity_session(checkout_proxy)
929
+ current_proxy = checkout_proxy
930
+ cloudflare_failures = 0
931
+ exit_rotated = False
932
+ last_error: Exception | None = None
933
+ for attempt in range(1, self.config.checkout_attempts + 1):
934
+ self.log(f"Checkout attempt {attempt}/{self.config.checkout_attempts}.")
935
+ try:
936
+ return session, self._create_checkout(session)
937
+ except UpstreamError as exc:
938
+ last_error = exc
939
+ if not exc.retryable or attempt >= self.config.checkout_attempts:
940
+ safe_close(session)
941
+ raise
942
+ if exc.cloudflare:
943
+ cloudflare_failures += 1
944
+ if cloudflare_failures >= self.config.cf_same_identity_attempts and not exit_rotated:
945
+ rotated = rotate_proxy_session(current_proxy, self.config.checkout_proxy_country)
946
+ if rotated != current_proxy:
947
+ current_proxy = rotated
948
+ set_proxy(session, current_proxy)
949
+ cloudflare_failures = 0
950
+ exit_rotated = True
951
+ self.log("Checkout CF retries exhausted; rotated the proxy exit once.")
952
+ if self.config.cf_retry_delay > 0:
953
+ self.sleep(self.config.cf_retry_delay)
954
+ except Exception as exc:
955
+ last_error = exc
956
+ if not is_retryable_network_error(exc) or attempt >= self.config.checkout_attempts:
957
+ safe_close(session)
958
+ raise ExtractorError(f"checkout network error: {exc}") from exc
959
+ safe_close(session)
960
+ raise ExtractorError(f"checkout retries exhausted: {last_error}")
961
+
962
+ def _update_promotion(
963
+ self,
964
+ checkout_session: Any,
965
+ checkout: dict[str, Any],
966
+ checkout_proxy: str,
967
+ update_proxy: str,
968
+ ) -> dict[str, Any]:
969
+ processor_entity = processor_entity_for_country(
970
+ checkout["billing_country"], checkout.get("processor_entity", "")
971
+ )
972
+ body = {
973
+ "checkout_session_id": checkout["cs_id"],
974
+ "processor_entity": processor_entity,
975
+ "plan_name": self.config.plan_name,
976
+ "price_interval": "month",
977
+ "seat_quantity": 1,
978
+ "promo_campaign": {
979
+ "promo_campaign_id": self.config.promo_campaign_id,
980
+ "is_coupon_from_query_param": False,
981
+ },
982
+ }
983
+ headers = {
984
+ "Referer": checkout_short_url(
985
+ checkout["cs_id"], checkout["billing_country"], processor_entity
986
+ ),
987
+ "x-openai-target-path": UPDATE_PATH,
988
+ "x-openai-target-route": UPDATE_PATH,
989
+ }
990
+ same_session = normalize_proxy_url(checkout_proxy) == normalize_proxy_url(update_proxy)
991
+ session = checkout_session if same_session else self._clone_session(checkout_session, update_proxy)
992
+ owns_session = not same_session
993
+ current_proxy = update_proxy
994
+ cloudflare_failures = 0
995
+ exit_rotated = False
996
+ try:
997
+ for attempt in range(1, self.config.update_attempts + 1):
998
+ self.log(f"Promotion update attempt {attempt}/{self.config.update_attempts}.")
999
+ try:
1000
+ refresh_cookie_header(session)
1001
+ response = session.post(
1002
+ f"https://chatgpt.com{UPDATE_PATH}",
1003
+ json=body,
1004
+ headers=headers,
1005
+ timeout=self.config.timeout,
1006
+ )
1007
+ except Exception as exc:
1008
+ if not is_retryable_network_error(exc) or attempt >= self.config.update_attempts:
1009
+ raise ExtractorError(f"promotion update network error: {exc}") from exc
1010
+ current_proxy = rotate_proxy_session(
1011
+ current_proxy, self.config.update_proxy_country
1012
+ )
1013
+ if owns_session:
1014
+ safe_close(session)
1015
+ session = self._clone_session(checkout_session, current_proxy)
1016
+ owns_session = True
1017
+ continue
1018
+ if int(getattr(response, "status_code", 0) or 0) >= 400:
1019
+ error = response_error(response, "checkout/update failed")
1020
+ if not error.retryable or attempt >= self.config.update_attempts:
1021
+ raise error
1022
+ if error.cloudflare:
1023
+ cloudflare_failures += 1
1024
+ if cloudflare_failures >= self.config.cf_same_identity_attempts and not exit_rotated:
1025
+ rotated = rotate_proxy_session(
1026
+ current_proxy, self.config.update_proxy_country
1027
+ )
1028
+ if rotated != current_proxy:
1029
+ current_proxy = rotated
1030
+ set_proxy(session, current_proxy)
1031
+ cloudflare_failures = 0
1032
+ exit_rotated = True
1033
+ self.log("Update CF retries exhausted; rotated the proxy exit once.")
1034
+ if self.config.cf_retry_delay > 0:
1035
+ self.sleep(self.config.cf_retry_delay)
1036
+ else:
1037
+ current_proxy = rotate_proxy_session(
1038
+ current_proxy, self.config.update_proxy_country
1039
+ )
1040
+ if owns_session:
1041
+ safe_close(session)
1042
+ session = self._clone_session(checkout_session, current_proxy)
1043
+ owns_session = True
1044
+ continue
1045
+ try:
1046
+ payload = response.json() or {}
1047
+ except Exception as exc:
1048
+ raise UpstreamError(502, "checkout/update returned invalid JSON") from exc
1049
+ if payload_has_invalid_promotion(payload):
1050
+ raise InvalidPromotionError("checkout/update returned invalid_promotion")
1051
+ if payload.get("success") is False:
1052
+ raise UpstreamError(502, "checkout/update explicitly rejected the promotion")
1053
+ sync_cookies(checkout_session, session)
1054
+ return payload
1055
+ raise ExtractorError("promotion update retries exhausted")
1056
+ finally:
1057
+ if owns_session:
1058
+ safe_close(session)
1059
+
1060
+ def _page_amount(self, session: Any, checkout: dict[str, Any]) -> tuple[int | None, str]:
1061
+ refresh_cookie_header(session)
1062
+ response = session.get(
1063
+ checkout_short_url(
1064
+ checkout["cs_id"],
1065
+ checkout["billing_country"],
1066
+ checkout.get("processor_entity", ""),
1067
+ ),
1068
+ headers={"Referer": "https://chatgpt.com/"},
1069
+ timeout=self.config.timeout,
1070
+ )
1071
+ if int(getattr(response, "status_code", 0) or 0) >= 400:
1072
+ raise response_error(response, "checkout page amount query failed")
1073
+ state = checkout_state_from_html(str(getattr(response, "text", "") or ""))
1074
+ return checkout_amount_minor(state), checkout_currency(state) or self.config.currency
1075
+
1076
+ def _verify_amount(
1077
+ self,
1078
+ checkout_session: Any,
1079
+ checkout: dict[str, Any],
1080
+ update_payload: dict[str, Any],
1081
+ ) -> tuple[str, int | None, str]:
1082
+ amount = checkout_amount_minor(update_payload)
1083
+ currency = checkout_currency(update_payload) or self.config.currency
1084
+ if amount is None:
1085
+ try:
1086
+ amount, currency = self._page_amount(checkout_session, checkout)
1087
+ except UpstreamError as exc:
1088
+ self.log(f"Amount page probe was unavailable ({exc.status_code}); returning pending.")
1089
+ amount = None
1090
+ if amount is None:
1091
+ return "pending", None, currency
1092
+ if amount != 0:
1093
+ raise NonZeroAmountError(
1094
+ f"promotion did not produce a zero checkout: amount_minor={amount} {currency}"
1095
+ )
1096
+ return "verified_zero", 0, currency
1097
+
1098
+ def extract(self) -> CheckoutResult:
1099
+ last_promotion_error: InvalidPromotionError | None = None
1100
+ for full_attempt in range(1, self.config.full_attempts + 1):
1101
+ checkout_session = None
1102
+ checkout_proxy, update_proxy = self._stage_proxies()
1103
+ try:
1104
+ self.log(f"Full checkout flow {full_attempt}/{self.config.full_attempts}.")
1105
+ self._preflight(checkout_proxy, update_proxy)
1106
+ checkout_session, checkout = self._create_checkout_with_retry(checkout_proxy)
1107
+ self.log(f"Checkout created: {checkout['cs_id'][:12]}...")
1108
+ update_payload = self._update_promotion(
1109
+ checkout_session, checkout, checkout_proxy, update_proxy
1110
+ )
1111
+ verification, amount, amount_currency = self._verify_amount(
1112
+ checkout_session, checkout, update_payload
1113
+ )
1114
+ self.last_checkout_proxy = checkout_proxy
1115
+ try:
1116
+ self.last_session_cookies = {
1117
+ str(name): str(value)
1118
+ for name, value in dict(checkout_session.cookies.get_dict()).items()
1119
+ if str(name) and str(value)
1120
+ }
1121
+ except Exception:
1122
+ self.last_session_cookies = {}
1123
+ return CheckoutResult(
1124
+ ok=True,
1125
+ long_url=checkout_short_url(
1126
+ checkout["cs_id"],
1127
+ checkout["billing_country"],
1128
+ checkout.get("processor_entity", ""),
1129
+ ),
1130
+ cs_id=checkout["cs_id"],
1131
+ processor_entity=processor_entity_for_country(
1132
+ checkout["billing_country"], checkout.get("processor_entity", "")
1133
+ ),
1134
+ billing_country=self.config.billing_country,
1135
+ currency=self.config.currency,
1136
+ payment_locale=self.config.payment_locale,
1137
+ amount_verification=verification,
1138
+ amount_minor=amount,
1139
+ amount_currency=amount_currency,
1140
+ )
1141
+ except InvalidPromotionError as exc:
1142
+ last_promotion_error = exc
1143
+ if full_attempt >= self.config.full_attempts:
1144
+ raise
1145
+ self.log("Promotion was invalid; discarding this checkout and rebuilding the full flow.")
1146
+ finally:
1147
+ safe_close(checkout_session)
1148
+ raise last_promotion_error or ExtractorError("checkout flow did not return a result")
1149
+
1150
+
1151
+ def read_credential_input(args: argparse.Namespace) -> str:
1152
+ if args.credential:
1153
+ return str(args.credential)
1154
+ if args.credential_file:
1155
+ if args.credential_file == "-":
1156
+ if sys.stdin.isatty():
1157
+ return getpass.getpass("Access token or session JSON: ")
1158
+ return sys.stdin.read()
1159
+ try:
1160
+ return Path(args.credential_file).expanduser().read_text(encoding="utf-8")
1161
+ except OSError as exc:
1162
+ raise ExtractorError(f"cannot read credential file: {exc}") from exc
1163
+ if not sys.stdin.isatty():
1164
+ return sys.stdin.read()
1165
+ return getpass.getpass("Access token or session JSON: ")
1166
+
1167
+
1168
+ def build_argument_parser() -> argparse.ArgumentParser:
1169
+ parser = argparse.ArgumentParser(
1170
+ description="Create a PH/PHP ChatGPT checkout short link through US checkout and TR update proxies."
1171
+ )
1172
+ parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
1173
+ parser.add_argument("--credential-file", default="", help="token/session JSON file, or '-' for stdin")
1174
+ parser.add_argument(
1175
+ "--credential",
1176
+ default="",
1177
+ help="raw token/session JSON (less secure than --credential-file)",
1178
+ )
1179
+ parser.add_argument("--session-cookie", default="", help="optional ChatGPT payment cookie header")
1180
+ parser.add_argument(
1181
+ "--cliproxy-host",
1182
+ default=os.getenv("CLIPROXY_HOST", os.getenv("OPENAI_PAY_CLIPROXY_HOST", "127.0.0.1:19010")),
1183
+ )
1184
+ parser.add_argument("--cliproxy-username", default=os.getenv("CLIPROXY_USERNAME", ""))
1185
+ parser.add_argument("--cliproxy-password", default=os.getenv("CLIPROXY_PASSWORD", ""))
1186
+ parser.add_argument("--checkout-proxy", default="", help="explicit proxy; overrides Cliproxy for checkout")
1187
+ parser.add_argument("--update-proxy", default="", help="explicit proxy; overrides Cliproxy for update")
1188
+ parser.add_argument("--billing-country", default="PH")
1189
+ parser.add_argument("--currency", default="PHP")
1190
+ parser.add_argument("--checkout-proxy-country", default="US")
1191
+ parser.add_argument("--update-proxy-country", default="TR")
1192
+ parser.add_argument("--payment-locale", default="en")
1193
+ parser.add_argument("--plan-name", default="chatgptplusplan")
1194
+ parser.add_argument("--promo-campaign-id", default="plus-1-month-free")
1195
+ parser.add_argument("--timeout", type=float, default=45.0)
1196
+ parser.add_argument("--checkout-attempts", type=int, default=10)
1197
+ parser.add_argument("--update-attempts", type=int, default=15)
1198
+ parser.add_argument("--full-attempts", type=int, default=3)
1199
+ parser.add_argument("--cf-same-identity-attempts", type=int, default=5)
1200
+ parser.add_argument("--cf-retry-delay", type=float, default=3.0)
1201
+ parser.add_argument("--skip-proxy-check", action="store_true")
1202
+ parser.add_argument("--pretty", action="store_true", help="pretty-print JSON output")
1203
+ return parser
1204
+
1205
+
1206
+ def config_from_args(args: argparse.Namespace) -> ExtractorConfig:
1207
+ return ExtractorConfig(
1208
+ billing_country=str(args.billing_country).upper(),
1209
+ currency=str(args.currency).upper(),
1210
+ payment_locale=str(args.payment_locale),
1211
+ checkout_proxy_country=str(args.checkout_proxy_country).upper(),
1212
+ update_proxy_country=str(args.update_proxy_country).upper(),
1213
+ cliproxy_host=str(args.cliproxy_host),
1214
+ cliproxy_username=str(args.cliproxy_username),
1215
+ cliproxy_password=str(args.cliproxy_password),
1216
+ checkout_proxy=str(args.checkout_proxy),
1217
+ update_proxy=str(args.update_proxy),
1218
+ plan_name=str(args.plan_name),
1219
+ promo_campaign_id=str(args.promo_campaign_id),
1220
+ timeout=float(args.timeout),
1221
+ checkout_attempts=int(args.checkout_attempts),
1222
+ update_attempts=int(args.update_attempts),
1223
+ full_attempts=int(args.full_attempts),
1224
+ cf_same_identity_attempts=int(args.cf_same_identity_attempts),
1225
+ cf_retry_delay=max(0.0, float(args.cf_retry_delay)),
1226
+ verify_proxy_country=not bool(args.skip_proxy_check),
1227
+ )
1228
+
1229
+
1230
+ def print_json(payload: dict[str, Any], pretty: bool) -> None:
1231
+ print(
1232
+ json.dumps(
1233
+ payload,
1234
+ ensure_ascii=False,
1235
+ indent=2 if pretty else None,
1236
+ separators=None if pretty else (",", ":"),
1237
+ )
1238
+ )
1239
+
1240
+
1241
+ def main(argv: list[str] | None = None) -> int:
1242
+ parser = build_argument_parser()
1243
+ args = parser.parse_args(argv)
1244
+ try:
1245
+ credentials = parse_credentials(read_credential_input(args), args.session_cookie)
1246
+ result = CheckoutExtractor(credentials, config_from_args(args)).extract()
1247
+ print_json(asdict(result), args.pretty)
1248
+ return 0
1249
+ except (ExtractorError, UpstreamError) as exc:
1250
+ print_json(
1251
+ {
1252
+ "ok": False,
1253
+ "error_type": type(exc).__name__,
1254
+ "error": str(exc),
1255
+ },
1256
+ args.pretty,
1257
+ )
1258
+ return 1
1259
+ except KeyboardInterrupt:
1260
+ print_json({"ok": False, "error_type": "Cancelled", "error": "cancelled"}, args.pretty)
1261
+ return 130
1262
+
1263
+
1264
+ if __name__ == "__main__":
1265
+ raise SystemExit(main())
curl_ca_bundle.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provide curl_cffi with a CA bundle path safe for native Windows curl."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ import tempfile
8
+ import threading
9
+ from pathlib import Path
10
+
11
+ try:
12
+ import certifi
13
+ except ImportError: # pragma: no cover - declared in requirements.txt
14
+ certifi = None # type: ignore[assignment]
15
+
16
+
17
+ _cached_path = ""
18
+ _cache_lock = threading.Lock()
19
+
20
+
21
+ def _is_ascii_path(path: Path) -> bool:
22
+ return str(path).isascii()
23
+
24
+
25
+ def _source_bundle() -> Path | None:
26
+ for variable in ("CURL_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE"):
27
+ configured = os.getenv(variable, "").strip()
28
+ if not configured:
29
+ continue
30
+ path = Path(configured).expanduser().resolve()
31
+ if not path.is_file():
32
+ raise RuntimeError(f"{variable}_NOT_FOUND: {path}")
33
+ return path
34
+ if certifi is None:
35
+ return None
36
+ path = Path(certifi.where()).resolve()
37
+ if not path.is_file():
38
+ raise RuntimeError(f"CERTIFI_CA_BUNDLE_NOT_FOUND: {path}")
39
+ return path
40
+
41
+
42
+ def _candidate_cache_dirs() -> list[Path]:
43
+ values = [
44
+ os.getenv("CURL_CA_ASCII_DIR", "").strip(),
45
+ os.getenv("CURL_CA_CACHE_DIR", "").strip(),
46
+ tempfile.gettempdir(),
47
+ str(Path(os.getenv("LOCALAPPDATA", "")) / "Temp")
48
+ if os.getenv("LOCALAPPDATA")
49
+ else "",
50
+ str(Path(os.getenv("SystemRoot", "")) / "Temp")
51
+ if os.getenv("SystemRoot")
52
+ else "",
53
+ ]
54
+ result: list[Path] = []
55
+ seen: set[str] = set()
56
+ for value in values:
57
+ if not value:
58
+ continue
59
+ path = Path(value).expanduser().resolve()
60
+ key = os.path.normcase(str(path))
61
+ if key in seen or not _is_ascii_path(path):
62
+ continue
63
+ seen.add(key)
64
+ result.append(path)
65
+ return result
66
+
67
+
68
+ def curl_ca_bundle_path() -> str:
69
+ """Return an existing ASCII-only CA path, copying certifi when necessary."""
70
+ global _cached_path
71
+ if _cached_path and Path(_cached_path).is_file():
72
+ return _cached_path
73
+ with _cache_lock:
74
+ if _cached_path and Path(_cached_path).is_file():
75
+ return _cached_path
76
+ source = _source_bundle()
77
+ if source is None:
78
+ return ""
79
+ if _is_ascii_path(source):
80
+ _cached_path = str(source)
81
+ return _cached_path
82
+
83
+ data = source.read_bytes()
84
+ if b"BEGIN CERTIFICATE" not in data:
85
+ raise RuntimeError("CERTIFI_CA_BUNDLE_INVALID")
86
+ digest = hashlib.sha256(data).hexdigest()
87
+ filename = f"protocol-card-ca-{digest[:16]}.pem"
88
+ failures: list[str] = []
89
+ for directory in _candidate_cache_dirs():
90
+ temporary: Path | None = None
91
+ target = directory / filename
92
+ try:
93
+ directory.mkdir(parents=True, exist_ok=True)
94
+ if target.is_file() and hashlib.sha256(target.read_bytes()).hexdigest() == digest:
95
+ _cached_path = str(target)
96
+ return _cached_path
97
+ temporary = directory / (
98
+ f".{filename}.{os.getpid()}.{threading.get_ident()}.tmp"
99
+ )
100
+ temporary.write_bytes(data)
101
+ os.replace(temporary, target)
102
+ if hashlib.sha256(target.read_bytes()).hexdigest() != digest:
103
+ raise RuntimeError("CA_CACHE_HASH_MISMATCH")
104
+ _cached_path = str(target)
105
+ return _cached_path
106
+ except Exception as exc:
107
+ try:
108
+ if target.is_file() and hashlib.sha256(target.read_bytes()).hexdigest() == digest:
109
+ _cached_path = str(target)
110
+ return _cached_path
111
+ except Exception:
112
+ pass
113
+ failures.append(f"{directory}={type(exc).__name__}")
114
+ if temporary is not None:
115
+ try:
116
+ temporary.unlink(missing_ok=True)
117
+ except Exception:
118
+ pass
119
+ raise RuntimeError(
120
+ "CURL_CA_ASCII_CACHE_UNAVAILABLE: " + "; ".join(failures)
121
+ )
122
+
123
+
124
+ def curl_session_kwargs() -> dict[str, object]:
125
+ path = curl_ca_bundle_path()
126
+ return {"verify": path} if path else {}
127
+
128
+
129
+ def is_ca_bundle_error(exc: Exception) -> bool:
130
+ detail = f"{type(exc).__name__}: {exc}".lower()
131
+ return any(
132
+ marker in detail
133
+ for marker in (
134
+ "curl: (77)",
135
+ "error adding trust anchors",
136
+ "curl_ca_ascii_cache_unavailable",
137
+ "ca_bundle_not_found",
138
+ "certifi_ca_bundle",
139
+ "ca_cache_hash_mismatch",
140
+ )
141
+ )
index.html DELETED
@@ -1,112 +0,0 @@
1
- <!doctype html>
2
- <html lang="zh-CN">
3
- <head>
4
- <meta charset="utf-8">
5
- <meta name="viewport" content="width=device-width,initial-scale=1">
6
- <title>直卡绑卡 · 提链 · 协议支付</title>
7
- <link rel="stylesheet" href="/static/direct-bind.css?v=20260804-35">
8
- </head>
9
- <body>
10
- <main class="shell batch-shell">
11
- <section class="hero">
12
- <span class="eyebrow">ONE CARD / ACCOUNT LIST / CHECKOUT LINKS</span>
13
- <h1>直卡绑卡 · 提链 · 协议支付</h1>
14
- <p>账号先导入列表,再按勾选账号执行任务;每个账号始终只占一行。</p>
15
- </section>
16
-
17
- <section class="card batch-card">
18
- <div class="steps batch-steps">
19
- <span id="stepCard" class="active">1 填写卡片</span>
20
- <span id="stepAt">2 导入账号</span>
21
- <span id="stepBind">3 批量绑卡</span>
22
- <span id="stepLink">4 批量提链</span>
23
- </div>
24
-
25
- <div class="setup-grid">
26
- <section class="batch-section card-setup-section">
27
- <div class="section-title">
28
- <div><b>卡片信息</b><small>卡号、有效期和 CVC 仅由 Stripe Elements 处理</small></div>
29
- <span class="tag">CARD FIRST</span>
30
- </div>
31
- <div class="card-fields-grid">
32
- <label class="card-field card-number-field"><span>卡号</span><div id="cardNumberElement" class="card-field-box"></div></label>
33
- <label class="card-field"><span>有效期</span><div id="cardExpiryElement" class="card-field-box"></div></label>
34
- <label class="card-field"><span>CVC</span><div id="cardCvcElement" class="card-field-box"></div></label>
35
- </div>
36
- <div class="billing-head"><b>账单地址</b><small>每个账号分别从地址接口自动获取</small></div>
37
- <div id="billingAutoStatus" class="billing-auto-status">等待加载卡片后自动获取,无需填写</div>
38
- <div id="cardReady" class="inline-state">请先导入账号并填写代理池,再加载安全卡片输入框</div>
39
- <button id="loadCardButton" class="secondary load-card-button" type="button">加载安全卡片输入框</button>
40
- </section>
41
-
42
- <section class="batch-section account-import-section">
43
- <div class="section-title">
44
- <div><b>导入账号</b><small>每行一个 AT;导入后输入框立即清空,账号进入下方列表</small></div>
45
- <span id="atCount" class="tag">0 条待导入</span>
46
- </div>
47
- <textarea id="accountImportInput" class="account-import-input" spellcheck="false" autocomplete="off" placeholder="每行粘贴一个 AT"></textarea>
48
- <div class="import-actions">
49
- <button id="importAtButton" type="button">导入到账号列表</button>
50
- <button id="importAtFileButton" class="secondary" type="button">从文件导入</button>
51
- <input id="atFileInput" type="file" accept=".txt,.json" hidden>
52
- </div>
53
- <div class="proxy-pool-note">导入框不保存;导入后立即分配注册项目指纹。账号、指纹、状态、错误和链接刷新后继续显示。</div>
54
- </section>
55
- </div>
56
-
57
- <section class="batch-section proxy-pool-section">
58
- <div class="section-title">
59
- <div><b>双代理池</b><small>代理池 1 只负责绑卡与支付;代理池 2 只负责提链</small></div>
60
- <span class="tag">US + 优惠地区</span>
61
- </div>
62
- <div class="dual-proxy-grid">
63
- <div class="proxy-pool-card">
64
- <div class="proxy-pool-head"><b>代理池 1</b><span id="bindProxyCount" class="tag">0 PROXY</span></div>
65
- <small>绑卡与支付:填写 US 节点</small>
66
- <textarea id="bindProxyPool" class="proxy-pool-input" spellcheck="false" autocomplete="off" placeholder="每行一个代理;支持 HTTP / HTTPS / SOCKS4 / SOCKS5"></textarea>
67
- </div>
68
- <div class="proxy-pool-card">
69
- <div class="proxy-pool-head"><b>代理池 2</b><span id="promoProxyCount" class="tag">0 PROXY</span></div>
70
- <small>优惠地区节点</small>
71
- <textarea id="promoProxyPool" class="proxy-pool-input" spellcheck="false" autocomplete="off" placeholder="每行一个代理;支持 HTTP / HTTPS / SOCKS4 / SOCKS5"></textarea>
72
- </div>
73
- </div>
74
- <div class="proxy-pool-note">协议支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H;无协议默认 HTTP。支持换行、空格、逗号或 JSON 数组,自动去重并按账号轮询分配;每池最多 500 条。</div>
75
- </section>
76
-
77
- <div class="action-row">
78
- <label class="concurrency-control"><span>并发</span><input id="batchConcurrency" type="number" min="1" max="50" value="1" inputmode="numeric"></label>
79
- <button id="validateButton" class="secondary" type="button">检查输入</button>
80
- <button id="fullFlowButton" type="button" disabled>1 提链 + 绑卡 + 提链 + 支付</button>
81
- <button id="batchBindLinkButton" class="secondary" type="button" disabled>2 提链 + 绑卡</button>
82
- <button id="linkPayButton" class="secondary" type="button" disabled>3 提链 + 支付</button>
83
- <button id="linkOnlyButton" class="secondary" type="button" disabled>4 提链</button>
84
- <button id="stopButton" class="secondary" type="button" disabled>停止</button>
85
- </div>
86
-
87
- <div class="progress-wrap">
88
- <div class="progress-meta"><span id="progressText">等待输入</span><span id="progressPercent">0%</span></div>
89
- <div class="progress-track"><i id="progressBar"></i></div>
90
- </div>
91
-
92
- <section class="batch-section result-section">
93
- <div class="section-title">
94
- <div><b>账号列表</b><small>每个账号固定一套注册指纹;状态、错误和 Checkout 链接在同一行更新</small></div>
95
- <div class="mini-actions account-list-actions">
96
- <label class="select-all-control"><input id="selectAllAccounts" type="checkbox"><span>全选</span></label>
97
- <button id="deleteSelectedButton" class="secondary small" type="button">删除选中</button>
98
- <button id="exportCsvButton" class="small export-csv-button" type="button">导出 CSV</button>
99
- <button id="clearButton" class="secondary small" type="button">清空列表</button>
100
- </div>
101
- </div>
102
- <div id="taskRows" class="task-rows"></div>
103
- <div id="accountEmpty" class="account-empty">尚未导入账号</div>
104
- </section>
105
- <div id="batchSummary" class="batch-summary" hidden></div>
106
- </section>
107
- </main>
108
- <script src="/static/direct-bind.js?v=20260804-52"></script>
109
- </body>
110
- </html>
111
-
112
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
local_checkout_bridge.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import sys
6
+ import traceback
7
+ from dataclasses import asdict
8
+ from pathlib import Path
9
+
10
+ from checkout_link_extractor import (
11
+ CheckoutExtractor,
12
+ Credentials,
13
+ ExtractorConfig,
14
+ checkout_short_url,
15
+ safe_close,
16
+ )
17
+
18
+
19
+ def safe_error_text(exc: Exception) -> str:
20
+ text = f"{type(exc).__name__}: {exc}"
21
+ text = re.sub(r"(?i)(bearer\s+)[^\s,;]+", r"\1[REDACTED]", text)
22
+ text = re.sub(r"(?i)(cookie\s*[:=]\s*)[^\r\n]+", r"\1[REDACTED]", text)
23
+ text = re.sub(r"(?<=://)[^/@\s]+:[^/@\s]+@", "[REDACTED]@", text)
24
+ text = re.sub(r"\beyJ[A-Za-z0-9_-]{16,}(?:\.[A-Za-z0-9_-]+){1,2}\b", "[REDACTED_TOKEN]", text)
25
+ return text[:1200]
26
+
27
+
28
+ def compact_trace(exc: Exception) -> list[str]:
29
+ frames = traceback.extract_tb(exc.__traceback__)[-6:]
30
+ return [f"{Path(frame.filename).name}:{frame.lineno}:{frame.name}" for frame in frames]
31
+
32
+
33
+ def main() -> int:
34
+ payload = json.loads(sys.stdin.read() or "{}")
35
+ access_token = str(payload.get("access_token") or "").strip()
36
+ entry_proxy = str(payload.get("entry_proxy") or "").strip()
37
+ exit_proxy = str(payload.get("exit_proxy") or "").strip()
38
+ if not access_token:
39
+ raise ValueError("AT_REQUIRED")
40
+ if not entry_proxy or not exit_proxy:
41
+ raise ValueError("PROXY_REQUIRED")
42
+
43
+ mode = str(payload.get("mode") or "extract").strip().lower()
44
+ extractor = CheckoutExtractor(
45
+ Credentials(
46
+ access_token=access_token,
47
+ session_cookie=str(payload.get("session_cookie") or ""),
48
+ ),
49
+ ExtractorConfig(
50
+ billing_country="PH",
51
+ currency="PHP",
52
+ payment_locale="en",
53
+ checkout_proxy_country="US",
54
+ update_proxy_country="TR",
55
+ checkout_proxy=entry_proxy,
56
+ update_proxy=exit_proxy,
57
+ checkout_attempts=10,
58
+ update_attempts=15,
59
+ full_attempts=3,
60
+ verify_proxy_country=False,
61
+ ),
62
+ logger=lambda message: print(str(message), file=sys.stderr, flush=True),
63
+ )
64
+ if mode == "initialize":
65
+ session = None
66
+ try:
67
+ session, checkout = extractor._create_checkout_with_retry(entry_proxy)
68
+ try:
69
+ extractor.last_session_cookies = {
70
+ str(name): str(value)
71
+ for name, value in dict(session.cookies.get_dict()).items()
72
+ if str(name) and str(value)
73
+ }
74
+ except Exception:
75
+ extractor.last_session_cookies = {}
76
+ extractor.last_checkout_proxy = entry_proxy
77
+ result = {
78
+ "ok": True,
79
+ "cs_id": checkout["cs_id"],
80
+ "long_url": checkout_short_url(
81
+ checkout["cs_id"],
82
+ checkout["billing_country"],
83
+ checkout.get("processor_entity") or "",
84
+ ),
85
+ "processor_entity": checkout.get("processor_entity") or "openai_llc",
86
+ "initialization_only": True,
87
+ }
88
+ finally:
89
+ safe_close(session)
90
+ else:
91
+ result = asdict(extractor.extract())
92
+ result.update(
93
+ {
94
+ "checkout_session_id": result.get("cs_id") or "",
95
+ "checkout_url": result.get("long_url") or "",
96
+ "short_link": result.get("long_url") or "",
97
+ "checkout_device_id": extractor.device_id,
98
+ "checkout_chatgpt_session_id": extractor.chatgpt_session_id,
99
+ "checkout_user_agent": extractor.config.user_agent,
100
+ "session_cookies": extractor.last_session_cookies,
101
+ "checkout_proxy": extractor.last_checkout_proxy or entry_proxy,
102
+ "source": "local_checkout_extractor",
103
+ }
104
+ )
105
+ print(json.dumps(result, ensure_ascii=True, separators=(",", ":")), flush=True)
106
+ return 0
107
+
108
+
109
+ if __name__ == "__main__":
110
+ try:
111
+ raise SystemExit(main())
112
+ except Exception as exc:
113
+ print(
114
+ json.dumps(
115
+ {
116
+ "ok": False,
117
+ "error": safe_error_text(exc),
118
+ "trace": compact_trace(exc),
119
+ },
120
+ ensure_ascii=True,
121
+ separators=(",", ":"),
122
+ ),
123
+ flush=True,
124
+ )
125
+ raise SystemExit(1)
ph_checkout_protocol.py ADDED
@@ -0,0 +1,1339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import json
6
+ import os
7
+ import random
8
+ import re
9
+ import sys
10
+ import time
11
+ import uuid
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from curl_ca_bundle import curl_session_kwargs
17
+
18
+
19
+ PAY153_ROOT = Path("/opt/pay153")
20
+ if str(PAY153_ROOT) not in sys.path:
21
+ sys.path.insert(0, str(PAY153_ROOT))
22
+
23
+ import stripe_checkout as sc # noqa: E402
24
+ from app import sentinel_headers # noqa: E402
25
+ from provider_checkout import _runtime_meta, default_billing # noqa: E402
26
+ from ph_short_extractor import ( # noqa: E402
27
+ DEFAULT_CLIENT_BUILD,
28
+ DEFAULT_CLIENT_VERSION,
29
+ DEFAULT_USER_AGENT,
30
+ )
31
+
32
+
33
+ SHORT_RE = re.compile(
34
+ r"^https://chatgpt\.com/checkout/(?P<processor>openai_ie|openai_llc)/(?P<session>(?:oaics_|cs_)[A-Za-z0-9_-]{12,})"
35
+ )
36
+
37
+
38
+ def event(kind: str, **payload: Any) -> None:
39
+ print(json.dumps({"type": kind, **payload}, ensure_ascii=True), flush=True)
40
+
41
+
42
+ def log(message: str, level: str = "info") -> None:
43
+ event("log", level=level, message=str(message or ""))
44
+
45
+
46
+ def normalize_proxy(raw: str) -> str:
47
+ value = str(raw or "").strip()
48
+ if not value:
49
+ return ""
50
+ if "://" in value:
51
+ return value
52
+ parts = value.split(":")
53
+ if len(parts) == 4:
54
+ host, port, username, password = parts
55
+ return f"http://{username}:{password}@{host}:{port}"
56
+ if len(parts) == 2:
57
+ return f"http://{value}"
58
+ return value
59
+
60
+
61
+ def build_identity_http(proxy: str, user_agent: str) -> Any:
62
+ from curl_cffi.requests import Session as CffiSession
63
+
64
+ ua = str(user_agent or DEFAULT_USER_AGENT)
65
+ impersonate = "firefox144" if "Firefox/144" in ua else "chrome136"
66
+ http = CffiSession(impersonate=impersonate, **curl_session_kwargs())
67
+ try:
68
+ http.trust_env = False
69
+ except Exception:
70
+ pass
71
+ if proxy:
72
+ http.proxies = {"http": proxy, "https": proxy}
73
+ return http
74
+
75
+
76
+ def build_stripe_http(proxy: str, user_agent: str) -> Any:
77
+ ua = str(user_agent or DEFAULT_USER_AGENT)
78
+ impersonate = "firefox144" if "Firefox/144" in ua else "chrome136"
79
+ return sc.build_http(proxy or None, impersonate=impersonate)
80
+
81
+
82
+ def install_cookies(http: Any, cookies: dict[str, Any], did: str) -> None:
83
+ for name, value in dict(cookies or {}).items():
84
+ if not str(name).strip() or not str(value):
85
+ continue
86
+ try:
87
+ http.cookies.set(str(name), str(value), domain="chatgpt.com")
88
+ except Exception:
89
+ try:
90
+ http.cookies.set(str(name), str(value))
91
+ except Exception:
92
+ pass
93
+ try:
94
+ http.cookies.set("oai-did", did, domain="chatgpt.com")
95
+ except Exception:
96
+ pass
97
+
98
+
99
+ def card_parts(raw: dict[str, Any]) -> dict[str, str]:
100
+ number = re.sub(r"\D", "", str(raw.get("number") or ""))
101
+ month = re.sub(r"\D", "", str(raw.get("exp_month") or raw.get("month") or ""))
102
+ year = re.sub(r"\D", "", str(raw.get("exp_year") or raw.get("year") or ""))
103
+ cvc = re.sub(r"\D", "", str(raw.get("cvc") or raw.get("cvv") or ""))
104
+ if len(year) == 2:
105
+ year = "20" + year
106
+ if not (12 <= len(number) <= 19 and 1 <= int(month or 0) <= 12 and len(year) == 4 and 3 <= len(cvc) <= 4):
107
+ raise ValueError("card fields are incomplete")
108
+ return {"number": number, "exp_month": str(int(month)), "exp_year": year, "cvc": cvc}
109
+
110
+
111
+ def chatgpt_headers(
112
+ payload: dict[str, Any],
113
+ device_id: str,
114
+ processor: str,
115
+ session_id: str,
116
+ path: str,
117
+ extra: dict[str, str] | None = None,
118
+ ) -> dict[str, str]:
119
+ headers = {
120
+ "Authorization": f"Bearer {str(payload.get('access_token') or '').strip()}",
121
+ "Accept": "*/*",
122
+ "Origin": "https://chatgpt.com",
123
+ "Referer": f"https://chatgpt.com/checkout/{processor}/{session_id}",
124
+ "OAI-Device-Id": device_id,
125
+ "OAI-Language": "en-US",
126
+ "User-Agent": str(payload.get("user_agent") or DEFAULT_USER_AGENT),
127
+ "Accept-Language": "en-US,en;q=0.9",
128
+ "OAI-Client-Version": DEFAULT_CLIENT_VERSION,
129
+ "OAI-Client-Build-Number": DEFAULT_CLIENT_BUILD,
130
+ "x-openai-target-path": path,
131
+ "x-openai-target-route": path,
132
+ }
133
+ checkout_trace_id = str(payload.get("checkout_chatgpt_session_id") or "").strip()
134
+ if checkout_trace_id:
135
+ headers["OAI-Session-Id"] = checkout_trace_id
136
+ account_id = str(payload.get("chatgpt_account_id") or "").strip()
137
+ if account_id:
138
+ headers["ChatGPT-Account-Id"] = account_id
139
+ if extra:
140
+ headers.update(extra)
141
+ return headers
142
+
143
+
144
+ def response_json(response: Any, label: str) -> dict[str, Any]:
145
+ text = str(getattr(response, "text", "") or "")
146
+ try:
147
+ data = response.json() or {}
148
+ except Exception as exc:
149
+ raise RuntimeError(f"{label} returned non-JSON HTTP {getattr(response, 'status_code', '?')}: {text[:400]}") from exc
150
+ if not isinstance(data, dict):
151
+ raise RuntimeError(f"{label} returned an invalid response")
152
+ return data
153
+
154
+
155
+ def api_error(data: dict[str, Any]) -> str:
156
+ error = data.get("error")
157
+ if isinstance(error, dict):
158
+ return str(error.get("message") or error.get("code") or error.get("type") or "")
159
+ return str(error or data.get("detail") or data.get("message") or "")
160
+
161
+
162
+ def _checkout_string(data: Any, keys: tuple[str, ...], prefix: str = "") -> str:
163
+ """Find a checkout scalar through shallow provider response wrappers."""
164
+ stack: list[tuple[Any, int]] = [(data, 0)]
165
+ visited: set[int] = set()
166
+ while stack and len(visited) < 5000:
167
+ current, depth = stack.pop()
168
+ if not isinstance(current, (dict, list)):
169
+ continue
170
+ identity = id(current)
171
+ if identity in visited:
172
+ continue
173
+ visited.add(identity)
174
+ if isinstance(current, dict):
175
+ for key in keys:
176
+ value = current.get(key)
177
+ if isinstance(value, str) and value.strip() and (not prefix or value.startswith(prefix)):
178
+ return value.strip()
179
+ if depth < 32:
180
+ stack.extend((value, depth + 1) for value in reversed(list(current.values())))
181
+ elif depth < 32:
182
+ stack.extend((value, depth + 1) for value in reversed(current))
183
+ return ""
184
+
185
+
186
+ def _checkout_methods(data: Any) -> list[str]:
187
+ stack: list[tuple[Any, int]] = [(data, 0)]
188
+ visited: set[int] = set()
189
+ while stack and len(visited) < 5000:
190
+ current, depth = stack.pop()
191
+ if not isinstance(current, (dict, list)):
192
+ continue
193
+ identity = id(current)
194
+ if identity in visited:
195
+ continue
196
+ visited.add(identity)
197
+ if isinstance(current, dict):
198
+ methods = current.get("payment_method_types") or current.get("paymentMethodTypes")
199
+ if isinstance(methods, list):
200
+ values = [str(item).lower().strip() for item in methods if str(item).strip()]
201
+ if values:
202
+ return values
203
+ if depth < 32:
204
+ stack.extend((value, depth + 1) for value in reversed(list(current.values())))
205
+ elif depth < 32:
206
+ stack.extend((value, depth + 1) for value in reversed(current))
207
+ return []
208
+
209
+
210
+ def stripe_error_detail(data: dict[str, Any]) -> str:
211
+ error = data.get("error") if isinstance(data.get("error"), dict) else {}
212
+ intent = error.get("payment_intent") or error.get("setup_intent") or {}
213
+ last_error = intent.get("last_payment_error") or intent.get("last_setup_error") or {}
214
+ parts: list[str] = []
215
+ for label, value in (
216
+ ("message", error.get("message") or last_error.get("message")),
217
+ ("code", error.get("code") or last_error.get("code")),
218
+ ("decline_code", error.get("decline_code") or last_error.get("decline_code")),
219
+ ("network_decline_code", error.get("network_decline_code") or last_error.get("network_decline_code")),
220
+ ("advice_code", error.get("advice_code") or last_error.get("advice_code")),
221
+ ):
222
+ text = str(value or "").strip()
223
+ if text and f"{label}={text}" not in parts:
224
+ parts.append(f"{label}={text}")
225
+ return "; ".join(parts) or api_error(data)
226
+
227
+
228
+ def resolve_oaics_checkout(
229
+ http: Any,
230
+ payload: dict[str, Any],
231
+ processor: str,
232
+ session_id: str,
233
+ device_id: str,
234
+ ) -> dict[str, Any]:
235
+ path = f"/backend-api/payments/checkout/{processor}/{session_id}"
236
+ response = http.get(
237
+ f"https://chatgpt.com{path}",
238
+ headers=chatgpt_headers(payload, device_id, processor, session_id, path),
239
+ timeout=45,
240
+ )
241
+ data = response_json(response, "OAICS Checkout")
242
+ if getattr(response, "status_code", 0) != 200:
243
+ raise RuntimeError(f"OAICS Checkout HTTP {getattr(response, 'status_code', '?')}: {api_error(data) or str(data)[:300]}")
244
+ resolved_id = _checkout_string(
245
+ data,
246
+ ("checkout_session_id", "checkoutSessionId", "session_id", "sessionId", "id"),
247
+ prefix=("cs_", "oaics_"),
248
+ )
249
+ pk = _checkout_string(data, ("publishable_key", "publishableKey", "stripe_publishable_key", "public_key"), "pk_")
250
+ customer_secret = _checkout_string(
251
+ data,
252
+ ("customer_session_client_secret", "customerSessionClientSecret", "client_secret", "clientSecret"),
253
+ "cuss_secret_",
254
+ )
255
+ methods = _checkout_methods(data)
256
+ missing: list[str] = []
257
+ if not resolved_id:
258
+ missing.append("checkout_session_id")
259
+ elif resolved_id != session_id:
260
+ missing.append("checkout_session_id_match")
261
+ if not pk:
262
+ missing.append("publishable_key")
263
+ if not customer_secret:
264
+ missing.append("customer_session_client_secret")
265
+ if not methods:
266
+ missing.append("payment_method_types")
267
+ if missing:
268
+ raise RuntimeError("OAICS_CHECKOUT_INCOMPLETE: missing=" + ",".join(missing))
269
+ if "card" not in methods:
270
+ raise RuntimeError(f"Checkout does not expose card; methods={methods}")
271
+ return data
272
+
273
+
274
+ def oaics_total(state: dict[str, Any]) -> tuple[int, str]:
275
+ checkout_state = state.get("checkout_state") if isinstance(state.get("checkout_state"), dict) else {}
276
+ total = checkout_state.get("total") if isinstance(checkout_state.get("total"), dict) else {}
277
+ final_total = total.get("total") if isinstance(total.get("total"), dict) else {}
278
+ amount = final_total.get("minorUnitsAmount")
279
+ if amount is None:
280
+ amount = 0
281
+ return int(amount), str(checkout_state.get("currency") or "php").lower()
282
+
283
+
284
+ def fetch_deferred_elements(
285
+ http: Any,
286
+ state: dict[str, Any],
287
+ session_id: str,
288
+ user_agent: str = DEFAULT_USER_AGENT,
289
+ ) -> dict[str, Any]:
290
+ pk = str(state.get("publishable_key") or "")
291
+ amount, currency = oaics_total(state)
292
+ methods = [str(item).lower() for item in (state.get("payment_method_types") or [])]
293
+ stripe_js_id = str(uuid.uuid4())
294
+ params: dict[str, Any] = {
295
+ "customer_session_client_secret": state.get("customer_session_client_secret"),
296
+ "client_betas[0]": "custom_checkout_server_updates_1",
297
+ "client_betas[1]": "custom_checkout_manual_approval_1",
298
+ "deferred_intent[mode]": "subscription",
299
+ "deferred_intent[amount]": str(amount),
300
+ "deferred_intent[currency]": currency,
301
+ "currency": currency,
302
+ "key": pk,
303
+ "elements_init_source": "stripe.elements",
304
+ "referrer_host": "chatgpt.com",
305
+ "stripe_js_id": stripe_js_id,
306
+ "locale": "en-PH",
307
+ "type": "deferred_intent",
308
+ }
309
+ # Official custom Checkout keeps mode=subscription even when amount=0.
310
+ # The zero-due branch later becomes a SetupIntent, but Elements is still
311
+ # initialized as a subscription with an explicit zero amount.
312
+ params["deferred_intent[setup_future_usage]"] = "off_session"
313
+ for index, method in enumerate(methods):
314
+ params[f"deferred_intent[payment_method_types][{index}]"] = method
315
+ response = http.get(
316
+ f"{sc.STRIPE_API}/v1/elements/sessions",
317
+ params=params,
318
+ headers={
319
+ "User-Agent": str(user_agent or DEFAULT_USER_AGENT),
320
+ "Accept": "application/json",
321
+ "Authorization": f"Bearer {pk}",
322
+ "Origin": "https://js.stripe.com",
323
+ "Referer": "https://js.stripe.com/",
324
+ },
325
+ timeout=45,
326
+ )
327
+ data = response_json(response, "Stripe Elements session")
328
+ if getattr(response, "status_code", 0) != 200:
329
+ raise RuntimeError(f"Stripe Elements session HTTP {getattr(response, 'status_code', '?')}: {api_error(data) or str(data)[:300]}")
330
+ elements_session_id = str(data.get("session_id") or "")
331
+ config_id = str(data.get("config_id") or "")
332
+ if not elements_session_id:
333
+ raise RuntimeError("Stripe Elements session did not return session_id")
334
+ def find_customer_id(value: Any) -> str:
335
+ if isinstance(value, str) and value.startswith("cus_"):
336
+ return value
337
+ if isinstance(value, dict):
338
+ for child in value.values():
339
+ found = find_customer_id(child)
340
+ if found:
341
+ return found
342
+ elif isinstance(value, list):
343
+ for child in value:
344
+ found = find_customer_id(child)
345
+ if found:
346
+ return found
347
+ return ""
348
+ customer_id = find_customer_id(data.get("customer")) or find_customer_id(data)
349
+ customer_payload = data.get("customer") if isinstance(data.get("customer"), dict) else {}
350
+ customer_session = customer_payload.get("customer_session") if isinstance(customer_payload.get("customer_session"), dict) else {}
351
+ customer_session_api_key = str(customer_session.get("api_key") or "")
352
+ customer_payment_method_ids = []
353
+ for item in customer_payload.get("payment_methods") or []:
354
+ if isinstance(item, dict):
355
+ payment_method_id = str(item.get("id") or "")
356
+ if payment_method_id.startswith("pm_") and payment_method_id not in customer_payment_method_ids:
357
+ customer_payment_method_ids.append(payment_method_id)
358
+ return {
359
+ "elements_session_id": elements_session_id,
360
+ "elements_session_config_id": config_id,
361
+ "config_id": config_id,
362
+ "stripe_js_id": stripe_js_id,
363
+ "currency": currency,
364
+ "checkout_amount": amount,
365
+ "payment_method_types": methods,
366
+ "runtime_version": sc.DEFAULT_STRIPE_RUNTIME_VERSION,
367
+ "customer_session_client_secret": str(state.get("customer_session_client_secret") or ""),
368
+ "customer_id": customer_id,
369
+ "customer_session_api_key": customer_session_api_key,
370
+ "customer_payment_method_ids": customer_payment_method_ids,
371
+ }
372
+
373
+
374
+ def submit_checkout_taxes(
375
+ http: Any,
376
+ payload: dict[str, Any],
377
+ processor: str,
378
+ session_id: str,
379
+ device_id: str,
380
+ billing: dict[str, Any],
381
+ currency: str,
382
+ ) -> dict[str, Any]:
383
+ address = dict(billing.get("address") or {})
384
+ clean_address = {
385
+ "country": str(address.get("country") or "PH").upper(),
386
+ "line1": str(address.get("line1") or ""),
387
+ "line2": str(address.get("line2") or ""),
388
+ "city": str(address.get("city") or ""),
389
+ "state": str(address.get("state") or ""),
390
+ "postal_code": str(address.get("postal_code") or ""),
391
+ }
392
+ path = "/backend-api/payments/checkout/taxes"
393
+ response = http.post(
394
+ f"https://chatgpt.com{path}",
395
+ json={
396
+ "checkout_session_id": session_id,
397
+ "checkout_email": str(billing.get("email") or ""),
398
+ "billing_country": "PH",
399
+ "billing_name": str(billing.get("name") or ""),
400
+ "currency": str(currency or "PHP").upper(),
401
+ "tax_id": None,
402
+ "processor_entity": processor,
403
+ "billing_address": clean_address,
404
+ },
405
+ headers=chatgpt_headers(
406
+ payload, device_id, processor, session_id, path,
407
+ {"Content-Type": "application/json"},
408
+ ),
409
+ timeout=50,
410
+ )
411
+ result = response_json(response, "OpenAI Checkout taxes")
412
+ if getattr(response, "status_code", 0) != 200:
413
+ raise RuntimeError(
414
+ f"OpenAI Checkout taxes HTTP {getattr(response, 'status_code', '?')}: "
415
+ f"{api_error(result) or str(result)[:350]}"
416
+ )
417
+ checkout = result.get("checkout_session")
418
+ return checkout if isinstance(checkout, dict) else {}
419
+
420
+
421
+ def snapshot_billing(
422
+ http: Any,
423
+ payload: dict[str, Any],
424
+ processor: str,
425
+ session_id: str,
426
+ device_id: str,
427
+ billing: dict[str, Any],
428
+ ) -> None:
429
+ address = billing.get("address") or {}
430
+ body = {
431
+ "snapshot": {
432
+ "billing_address": {
433
+ "name": billing.get("name", ""),
434
+ "address": {
435
+ "line1": address.get("line1", ""),
436
+ "line2": address.get("line2", ""),
437
+ "city": address.get("city", ""),
438
+ "country": address.get("country", "PH"),
439
+ "postal_code": address.get("postal_code", ""),
440
+ "state": address.get("state", ""),
441
+ },
442
+ }
443
+ }
444
+ }
445
+ path = "/backend-api/payments/checkout/snapshot"
446
+ try:
447
+ response = http.post(
448
+ f"https://chatgpt.com{path}",
449
+ json=body,
450
+ headers=chatgpt_headers(
451
+ payload, device_id, processor, session_id, path, {"Content-Type": "application/json"}
452
+ ),
453
+ timeout=30,
454
+ )
455
+ log(f"OAICS billing snapshot HTTP {getattr(response, 'status_code', '?')}")
456
+ except Exception as exc:
457
+ log(f"OAICS billing snapshot skipped: {type(exc).__name__}", "warn")
458
+
459
+
460
+ def update_saved_payment_method_billing(
461
+ http: Any,
462
+ pk: str,
463
+ payment_method_id: str,
464
+ billing: dict[str, Any],
465
+ elements_context: dict[str, Any] | None = None,
466
+ user_agent: str = DEFAULT_USER_AGENT,
467
+ ) -> dict[str, Any]:
468
+ if not re.fullmatch(r"pm_[A-Za-z0-9]+", str(payment_method_id or "")):
469
+ raise ValueError("saved PaymentMethod ID is invalid")
470
+ context = dict(elements_context or {})
471
+ customer_api_key = str(context.get("customer_session_api_key") or "")
472
+ authorization_key = customer_api_key if customer_api_key.startswith("ek_") else pk
473
+ address = dict(billing.get("address") or {})
474
+ data = {
475
+ "billing_details[name]": str(billing.get("name") or ""),
476
+ "billing_details[email]": str(billing.get("email") or ""),
477
+ "billing_details[phone]": str(billing.get("phone") or ""),
478
+ "billing_details[address][line1]": str(address.get("line1") or ""),
479
+ "billing_details[address][line2]": str(address.get("line2") or ""),
480
+ "billing_details[address][city]": str(address.get("city") or ""),
481
+ "billing_details[address][state]": str(address.get("state") or ""),
482
+ "billing_details[address][postal_code]": str(address.get("postal_code") or ""),
483
+ "billing_details[address][country]": str(address.get("country") or "PH").upper(),
484
+ "key": pk,
485
+ }
486
+ response = http.post(
487
+ f"{sc.STRIPE_API}/v1/payment_methods/{payment_method_id}",
488
+ data={key: value for key, value in data.items() if value not in (None, "")},
489
+ headers={
490
+ "User-Agent": str(user_agent or DEFAULT_USER_AGENT),
491
+ "Accept": "application/json",
492
+ "Authorization": f"Bearer {authorization_key}",
493
+ "Origin": "https://js.stripe.com",
494
+ "Referer": "https://js.stripe.com/",
495
+ "Stripe-Version": "2020-08-27",
496
+ },
497
+ timeout=40,
498
+ )
499
+ result = response_json(response, "Stripe saved PaymentMethod billing update")
500
+ if getattr(response, "status_code", 0) != 200:
501
+ raise RuntimeError(
502
+ f"Stripe saved PaymentMethod billing update HTTP {getattr(response, 'status_code', '?')}: "
503
+ f"{api_error(result) or str(result)[:300]}"
504
+ )
505
+ if str(result.get("id") or payment_method_id) != payment_method_id:
506
+ raise RuntimeError("Stripe saved PaymentMethod billing update returned a mismatched ID")
507
+ return result
508
+
509
+
510
+ def create_card_payment_method(
511
+ http: Any,
512
+ pk: str,
513
+ session_id: str,
514
+ ctx: dict[str, Any],
515
+ billing: dict[str, Any],
516
+ card: dict[str, str],
517
+ ) -> str:
518
+ common, attr = _runtime_meta(ctx, session_id)
519
+ address = billing.get("address") or {}
520
+ data = {
521
+ "type": "card",
522
+ "card[number]": card["number"],
523
+ "card[cvc]": card["cvc"],
524
+ "card[exp_month]": card["exp_month"],
525
+ "card[exp_year]": card["exp_year"],
526
+ "billing_details[name]": billing.get("name", ""),
527
+ "billing_details[email]": billing.get("email", ""),
528
+ "billing_details[address][country]": address.get("country", "PH"),
529
+ "billing_details[address][line1]": address.get("line1", ""),
530
+ "billing_details[address][line2]": address.get("line2", ""),
531
+ "billing_details[address][city]": address.get("city", ""),
532
+ "billing_details[address][postal_code]": address.get("postal_code", ""),
533
+ "billing_details[address][state]": address.get("state", ""),
534
+ "payment_user_agent": (
535
+ f"stripe.js/{common['runtime_version']}; stripe-js-v3/{common['runtime_version']}; "
536
+ "payment-element; deferred-intent"
537
+ ),
538
+ "referrer": "https://chatgpt.com",
539
+ "time_on_page": str(random.randint(18000, 52000)),
540
+ "guid": common["guid"],
541
+ "muid": common["muid"],
542
+ "sid": common["sid"],
543
+ "key": pk,
544
+ "_stripe_version": sc.STRIPE_VERSION_FULL,
545
+ "client_attribution_metadata[client_session_id]": attr["client_session_id"],
546
+ "client_attribution_metadata[checkout_session_id]": attr["checkout_session_id"],
547
+ "client_attribution_metadata[checkout_config_id]": attr["checkout_config_id"],
548
+ "client_attribution_metadata[elements_session_id]": attr["elements_session_id"],
549
+ "client_attribution_metadata[elements_session_config_id]": attr["elements_session_config_id"],
550
+ "client_attribution_metadata[merchant_integration_source]": "elements",
551
+ "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
552
+ "client_attribution_metadata[merchant_integration_version]": "2021",
553
+ "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
554
+ "client_attribution_metadata[payment_method_selection_flow]": "automatic",
555
+ }
556
+ data = {key: value for key, value in data.items() if value not in (None, "")}
557
+ response = http.post(
558
+ f"{sc.STRIPE_API}/v1/payment_methods",
559
+ data=data,
560
+ headers=sc._stripe_headers(),
561
+ timeout=40,
562
+ )
563
+ result = response_json(response, "Card PaymentMethod")
564
+ if getattr(response, "status_code", 0) != 200:
565
+ raise RuntimeError(f"Card PaymentMethod HTTP {getattr(response, 'status_code', '?')}: {api_error(result) or str(result)[:300]}")
566
+ payment_method_id = str(result.get("id") or "")
567
+ if not payment_method_id.startswith("pm_"):
568
+ raise RuntimeError("Card PaymentMethod did not return pm_id")
569
+ return payment_method_id
570
+
571
+
572
+ def create_confirmation_token(
573
+ http: Any,
574
+ pk: str,
575
+ payment_method_id: str,
576
+ return_url: str,
577
+ *,
578
+ setup_only: bool = False,
579
+ customer_session_client_secret: str = "",
580
+ elements_context: dict[str, Any] | None = None,
581
+ user_agent: str = DEFAULT_USER_AGENT,
582
+ ) -> str:
583
+ data = {
584
+ "payment_method": payment_method_id,
585
+ "key": pk,
586
+ }
587
+ # Both the OpenAI-created PaymentIntent and the ConfirmationToken must
588
+ # declare identical future usage. For paid Checkout this only saves the
589
+ # method after a successful charge; it does not pre-attach the card.
590
+ data["setup_future_usage"] = "off_session"
591
+ if return_url:
592
+ data["return_url"] = return_url
593
+ context = dict(elements_context or {})
594
+ currency = str(context.get("currency") or "php").lower()
595
+ methods = [str(item).lower() for item in (context.get("payment_method_types") or ["card"])]
596
+ data["client_context[currency]"] = currency
597
+ data["client_context[mode]"] = "subscription"
598
+ for index, method in enumerate(methods):
599
+ data[f"client_context[payment_method_types][{index}]"] = method
600
+ customer_id = str(context.get("customer_id") or "")
601
+ if customer_id.startswith("cus_"):
602
+ data["client_context[customer]"] = customer_id
603
+ data.update({
604
+ "client_attribution_metadata[client_session_id]": str(context.get("stripe_js_id") or uuid.uuid4()),
605
+ "client_attribution_metadata[merchant_integration_source]": "elements",
606
+ "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
607
+ "client_attribution_metadata[merchant_integration_version]": "2021",
608
+ "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
609
+ "client_attribution_metadata[payment_method_selection_flow]": "merchant_specified",
610
+ "client_attribution_metadata[elements_session_id]": str(context.get("elements_session_id") or ""),
611
+ "client_attribution_metadata[elements_session_config_id]": str(context.get("elements_session_config_id") or ""),
612
+ "client_attribution_metadata[merchant_integration_additional_elements][0]": "expressCheckout",
613
+ "client_attribution_metadata[merchant_integration_additional_elements][1]": "payment",
614
+ "client_attribution_metadata[merchant_integration_additional_elements][2]": "address",
615
+ "set_as_default_payment_method": "false",
616
+ })
617
+ data = {key: value for key, value in data.items() if value not in (None, "")}
618
+ customer_api_key = str(context.get("customer_session_api_key") or "")
619
+ authorization_key = customer_api_key if customer_api_key.startswith("ek_") else pk
620
+ response = http.post(
621
+ f"{sc.STRIPE_API}/v1/confirmation_tokens",
622
+ data=data,
623
+ headers={
624
+ "User-Agent": str(user_agent or DEFAULT_USER_AGENT),
625
+ "Accept": "application/json",
626
+ "Authorization": f"Bearer {authorization_key}",
627
+ "Origin": "https://js.stripe.com",
628
+ "Referer": "https://js.stripe.com/",
629
+ "Stripe-Version": "2020-08-27",
630
+ },
631
+ timeout=40,
632
+ )
633
+ result = response_json(response, "Stripe ConfirmationToken")
634
+ if getattr(response, "status_code", 0) != 200:
635
+ raise RuntimeError(f"Stripe ConfirmationToken HTTP {getattr(response, 'status_code', '?')}: {api_error(result) or str(result)[:300]}")
636
+ token_id = str(result.get("id") or "")
637
+ if not token_id.startswith("ctoken_"):
638
+ raise RuntimeError("Stripe ConfirmationToken did not return ctoken_id")
639
+ return token_id
640
+
641
+
642
+ def confirm_openai_checkout(
643
+ http: Any,
644
+ payload: dict[str, Any],
645
+ processor: str,
646
+ session_id: str,
647
+ device_id: str,
648
+ did: str,
649
+ proxy: str,
650
+ confirmation_token: str,
651
+ ) -> dict[str, Any]:
652
+ path = "/backend-api/payments/checkout/confirm"
653
+ sentinel = asyncio.run(sentinel_headers(proxy, "checkout_session_approval", device_id, did))
654
+ response = http.post(
655
+ f"https://chatgpt.com{path}",
656
+ json={
657
+ "checkout_session_id": session_id,
658
+ "confirm_token": confirmation_token,
659
+ "selected_payment_method_type": "card",
660
+ },
661
+ headers=chatgpt_headers(
662
+ payload,
663
+ device_id,
664
+ processor,
665
+ session_id,
666
+ path,
667
+ {"Content-Type": "application/json", **sentinel},
668
+ ),
669
+ timeout=60,
670
+ )
671
+ result = response_json(response, "OpenAI Checkout confirm")
672
+ if getattr(response, "status_code", 0) != 200:
673
+ raise RuntimeError(f"OpenAI Checkout confirm HTTP {getattr(response, 'status_code', '?')}: {api_error(result) or str(result)[:350]}")
674
+ if api_error(result):
675
+ raise RuntimeError(f"OpenAI Checkout confirm: {api_error(result)}")
676
+ intent_type = str(result.get("type") or "")
677
+ client_secret = str(result.get("client_secret") or "")
678
+ if intent_type not in {"setup_intent", "payment_intent"} or "_secret_" not in client_secret:
679
+ status = str(result.get("status") or "unknown").lower()
680
+ log(f"OpenAI Checkout confirm returned status={status} without client_secret", "warn")
681
+ return result
682
+
683
+
684
+ def approve_oaics_checkout(
685
+ http: Any,
686
+ payload: dict[str, Any],
687
+ processor: str,
688
+ session_id: str,
689
+ device_id: str,
690
+ did: str,
691
+ proxy: str,
692
+ ) -> dict[str, Any]:
693
+ path = "/backend-api/payments/checkout/approve"
694
+ sentinel = asyncio.run(sentinel_headers(proxy, "checkout_session_approval", device_id, did))
695
+ response = http.post(
696
+ f"https://chatgpt.com{path}",
697
+ json={"checkout_session_id": session_id, "processor_entity": processor},
698
+ headers=chatgpt_headers(
699
+ payload,
700
+ device_id,
701
+ processor,
702
+ session_id,
703
+ path,
704
+ {"Content-Type": "application/json", **sentinel},
705
+ ),
706
+ timeout=50,
707
+ )
708
+ result = response_json(response, "OpenAI Checkout approval")
709
+ if getattr(response, "status_code", 0) != 200:
710
+ raise RuntimeError(f"OpenAI Checkout approval HTTP {getattr(response, 'status_code', '?')}: {api_error(result) or str(result)[:300]}")
711
+ approval = str(result.get("result") or "").lower()
712
+ if approval and approval != "approved":
713
+ raise RuntimeError(f"OpenAI Checkout approval result={approval}")
714
+ return result
715
+
716
+
717
+ def intent_parts(intent_type: str, client_secret: str) -> tuple[str, str]:
718
+ expected = "seti_" if intent_type == "setup_intent" else "pi_"
719
+ intent_id = client_secret.split("_secret_", 1)[0]
720
+ if not intent_id.startswith(expected):
721
+ raise RuntimeError("Stripe intent client secret does not match the returned type")
722
+ plural = "setup_intents" if intent_type == "setup_intent" else "payment_intents"
723
+ return intent_id, plural
724
+
725
+
726
+ def confirm_stripe_intent(
727
+ http: Any,
728
+ pk: str,
729
+ intent_type: str,
730
+ client_secret: str,
731
+ confirmation_token: str,
732
+ return_url: str,
733
+ ) -> dict[str, Any]:
734
+ intent_id, plural = intent_parts(intent_type, client_secret)
735
+ data = {
736
+ "client_secret": client_secret,
737
+ "confirmation_token": confirmation_token,
738
+ "use_stripe_sdk": "true",
739
+ "key": pk,
740
+ "_stripe_version": sc.STRIPE_VERSION_FULL,
741
+ "client_attribution_metadata[merchant_integration_source]": "l1",
742
+ }
743
+ # PH paid short links use payment-first semantics. Stripe only attaches the
744
+ # successful PaymentMethod to the Checkout customer after the charge has
745
+ # succeeded. A zero-due SetupIntent remains a bind-only operation.
746
+ if intent_type == "payment_intent":
747
+ data["setup_future_usage"] = "off_session"
748
+ if return_url:
749
+ data["return_url"] = return_url
750
+ response = http.post(
751
+ f"{sc.STRIPE_API}/v1/{plural}/{intent_id}/confirm",
752
+ data=data,
753
+ headers=sc._stripe_headers(),
754
+ timeout=60,
755
+ )
756
+ result = response_json(response, "Stripe intent confirm")
757
+ if getattr(response, "status_code", 0) != 200:
758
+ raise RuntimeError(
759
+ f"Stripe intent confirm HTTP {getattr(response, 'status_code', '?')}: "
760
+ f"{stripe_error_detail(result) or str(result)[:350]}"
761
+ )
762
+ return result
763
+
764
+
765
+ def retrieve_stripe_intent(http: Any, pk: str, intent_type: str, client_secret: str) -> dict[str, Any]:
766
+ intent_id, plural = intent_parts(intent_type, client_secret)
767
+ response = http.get(
768
+ f"{sc.STRIPE_API}/v1/{plural}/{intent_id}",
769
+ params={"client_secret": client_secret, "key": pk, "_stripe_version": sc.STRIPE_VERSION_FULL},
770
+ headers=sc._stripe_headers(),
771
+ timeout=40,
772
+ )
773
+ result = response_json(response, "Stripe intent retrieve")
774
+ if getattr(response, "status_code", 0) != 200:
775
+ raise RuntimeError(f"Stripe intent retrieve HTTP {getattr(response, 'status_code', '?')}: {api_error(result) or str(result)[:300]}")
776
+ return result
777
+
778
+
779
+ def post_payment_binding_state(intent_type: str, intent: dict[str, Any]) -> dict[str, Any]:
780
+ status = str(intent.get("status") or "").lower()
781
+ payment_method = intent.get("payment_method")
782
+ if isinstance(payment_method, dict):
783
+ payment_method = payment_method.get("id")
784
+ customer = intent.get("customer")
785
+ if isinstance(customer, dict):
786
+ customer = customer.get("id")
787
+ if intent_type != "payment_intent":
788
+ return {
789
+ "payment_first": False,
790
+ "card_binding_mode": "setup_only",
791
+ "card_binding_status": "completed" if status == "succeeded" else status or "pending",
792
+ }
793
+ confirmed = bool(status == "succeeded" and str(payment_method or "").startswith("pm_") and customer)
794
+ return {
795
+ "payment_first": True,
796
+ "card_binding_mode": "after_payment",
797
+ "card_binding_status": "confirmed" if confirmed else (
798
+ "requested_after_payment" if status == "succeeded" else "waiting_for_payment"
799
+ ),
800
+ }
801
+
802
+
803
+ def next_action_payload(data: dict[str, Any]) -> dict[str, Any]:
804
+ action = data.get("next_action") if isinstance(data.get("next_action"), dict) else sc._find_next_action(data)
805
+ if not action:
806
+ return {}
807
+ redirect = action.get("redirect_to_url") if isinstance(action.get("redirect_to_url"), dict) else {}
808
+ return {
809
+ "type": str(action.get("type") or ""),
810
+ "redirect_url": str(redirect.get("url") or ""),
811
+ "use_stripe_sdk": action.get("use_stripe_sdk") or {},
812
+ }
813
+
814
+
815
+ def finalize_return(
816
+ http: Any,
817
+ payload: dict[str, Any],
818
+ processor: str,
819
+ session_id: str,
820
+ device_id: str,
821
+ return_url: str,
822
+ ) -> int | None:
823
+ if not return_url:
824
+ return None
825
+ try:
826
+ response = http.get(
827
+ return_url,
828
+ headers=chatgpt_headers(payload, device_id, processor, session_id, "/checkout/verify"),
829
+ allow_redirects=True,
830
+ timeout=45,
831
+ )
832
+ return getattr(response, "status_code", None)
833
+ except Exception as exc:
834
+ log(f"Checkout return URL follow-up skipped: {type(exc).__name__}", "warn")
835
+ return None
836
+
837
+
838
+ def subscription_summary(value: Any) -> dict[str, Any]:
839
+ record: dict[str, Any] = {}
840
+ if isinstance(value, dict):
841
+ if "plan_type" in value:
842
+ record = value
843
+ else:
844
+ for key in ("subscription", "active_subscription", "data"):
845
+ candidate = value.get(key)
846
+ if isinstance(candidate, dict) and "plan_type" in candidate:
847
+ record = candidate
848
+ break
849
+ if isinstance(candidate, list):
850
+ record = next((item for item in candidate if isinstance(item, dict) and "plan_type" in item), {})
851
+ if record:
852
+ break
853
+ elif isinstance(value, list):
854
+ record = next((item for item in value if isinstance(item, dict) and "plan_type" in item), {})
855
+
856
+ def flag(name: str) -> bool:
857
+ raw = record.get(name)
858
+ if isinstance(raw, bool):
859
+ return raw
860
+ return str(raw or "").strip().lower() in {"1", "true", "yes"}
861
+
862
+ plan_type = str(record.get("plan_type") or "").lower()
863
+ is_processor_stripe = flag("is_processor_stripe")
864
+ is_delinquent = flag("is_delinquent")
865
+ verified = bool(plan_type == "plus" and is_processor_stripe and not is_delinquent)
866
+ return {
867
+ "verified": verified,
868
+ "verification_state": "plus" if verified else "unknown",
869
+ "attempts_used": 0,
870
+ "http_status": None,
871
+ "checked_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
872
+ "plan_type": plan_type,
873
+ "billing_period": str(record.get("billing_period") or "").lower(),
874
+ "billing_currency": str(record.get("billing_currency") or "").upper(),
875
+ "will_renew": flag("will_renew"),
876
+ "is_processor_stripe": is_processor_stripe,
877
+ "is_delinquent": is_delinquent,
878
+ }
879
+
880
+
881
+ def verify_subscription_state(
882
+ http: Any,
883
+ payload: dict[str, Any],
884
+ processor: str,
885
+ session_id: str,
886
+ device_id: str,
887
+ attempts: int | None = None,
888
+ delay_seconds: float | None = None,
889
+ ) -> dict[str, Any]:
890
+ def env_attempts() -> int:
891
+ try:
892
+ return max(1, int(os.environ.get("PLUS_VERIFY_ATTEMPTS", "15")))
893
+ except (TypeError, ValueError):
894
+ return 15
895
+
896
+ def env_delay() -> float:
897
+ try:
898
+ return max(0.0, float(os.environ.get("PLUS_VERIFY_DELAY_SECONDS", "2")))
899
+ except (TypeError, ValueError):
900
+ return 2.0
901
+
902
+ attempt_limit = max(1, int(attempts)) if attempts is not None else env_attempts()
903
+ retry_delay = max(0.0, float(delay_seconds)) if delay_seconds is not None else env_delay()
904
+ path = "/backend-api/subscriptions"
905
+ last = subscription_summary({})
906
+ account_id = str(payload.get("chatgpt_account_id") or "").strip()
907
+ if not account_id:
908
+ last.update(
909
+ verification_state="unknown",
910
+ error="SUBSCRIPTION_ACCOUNT_ID_MISSING",
911
+ checked_at=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
912
+ )
913
+ log("Subscription state could not be checked without an account ID", "warn")
914
+ return last
915
+ last_status: int | None = None
916
+ all_attempts_valid_free = True
917
+ attempts_used = 0
918
+ for attempt in range(1, attempt_limit + 1):
919
+ attempts_used = attempt
920
+ last_status = None
921
+ try:
922
+ response = http.get(
923
+ f"https://chatgpt.com{path}",
924
+ params={"account_id": account_id},
925
+ headers=chatgpt_headers(payload, device_id, processor, session_id, path),
926
+ timeout=40,
927
+ )
928
+ last_status = int(getattr(response, "status_code", 0) or 0)
929
+ if last_status == 200:
930
+ last = subscription_summary(response_json(response, "ChatGPT subscriptions"))
931
+ if last.get("verified"):
932
+ last.update(
933
+ verification_state="plus",
934
+ attempts_used=attempt,
935
+ http_status=last_status,
936
+ checked_at=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
937
+ )
938
+ log(
939
+ "Subscription verified: "
940
+ f"plan={last.get('plan_type')} period={last.get('billing_period')} "
941
+ f"currency={last.get('billing_currency')}"
942
+ )
943
+ return last
944
+ if last.get("plan_type") != "free":
945
+ all_attempts_valid_free = False
946
+ else:
947
+ all_attempts_valid_free = False
948
+ except Exception as exc:
949
+ all_attempts_valid_free = False
950
+ last = subscription_summary({})
951
+ log(f"Subscription verification attempt {attempt} skipped: {type(exc).__name__}", "warn")
952
+ if attempt < attempt_limit and retry_delay:
953
+ time.sleep(retry_delay)
954
+ last.update(
955
+ verified=False,
956
+ verification_state="not_plus" if all_attempts_valid_free else "unknown",
957
+ attempts_used=attempts_used,
958
+ http_status=last_status,
959
+ checked_at=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
960
+ )
961
+ if last["verification_state"] == "not_plus":
962
+ log("Subscription remained on the valid Free state after all verification attempts", "warn")
963
+ else:
964
+ log("Subscription state could not be determined after payment", "warn")
965
+ return last
966
+
967
+
968
+ def verification_result(
969
+ attempt: int,
970
+ session_id: str,
971
+ processor: str,
972
+ pk: str,
973
+ intent_type: str,
974
+ client_secret: str,
975
+ action: dict[str, Any],
976
+ amount: int,
977
+ currency: str,
978
+ ) -> dict[str, Any]:
979
+ return {
980
+ "status": "verification_required",
981
+ "attempt": attempt,
982
+ "checkout_session_id": session_id,
983
+ "processor_entity": processor,
984
+ "stripe_publishable_key": pk,
985
+ "intent_type": intent_type,
986
+ "intent_client_secret": client_secret,
987
+ "next_action": action,
988
+ "checkout_amount": amount,
989
+ "checkout_currency": currency.upper(),
990
+ }
991
+
992
+
993
+ def attempt_payment(payload: dict[str, Any], raw_card: dict[str, Any], attempt: int) -> dict[str, Any]:
994
+ short_url = str(payload.get("short_url") or "").strip()
995
+ match = SHORT_RE.match(short_url)
996
+ if not match:
997
+ raise ValueError("PH Checkout URL format is invalid")
998
+ access_token = str(payload.get("access_token") or "").strip()
999
+ if not access_token:
1000
+ raise ValueError("ChatGPT access token is missing")
1001
+ payment_proxy = normalize_proxy(str(payload.get("proxy") or ""))
1002
+ processor = str(payload.get("processor_entity") or match.group("processor"))
1003
+ session_id = str(payload.get("checkout_session_id") or match.group("session"))
1004
+ email = str(payload.get("email") or "").strip()
1005
+ provided_confirmation_token = str(payload.get("confirmation_token") or "").strip()
1006
+ if provided_confirmation_token and not re.fullmatch(r"ctoken_[A-Za-z0-9]+", provided_confirmation_token):
1007
+ raise ValueError("ConfirmationToken ID is invalid")
1008
+ saved_payment_method_id = str(
1009
+ payload.get("saved_payment_method_id")
1010
+ or raw_card.get("saved_payment_method_id")
1011
+ or ""
1012
+ ).strip()
1013
+ if saved_payment_method_id and not re.fullmatch(r"pm_[A-Za-z0-9]+", saved_payment_method_id):
1014
+ raise ValueError("saved PaymentMethod ID is invalid")
1015
+ card = {} if (provided_confirmation_token or saved_payment_method_id) else card_parts(raw_card)
1016
+ session_cookies = dict(payload.get("session_cookies") or {})
1017
+ cookie_device_id = str(session_cookies.get("oai-did") or "").strip()
1018
+ device_id = str(payload.get("checkout_device_id") or cookie_device_id or uuid.uuid4())
1019
+ did = device_id
1020
+ payload = dict(payload)
1021
+ payload["checkout_device_id"] = device_id
1022
+ payload["checkout_chatgpt_session_id"] = str(payload.get("checkout_chatgpt_session_id") or uuid.uuid4())
1023
+ payload["user_agent"] = str(payload.get("user_agent") or DEFAULT_USER_AGENT)
1024
+
1025
+ chatgpt_http = build_identity_http(payment_proxy, payload["user_agent"])
1026
+ stripe_http = build_stripe_http(payment_proxy, payload["user_agent"])
1027
+ install_cookies(chatgpt_http, session_cookies, device_id)
1028
+ log("Checkout identity restored: original OAI device/cookie and matching HTTP fingerprint")
1029
+ prepared_state = payload.get("prepared_checkout_state") if isinstance(payload.get("prepared_checkout_state"), dict) else {}
1030
+ if provided_confirmation_token and prepared_state:
1031
+ state = dict(prepared_state)
1032
+ pk = str(state.get("publishable_key") or "")
1033
+ amount = int(payload.get("prepared_amount") if payload.get("prepared_amount") is not None else oaics_total(state)[0])
1034
+ currency = str(payload.get("prepared_currency") or oaics_total(state)[1]).lower()
1035
+ log(f"Attempt {attempt}: reuse immutable prepared OAICS context")
1036
+ else:
1037
+ log(f"Attempt {attempt}: resolve OAICS Checkout")
1038
+ state = resolve_oaics_checkout(chatgpt_http, payload, processor, session_id, device_id)
1039
+ pk = str(state.get("publishable_key") or "")
1040
+ amount, currency = oaics_total(state)
1041
+ log(f"OAICS session resolved: amount={amount} currency={currency.upper()}")
1042
+
1043
+ billing = default_billing("PH", email, real_random=True)
1044
+ if saved_payment_method_id or provided_confirmation_token:
1045
+ log("Prepared/saved PaymentMethod flow: preserve the original Checkout billing and CustomerSession")
1046
+ else:
1047
+ tax_state = submit_checkout_taxes(
1048
+ chatgpt_http, payload, processor, session_id, device_id, billing, currency
1049
+ )
1050
+ if tax_state:
1051
+ state = {**state, **tax_state}
1052
+ pk = str(state.get("publishable_key") or pk)
1053
+ amount, currency = oaics_total(state)
1054
+ log(f"PH billing taxes submitted: amount={amount} currency={currency.upper()}")
1055
+ snapshot_billing(chatgpt_http, payload, processor, session_id, device_id, billing)
1056
+ refreshed_state = resolve_oaics_checkout(
1057
+ chatgpt_http, payload, processor, session_id, device_id
1058
+ )
1059
+ if refreshed_state:
1060
+ state = {**state, **refreshed_state}
1061
+ pk = str(state.get("publishable_key") or pk)
1062
+ amount, currency = oaics_total(state)
1063
+ log("OAICS Checkout refreshed after billing snapshot")
1064
+
1065
+ prepared_ctx = payload.get("prepared_elements_context") if isinstance(payload.get("prepared_elements_context"), dict) else {}
1066
+ if provided_confirmation_token and prepared_ctx:
1067
+ ctx = dict(prepared_ctx)
1068
+ log("Reusing the exact Elements/CustomerSession context that minted the ConfirmationToken")
1069
+ else:
1070
+ ctx = fetch_deferred_elements(stripe_http, state, session_id, payload["user_agent"])
1071
+ log("Stripe deferred Elements session initialized")
1072
+ ctx["billing"] = billing
1073
+
1074
+ return_url = str(state.get("confirm_return_url") or "")
1075
+ setup_only = amount == 0
1076
+ if provided_confirmation_token:
1077
+ confirmation_token = provided_confirmation_token
1078
+ log(f"Attempt {attempt}: using prepared ConfirmationToken from the locked Elements context")
1079
+ else:
1080
+ if saved_payment_method_id:
1081
+ payment_method_id = saved_payment_method_id
1082
+ log(f"Attempt {attempt}: using the account saved PaymentMethod")
1083
+ else:
1084
+ payment_method_id = create_card_payment_method(stripe_http, pk, session_id, ctx, billing, card)
1085
+ log(f"Attempt {attempt}: card PaymentMethod created (unattached)")
1086
+ confirmation_token = create_confirmation_token(
1087
+ stripe_http, pk, payment_method_id, return_url, setup_only=setup_only,
1088
+ customer_session_client_secret=str(ctx.get("customer_session_client_secret") or ""),
1089
+ elements_context=ctx,
1090
+ user_agent=payload["user_agent"],
1091
+ )
1092
+ if setup_only:
1093
+ log("Zero-due Checkout: SetupIntent binding ConfirmationToken created")
1094
+ else:
1095
+ log("Paid Checkout: post-payment-save ConfirmationToken created")
1096
+
1097
+ preconfirmed_checkout = payload.get("preconfirmed_checkout") or {}
1098
+ if isinstance(preconfirmed_checkout, dict) and preconfirmed_checkout:
1099
+ checkout_confirm = dict(preconfirmed_checkout)
1100
+ log("Using Checkout confirm result produced by the official headless page")
1101
+ else:
1102
+ checkout_confirm = confirm_openai_checkout(
1103
+ chatgpt_http, payload, processor, session_id, device_id, did, payment_proxy, confirmation_token
1104
+ )
1105
+ intent_type = str(checkout_confirm.get("type") or "")
1106
+ client_secret = str(checkout_confirm.get("client_secret") or "")
1107
+ return_url = str(checkout_confirm.get("confirm_return_url") or return_url)
1108
+ confirm_status = str(checkout_confirm.get("status") or "").lower()
1109
+ if not client_secret:
1110
+ if confirm_status in {"blocked", "error", "expired", "failed"}:
1111
+ mode = "ZERO_DUE_SETUP" if amount == 0 else "PAID_CHECKOUT"
1112
+ raise RuntimeError(
1113
+ f"OPENAI_CONFIRM_{confirm_status.upper()}: mode={mode}; "
1114
+ "request was blocked before Stripe intent creation; this is not an issuer card decline"
1115
+ )
1116
+ if confirm_status in {"requires_approval", "pending", "requires_confirmation", "open", "success", "succeeded"}:
1117
+ log(f"OpenAI Checkout status={confirm_status}; submit approval and retry confirm")
1118
+ approve_oaics_checkout(chatgpt_http, payload, processor, session_id, device_id, did, payment_proxy)
1119
+ checkout_confirm = confirm_openai_checkout(
1120
+ chatgpt_http, payload, processor, session_id, device_id, did, payment_proxy, confirmation_token
1121
+ )
1122
+ intent_type = str(checkout_confirm.get("type") or "")
1123
+ client_secret = str(checkout_confirm.get("client_secret") or "")
1124
+ return_url = str(checkout_confirm.get("confirm_return_url") or return_url)
1125
+ confirm_status = str(checkout_confirm.get("status") or "").lower()
1126
+ if not client_secret:
1127
+ refreshed = resolve_oaics_checkout(chatgpt_http, payload, processor, session_id, device_id)
1128
+ if str(refreshed.get("payment_status") or "").lower() == "paid":
1129
+ return_status = finalize_return(chatgpt_http, payload, processor, session_id, device_id, return_url)
1130
+ subscription = verify_subscription_state(
1131
+ chatgpt_http, payload, processor, session_id, device_id
1132
+ )
1133
+ return {
1134
+ "status": "success" if subscription.get("verified") else "pending_verification",
1135
+ "attempt": attempt,
1136
+ "checkout_session_id": session_id,
1137
+ "processor_entity": processor,
1138
+ "checkout_amount": amount,
1139
+ "checkout_currency": currency.upper(),
1140
+ "intent_type": "server_confirmed",
1141
+ "intent_status": str(refreshed.get("payment_status") or "paid"),
1142
+ "return_http_status": return_status,
1143
+ "subscription": subscription,
1144
+ }
1145
+ raise RuntimeError(
1146
+ f"OpenAI Checkout confirm status={confirm_status or 'unknown'} without payment client secret"
1147
+ )
1148
+ log(f"OpenAI Checkout confirm returned {intent_type}")
1149
+
1150
+ intent = confirm_stripe_intent(
1151
+ stripe_http, pk, intent_type, client_secret, confirmation_token, return_url
1152
+ )
1153
+ status = str(intent.get("status") or "")
1154
+ action = next_action_payload(intent)
1155
+ log(f"Stripe {intent_type} status={status or '-'}")
1156
+ if action:
1157
+ return verification_result(
1158
+ attempt, session_id, processor, pk, intent_type, client_secret, action, amount, currency
1159
+ )
1160
+
1161
+ if bool(state.get("requires_manual_approval")) and status not in {"succeeded", "processing"}:
1162
+ log(f"Attempt {attempt}: submit ChatGPT Checkout approval")
1163
+ approve_oaics_checkout(chatgpt_http, payload, processor, session_id, device_id, did, payment_proxy)
1164
+ try:
1165
+ intent = confirm_stripe_intent(
1166
+ stripe_http, pk, intent_type, client_secret, confirmation_token, return_url
1167
+ )
1168
+ except Exception as exc:
1169
+ log(f"Second Stripe confirm returned {type(exc).__name__}; retrieving intent", "warn")
1170
+ intent = retrieve_stripe_intent(stripe_http, pk, intent_type, client_secret)
1171
+ status = str(intent.get("status") or "")
1172
+ action = next_action_payload(intent)
1173
+ log(f"Stripe {intent_type} after approval status={status or '-'}")
1174
+ if action:
1175
+ return verification_result(
1176
+ attempt, session_id, processor, pk, intent_type, client_secret, action, amount, currency
1177
+ )
1178
+
1179
+ if status not in {"succeeded", "processing"}:
1180
+ decline = intent.get("last_setup_error") or intent.get("last_payment_error") or {}
1181
+ detail = api_error(intent) or str(decline.get("message") or decline.get("code") or status or "unknown")
1182
+ raise RuntimeError(f"Stripe {intent_type} did not complete: {detail}")
1183
+
1184
+ if intent_type == "payment_intent" and status == "succeeded":
1185
+ log("Payment succeeded; checking post-payment card attachment")
1186
+ try:
1187
+ intent = retrieve_stripe_intent(stripe_http, pk, intent_type, client_secret)
1188
+ status = str(intent.get("status") or status)
1189
+ except Exception as exc:
1190
+ log(f"Post-payment attachment check skipped: {type(exc).__name__}", "warn")
1191
+ binding = post_payment_binding_state(intent_type, intent)
1192
+ return_status = finalize_return(chatgpt_http, payload, processor, session_id, device_id, return_url)
1193
+ subscription = verify_subscription_state(
1194
+ chatgpt_http, payload, processor, session_id, device_id
1195
+ )
1196
+ if binding.get("payment_first"):
1197
+ log(f"Post-payment card binding status={binding.get('card_binding_status')}")
1198
+ return {
1199
+ "status": "success" if subscription.get("verified") else "pending_verification",
1200
+ "attempt": attempt,
1201
+ "checkout_session_id": session_id,
1202
+ "processor_entity": processor,
1203
+ "checkout_amount": amount,
1204
+ "checkout_currency": currency.upper(),
1205
+ "intent_type": intent_type,
1206
+ "intent_status": status,
1207
+ "return_http_status": return_status,
1208
+ "subscription": subscription,
1209
+ **binding,
1210
+ }
1211
+
1212
+
1213
+ def run(payload: dict[str, Any]) -> dict[str, Any]:
1214
+ if str(payload.get("mode") or "").lower() == "resume":
1215
+ session_id = str(payload.get("checkout_session_id") or "").strip()
1216
+ pk = str(payload.get("stripe_publishable_key") or "").strip()
1217
+ intent_type = str(payload.get("intent_type") or "").strip()
1218
+ client_secret = str(payload.get("intent_client_secret") or "").strip()
1219
+ if not session_id or not pk or intent_type not in {"setup_intent", "payment_intent"} or not client_secret:
1220
+ raise ValueError("resume context is incomplete")
1221
+ proxy = normalize_proxy(str(payload.get("proxy") or ""))
1222
+ http = sc.build_http(proxy or None)
1223
+ resume_cookies = dict(payload.get("session_cookies") or {})
1224
+ resume_device_id = str(payload.get("checkout_device_id") or resume_cookies.get("oai-did") or uuid.uuid4())
1225
+ install_cookies(http, resume_cookies, resume_device_id)
1226
+ log("Verification completed; retrieving the original Stripe intent")
1227
+ intent = retrieve_stripe_intent(http, pk, intent_type, client_secret)
1228
+ status = str(intent.get("status") or "")
1229
+ action = next_action_payload(intent)
1230
+ if action or status in {"requires_action", "requires_payment_method", "requires_confirmation"}:
1231
+ return {
1232
+ "status": "verification_required",
1233
+ "checkout_session_id": session_id,
1234
+ "stripe_publishable_key": pk,
1235
+ "intent_type": intent_type,
1236
+ "intent_client_secret": client_secret,
1237
+ "next_action": action,
1238
+ }
1239
+ if status not in {"succeeded", "processing"}:
1240
+ raise RuntimeError(f"Stripe intent status={status or 'unknown'}")
1241
+ binding = post_payment_binding_state(intent_type, intent)
1242
+ if binding.get("payment_first"):
1243
+ log(f"Post-payment card binding status={binding.get('card_binding_status')}")
1244
+ return {
1245
+ "status": "success",
1246
+ "checkout_session_id": session_id,
1247
+ "intent_type": intent_type,
1248
+ "intent_status": status,
1249
+ **binding,
1250
+ }
1251
+
1252
+ provided_confirmation_token = str(payload.get("confirmation_token") or "").strip()
1253
+ if provided_confirmation_token and not re.fullmatch(r"ctoken_[A-Za-z0-9]+", provided_confirmation_token):
1254
+ raise ValueError("ConfirmationToken ID is invalid")
1255
+ saved_payment_method_id = str(payload.get("saved_payment_method_id") or "").strip()
1256
+ if saved_payment_method_id and not re.fullmatch(r"pm_[A-Za-z0-9]+", saved_payment_method_id):
1257
+ raise ValueError("saved PaymentMethod ID is invalid")
1258
+ cards = payload.get("cards") if isinstance(payload.get("cards"), list) else []
1259
+ if provided_confirmation_token and not cards:
1260
+ cards = [{}]
1261
+ elif saved_payment_method_id and not cards:
1262
+ cards = [{"saved_payment_method_id": saved_payment_method_id}]
1263
+ if not cards:
1264
+ raise ValueError("at least one card, saved PaymentMethod, or ConfirmationToken is required")
1265
+ raw_proxies = payload.get("proxies") if isinstance(payload.get("proxies"), list) else []
1266
+ proxies: list[str] = []
1267
+ for value in [*raw_proxies, payload.get("proxy")]:
1268
+ normalized = normalize_proxy(str(value or ""))
1269
+ if normalized and normalized not in proxies:
1270
+ proxies.append(normalized)
1271
+ if not proxies:
1272
+ raise ValueError("at least one payment proxy is required")
1273
+ try:
1274
+ card_retry_count = int(payload.get("card_retry_count", 2))
1275
+ except (TypeError, ValueError):
1276
+ card_retry_count = 2
1277
+ card_retry_count = max(0, min(10, card_retry_count))
1278
+ try:
1279
+ card_retry_delay = float(payload.get("card_retry_delay", 1))
1280
+ except (TypeError, ValueError):
1281
+ card_retry_delay = 1.0
1282
+ card_retry_delay = max(1.0, min(10.0, card_retry_delay))
1283
+ last_error = ""
1284
+ protocol_attempt = 0
1285
+ for proxy_index, proxy in enumerate(proxies, 1):
1286
+ log(f"Payment route {proxy_index}/{len(proxies)} selected")
1287
+ proxy_payload = dict(payload)
1288
+ proxy_payload["proxy"] = proxy
1289
+ switch_proxy = False
1290
+ for card_index, raw_card in enumerate(cards, 1):
1291
+ for retry_index in range(card_retry_count + 1):
1292
+ protocol_attempt += 1
1293
+ log(
1294
+ f"Card {card_index}/{len(cards)} submission "
1295
+ f"{retry_index + 1}/{card_retry_count + 1}"
1296
+ )
1297
+ try:
1298
+ result = attempt_payment(proxy_payload, dict(raw_card or {}), protocol_attempt)
1299
+ if result.get("status") in {"success", "verification_required", "pending_verification"}:
1300
+ result["card_index"] = card_index
1301
+ result["card_submission"] = retry_index + 1
1302
+ result["proxy_attempt"] = proxy_index
1303
+ return result
1304
+ except Exception as exc:
1305
+ last_error = f"{type(exc).__name__}: {exc}"
1306
+ log(
1307
+ f"Card {card_index} submission {retry_index + 1} failed: {last_error}",
1308
+ "warn",
1309
+ )
1310
+ if "OPENAI_CONFIRM_BLOCKED" in last_error:
1311
+ switch_proxy = True
1312
+ if proxy_index < len(proxies):
1313
+ log("OpenAI confirm blocked; switching to the next US payment route", "warn")
1314
+ break
1315
+ if retry_index < card_retry_count:
1316
+ log(f"Retrying the same card in {card_retry_delay:g} second(s)")
1317
+ time.sleep(card_retry_delay)
1318
+ if switch_proxy:
1319
+ break
1320
+ if switch_proxy:
1321
+ continue
1322
+ if last_error.startswith("RuntimeError: "):
1323
+ last_error = last_error[len("RuntimeError: "):]
1324
+ raise RuntimeError(last_error or "all card/proxy attempts failed")
1325
+
1326
+
1327
+ def main() -> int:
1328
+ try:
1329
+ payload = json.loads(sys.stdin.read() or "{}")
1330
+ result = run(payload)
1331
+ event("result", result=result)
1332
+ return 0
1333
+ except Exception as exc:
1334
+ event("error", error=f"{type(exc).__name__}: {exc}")
1335
+ return 1
1336
+
1337
+
1338
+ if __name__ == "__main__":
1339
+ raise SystemExit(main())
ph_short_extractor.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """Client identity constants shared by the protocol checkout worker."""
2
+
3
+ from checkout_link_extractor import (
4
+ DEFAULT_CLIENT_BUILD,
5
+ DEFAULT_CLIENT_VERSION,
6
+ DEFAULT_USER_AGENT,
7
+ )
8
+
9
+ __all__ = ["DEFAULT_CLIENT_BUILD", "DEFAULT_CLIENT_VERSION", "DEFAULT_USER_AGENT"]
provider_checkout.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Provider metadata and billing compatibility helpers for protocol checkout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import uuid
8
+ from typing import Any
9
+
10
+
11
+ def _runtime_meta(context: dict[str, Any] | None, session_id: str) -> tuple[dict[str, str], dict[str, str]]:
12
+ context = dict(context or {})
13
+ runtime = str(context.get("runtime_version") or "3")
14
+ common = {
15
+ "runtime_version": runtime,
16
+ "guid": str(context.get("guid") or uuid.uuid4()),
17
+ "muid": str(context.get("muid") or uuid.uuid4()),
18
+ "sid": str(context.get("sid") or uuid.uuid4()),
19
+ }
20
+ attributes = {
21
+ "client_session_id": str(context.get("stripe_js_id") or uuid.uuid4()),
22
+ "checkout_session_id": str(context.get("checkout_session_id") or session_id),
23
+ "checkout_config_id": str(context.get("elements_session_config_id") or context.get("config_id") or ""),
24
+ "elements_session_id": str(context.get("elements_session_id") or ""),
25
+ "elements_session_config_id": str(context.get("elements_session_config_id") or context.get("config_id") or ""),
26
+ }
27
+ return common, attributes
28
+
29
+
30
+ def _billing_name(email: str) -> str:
31
+ local = re.sub(r"[^A-Za-z ]+", " ", str(email or "").split("@", 1)[0])
32
+ words = [word.capitalize() for word in local.split() if word]
33
+ return " ".join(words[:3]) or "Checkout Customer"
34
+
35
+
36
+ def default_billing(country: str = "PH", email: str = "", *, real_random: bool = False) -> dict[str, Any]:
37
+ country = str(country or "PH").upper()
38
+ if country != "PH":
39
+ raise ValueError("provider billing country must be PH")
40
+ return {
41
+ "name": os.getenv("PH_BILLING_NAME", "").strip() or _billing_name(email),
42
+ "email": str(email or "").strip(),
43
+ "phone": os.getenv("PH_BILLING_PHONE", "+6325550100").strip(),
44
+ "address": {
45
+ "country": "PH",
46
+ "line1": os.getenv("PH_BILLING_LINE1", "Ayala Avenue").strip(),
47
+ "line2": os.getenv("PH_BILLING_LINE2", "").strip(),
48
+ "city": os.getenv("PH_BILLING_CITY", "Makati").strip(),
49
+ "state": os.getenv("PH_BILLING_STATE", "Metro Manila").strip(),
50
+ "postal_code": os.getenv("PH_BILLING_POSTAL_CODE", "1226").strip(),
51
+ },
52
+ }
proxy_preflight.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ from concurrent.futures import ThreadPoolExecutor, as_completed
6
+ from urllib.parse import urlsplit, urlunsplit
7
+
8
+ from curl_ca_bundle import curl_session_kwargs
9
+
10
+ try:
11
+ from curl_cffi.requests import Session as CurlSession
12
+ except Exception: # pragma: no cover - exercised only in a minimal install
13
+ CurlSession = None
14
+
15
+ try:
16
+ import requests
17
+ except Exception: # pragma: no cover - exercised only in a minimal install
18
+ requests = None
19
+
20
+
21
+ TRACE = "https://www.cloudflare.com/cdn-cgi/trace"
22
+
23
+
24
+ def _redact_proxy(proxy: str) -> str:
25
+ """Keep diagnostics useful without echoing proxy credentials."""
26
+ try:
27
+ parsed = urlsplit(str(proxy))
28
+ if not parsed.scheme or not parsed.netloc:
29
+ return str(proxy)
30
+ host = parsed.hostname or ""
31
+ if parsed.port:
32
+ host = f"{host}:{parsed.port}"
33
+ return urlunsplit((parsed.scheme, host, parsed.path, parsed.query, parsed.fragment))
34
+ except Exception:
35
+ return "<proxy>"
36
+
37
+
38
+ def _redact_error(error: str, proxy: str) -> str:
39
+ message = str(error or "")
40
+ return message.replace(str(proxy or ""), _redact_proxy(proxy))[:240]
41
+
42
+
43
+ def _country(response) -> str:
44
+ text = str(getattr(response, "text", "") or "").strip()
45
+ fields = {
46
+ line.split("=", 1)[0].strip().lower(): line.split("=", 1)[1].strip()
47
+ for line in text.splitlines()
48
+ if "=" in line
49
+ }
50
+ value = fields.get("loc") or fields.get("country") or fields.get("countrycode")
51
+ if value:
52
+ return str(value).upper()[:8]
53
+ try:
54
+ body = response.json()
55
+ except Exception:
56
+ body = None
57
+ if isinstance(body, dict):
58
+ value = body.get("country_code") or body.get("countryCode") or body.get("country")
59
+ if value:
60
+ return str(value).upper()[:8]
61
+ # A few country endpoints return a bare ISO code.
62
+ if len(text) <= 8 and text.isalpha():
63
+ return text.upper()
64
+ return ""
65
+
66
+
67
+ def _probe_client(proxy: str, client_name: str):
68
+ session = None
69
+ try:
70
+ if client_name.startswith("curl_"):
71
+ if CurlSession is None:
72
+ raise RuntimeError("curl_cffi unavailable")
73
+ session = CurlSession(
74
+ impersonate=client_name.removeprefix("curl_"),
75
+ **curl_session_kwargs(),
76
+ )
77
+ else:
78
+ if requests is None:
79
+ raise RuntimeError("requests unavailable")
80
+ session = requests.Session()
81
+ session.trust_env = False
82
+ session.proxies = {"http": proxy, "https": proxy}
83
+ response = session.get(TRACE, timeout=(8, 12))
84
+ status = int(getattr(response, "status_code", 0) or 0)
85
+ country = _country(response) if status == 200 else ""
86
+ return {"transport": client_name, "status": status, "country": country}
87
+ except Exception as exc:
88
+ return {"transport": client_name, "status": 0, "country": "", "error": str(exc)[:240]}
89
+ finally:
90
+ try:
91
+ if session is not None:
92
+ session.close()
93
+ except Exception:
94
+ pass
95
+
96
+
97
+ def check(proxy, expected):
98
+ proxy = str(proxy or "").strip()
99
+ expected = str(expected or "US").upper()
100
+ attempts = []
101
+ for client_name in ("curl_firefox144", "curl_chrome146", "requests_openssl"):
102
+ result = _probe_client(proxy, client_name)
103
+ attempts.append(result)
104
+ if result.get("country") == expected:
105
+ return {
106
+ "proxy": proxy,
107
+ "state": "match",
108
+ "country": expected,
109
+ "transport": result.get("transport"),
110
+ "attempts": attempts,
111
+ }
112
+ countries = [str(item.get("country") or "") for item in attempts if item.get("country")]
113
+ mismatch = next((value for value in countries if value != expected), "")
114
+ return {
115
+ "proxy": proxy,
116
+ "state": "mismatch" if mismatch else "inconclusive",
117
+ "country": mismatch,
118
+ "attempts": attempts,
119
+ }
120
+
121
+
122
+ def validate(values, expected, limit=30):
123
+ source = []
124
+ for item in values:
125
+ value = str(item or "").strip()
126
+ if value and value not in source:
127
+ source.append(value)
128
+ source = source[:100]
129
+ results = []
130
+ with ThreadPoolExecutor(max_workers=min(24, max(1, len(source)))) as pool:
131
+ futures = {pool.submit(check, proxy, expected): proxy for proxy in source}
132
+ for future in as_completed(futures):
133
+ try:
134
+ results.append(future.result())
135
+ except Exception as exc:
136
+ results.append({"proxy": futures[future], "state": "inconclusive", "error": str(exc)[:240], "attempts": []})
137
+ valid = [item["proxy"] for item in results if item.get("state") == "match"][:limit]
138
+ inconclusive = [item["proxy"] for item in results if item.get("state") == "inconclusive"][:limit]
139
+ mismatch = [item["proxy"] for item in results if item.get("state") == "mismatch"]
140
+ diagnostics = []
141
+ for item in results:
142
+ attempts = []
143
+ for attempt in item.get("attempts") or []:
144
+ safe_attempt = dict(attempt)
145
+ if safe_attempt.get("error"):
146
+ safe_attempt["error"] = _redact_error(safe_attempt["error"], item.get("proxy") or "")
147
+ attempts.append(safe_attempt)
148
+ diagnostics.append({
149
+ "proxy": _redact_proxy(item.get("proxy") or ""),
150
+ "state": item.get("state"),
151
+ "country": item.get("country") or "",
152
+ "attempts": attempts,
153
+ })
154
+ return valid, len(source), inconclusive, mismatch, diagnostics
155
+
156
+
157
+ def main():
158
+ data = json.loads(sys.stdin.read() or "{}")
159
+ if "proxies" in data:
160
+ expected = str(data.get("expected") or "US").upper()
161
+ limit = max(1, min(30, int(data.get("limit") or 3)))
162
+ valid, total, inconclusive, mismatch, diagnostics = validate(data.get("proxies") or [], expected, limit)
163
+ result = {
164
+ "ok": bool(valid), "proxies": valid, "expected": expected, "total": total,
165
+ "valid": len(valid), "inconclusive": inconclusive, "mismatch": mismatch,
166
+ "diagnostics": diagnostics,
167
+ }
168
+ print(json.dumps(result))
169
+ return 0 if valid else 2
170
+ entry, entry_total, entry_inconclusive, entry_mismatch, entry_diag = validate(data.get("entry") or [], "US")
171
+ exit, exit_total, exit_inconclusive, exit_mismatch, exit_diag = validate(data.get("exit") or [], "TR")
172
+ result = {
173
+ "ok": bool(entry and exit), "entry": entry, "exit": exit,
174
+ "entry_total": entry_total, "exit_total": exit_total,
175
+ "entry_valid": len(entry), "exit_valid": len(exit),
176
+ "entry_inconclusive": entry_inconclusive, "exit_inconclusive": exit_inconclusive,
177
+ "entry_mismatch": entry_mismatch, "exit_mismatch": exit_mismatch,
178
+ "entry_diagnostics": entry_diag, "exit_diagnostics": exit_diag,
179
+ }
180
+ print(json.dumps(result))
181
+ return 0 if entry and exit else 2
182
+
183
+
184
+ if __name__ == "__main__":
185
+ raise SystemExit(main())
remote_browser.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import os
5
+ import queue
6
+ import re
7
+ import subprocess
8
+ import threading
9
+ import time
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import unquote, urlsplit
14
+
15
+
16
+ _DISPLAY_COUNTER = itertools.count(220)
17
+ _DISPLAY_LOCK = threading.Lock()
18
+ _BROWSER_LIMIT = max(1, min(int(os.getenv("PH_PORTAL_BROWSER_LIMIT", "2") or 2), 4))
19
+ _BROWSER_SEMAPHORE = threading.BoundedSemaphore(_BROWSER_LIMIT)
20
+ _CHECKOUT_RE = re.compile(r"^https://chatgpt\.com/checkout/(?:openai_ie|openai_llc)/[^/?#]+")
21
+ _SESSION_COOKIE_NAMES = {
22
+ "__Secure-next-auth.session-token",
23
+ "next-auth.session-token",
24
+ "__Secure-authjs.session-token",
25
+ "authjs.session-token",
26
+ "oai-did",
27
+ "_account",
28
+ "_account_is_fedramp",
29
+ "__Secure-oai-is",
30
+ "auth_provider",
31
+ "oai-client-auth-session",
32
+ "unified_session_manifest",
33
+ "oaicom-stable-id",
34
+ "oai-sc",
35
+ }
36
+
37
+
38
+ def playwright_proxy(raw: str) -> dict[str, str] | None:
39
+ value = str(raw or "").strip()
40
+ if not value or value.upper() == "DIRECT":
41
+ return None
42
+ if "://" not in value:
43
+ value = f"http://{value}"
44
+ parsed = urlsplit(value)
45
+ if not parsed.hostname or not parsed.port:
46
+ raise ValueError("账号代理格式不正确")
47
+ result = {"server": f"{parsed.scheme or 'http'}://{parsed.hostname}:{parsed.port}"}
48
+ if parsed.username:
49
+ result["username"] = unquote(parsed.username)
50
+ if parsed.password:
51
+ result["password"] = unquote(parsed.password)
52
+ return result
53
+
54
+
55
+ @dataclass
56
+ class RemoteBrowserState:
57
+ ready: bool = False
58
+ done: bool = False
59
+ error: str = ""
60
+ message: str = "正在启动临时 Chromium…"
61
+ current_url: str = ""
62
+ checkout_url: str = ""
63
+
64
+
65
+ class RemoteBrowserController:
66
+ """Render one isolated Chromium context and reuse a stored ChatGPT session."""
67
+
68
+ def __init__(
69
+ self,
70
+ *,
71
+ start_url: str,
72
+ executable_path: str = "/usr/bin/chromium",
73
+ viewport_width: int = 1280,
74
+ viewport_height: int = 800,
75
+ locale: str = "en-PH",
76
+ timezone_id: str = "Asia/Manila",
77
+ session_cookies: dict[str, str] | None = None,
78
+ session_token: str = "",
79
+ access_token: str = "",
80
+ chatgpt_account_id: str = "",
81
+ proxy: str = "",
82
+ user_agent: str = "",
83
+ ) -> None:
84
+ self.start_url = start_url
85
+ self.executable_path = executable_path
86
+ self.viewport_width = viewport_width
87
+ self.viewport_height = viewport_height
88
+ self.locale = locale
89
+ self.timezone_id = timezone_id
90
+ self.session_cookies = dict(session_cookies or {})
91
+ self.session_token = str(session_token or "").strip()
92
+ self.access_token = str(access_token or "").strip()
93
+ self.chatgpt_account_id = str(chatgpt_account_id or "").strip()
94
+ self.proxy = str(proxy or "").strip()
95
+ self.user_agent = str(user_agent or "").strip()
96
+ self._lock = threading.RLock()
97
+ self._state = RemoteBrowserState()
98
+ self._frame = b""
99
+ self._commands: queue.Queue[dict[str, Any]] = queue.Queue(maxsize=100)
100
+ self._stop_event = threading.Event()
101
+ self._thread: threading.Thread | None = None
102
+
103
+ def start(self) -> None:
104
+ if self._thread and self._thread.is_alive():
105
+ return
106
+ self._thread = threading.Thread(target=self._run, name="ph-short-remote-browser", daemon=True)
107
+ self._thread.start()
108
+
109
+ def stop(self) -> None:
110
+ self._stop_event.set()
111
+ try:
112
+ self._commands.put_nowait({"type": "stop"})
113
+ except queue.Full:
114
+ pass
115
+
116
+ def state(self) -> RemoteBrowserState:
117
+ with self._lock:
118
+ return RemoteBrowserState(**self._state.__dict__)
119
+
120
+ def frame(self) -> bytes:
121
+ with self._lock:
122
+ return bytes(self._frame)
123
+
124
+ def action(self, payload: dict[str, Any]) -> None:
125
+ action_type = str(payload.get("type") or "").strip().lower()
126
+ if action_type not in {"click", "text", "key", "reload", "scroll"}:
127
+ raise ValueError("不支持的浏览器操作")
128
+ command = dict(payload)
129
+ command["type"] = action_type
130
+ try:
131
+ self._commands.put_nowait(command)
132
+ except queue.Full as exc:
133
+ raise ValueError("浏览器操作队列已满") from exc
134
+
135
+ def _set_state(self, **values: Any) -> None:
136
+ with self._lock:
137
+ for key, value in values.items():
138
+ setattr(self._state, key, value)
139
+
140
+ @staticmethod
141
+ def _next_display() -> int:
142
+ with _DISPLAY_LOCK:
143
+ for _ in range(100):
144
+ number = next(_DISPLAY_COUNTER)
145
+ if not Path(f"/tmp/.X{number}-lock").exists():
146
+ return number
147
+ raise RuntimeError("没有可用的临时显示编号")
148
+
149
+ def _cookie_payload(self) -> list[dict[str, Any]]:
150
+ values = {
151
+ str(name): str(value)
152
+ for name, value in self.session_cookies.items()
153
+ if str(name) in _SESSION_COOKIE_NAMES and str(value)
154
+ }
155
+ if self.session_token:
156
+ values.setdefault("__Secure-next-auth.session-token", self.session_token)
157
+ return [
158
+ {
159
+ "name": name,
160
+ "value": value,
161
+ "url": "https://chatgpt.com/",
162
+ "secure": True,
163
+ "sameSite": "Lax",
164
+ }
165
+ for name, value in values.items()
166
+ ]
167
+
168
+ def _run(self) -> None:
169
+ xvfb: subprocess.Popen | None = None
170
+ browser = None
171
+ acquired = False
172
+ try:
173
+ self._set_state(message="等待临时浏览器资源…")
174
+ while not self._stop_event.is_set():
175
+ if _BROWSER_SEMAPHORE.acquire(timeout=0.5):
176
+ acquired = True
177
+ break
178
+ if not acquired:
179
+ return
180
+
181
+ display_number = self._next_display()
182
+ display = f":{display_number}"
183
+ xvfb = subprocess.Popen(
184
+ [
185
+ "Xvfb", display, "-screen", "0",
186
+ f"{self.viewport_width}x{self.viewport_height}x24",
187
+ "-nolisten", "tcp", "-ac",
188
+ ],
189
+ stdout=subprocess.DEVNULL,
190
+ stderr=subprocess.DEVNULL,
191
+ )
192
+ time.sleep(0.35)
193
+ if xvfb.poll() is not None:
194
+ raise RuntimeError("Xvfb 启动失败")
195
+
196
+ from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
197
+ from playwright.sync_api import sync_playwright
198
+
199
+ self._set_state(message="正在注入账号已有 Cookie、AT 与代理…")
200
+ with sync_playwright() as playwright:
201
+ launch_options: dict[str, Any] = {
202
+ "headless": False,
203
+ "executable_path": self.executable_path,
204
+ "env": {**os.environ, "DISPLAY": display},
205
+ "args": [
206
+ "--no-sandbox",
207
+ "--disable-dev-shm-usage",
208
+ "--disable-background-networking",
209
+ f"--window-size={self.viewport_width},{self.viewport_height}",
210
+ ],
211
+ }
212
+ proxy_config = playwright_proxy(self.proxy)
213
+ if proxy_config:
214
+ launch_options["proxy"] = proxy_config
215
+ browser = playwright.chromium.launch(**launch_options)
216
+
217
+ context_options: dict[str, Any] = {
218
+ "viewport": {"width": self.viewport_width, "height": self.viewport_height},
219
+ "locale": self.locale,
220
+ "timezone_id": self.timezone_id,
221
+ }
222
+ if self.user_agent:
223
+ context_options["user_agent"] = self.user_agent
224
+ context = browser.new_context(**context_options)
225
+ cookies = self._cookie_payload()
226
+ if cookies:
227
+ context.add_cookies(cookies)
228
+
229
+ page = context.new_page()
230
+ if self.access_token:
231
+ def add_existing_auth(route, req):
232
+ headers = dict(req.headers)
233
+ headers["authorization"] = f"Bearer {self.access_token}"
234
+ if self.chatgpt_account_id:
235
+ headers["chatgpt-account-id"] = self.chatgpt_account_id
236
+ route.continue_(headers=headers)
237
+
238
+ page.route("https://chatgpt.com/backend-api/**", add_existing_auth)
239
+
240
+ try:
241
+ page.goto(self.start_url, wait_until="domcontentloaded", timeout=30000)
242
+ except PlaywrightTimeoutError:
243
+ self._set_state(message="官方短链仍在加载,可在画面中继续操作")
244
+ self._set_state(
245
+ ready=True,
246
+ message="账号已有会话已注入;没有执行登录,也没有刷新 AT",
247
+ )
248
+
249
+ last_frame_at = 0.0
250
+ while not self._stop_event.is_set():
251
+ pages = [item for item in context.pages if not item.is_closed()]
252
+ if pages:
253
+ page = pages[-1]
254
+ current_url = str(page.url or "")
255
+ checkout_match = _CHECKOUT_RE.match(current_url)
256
+ state_values: dict[str, Any] = {"current_url": current_url}
257
+ if checkout_match:
258
+ state_values.update(
259
+ checkout_url=checkout_match.group(0),
260
+ message="菲律宾 Checkout 已在原账号会话中打开;全程未刷新 AT",
261
+ )
262
+ elif "/auth/" in current_url or "/login" in current_url:
263
+ state_values.update(
264
+ message="保存的登录 Cookie 已过期;本次没有刷新 AT,也没有改动短链",
265
+ )
266
+ self._set_state(**state_values)
267
+
268
+ try:
269
+ command = self._commands.get(timeout=0.12)
270
+ except queue.Empty:
271
+ command = None
272
+ if command:
273
+ command_type = command.get("type")
274
+ if command_type == "stop":
275
+ break
276
+ if command_type == "click":
277
+ x = max(0.0, min(float(command.get("x", 0)), self.viewport_width))
278
+ y = max(0.0, min(float(command.get("y", 0)), self.viewport_height))
279
+ page.mouse.click(x, y)
280
+ elif command_type == "text":
281
+ page.keyboard.type(str(command.get("value") or "")[:500], delay=18)
282
+ elif command_type == "key":
283
+ key = str(command.get("key") or "")
284
+ if key in {"Enter", "Tab", "Backspace", "Escape", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"}:
285
+ page.keyboard.press(key)
286
+ elif command_type == "reload":
287
+ page.reload(wait_until="domcontentloaded", timeout=45000)
288
+ elif command_type == "scroll":
289
+ page.mouse.wheel(0, max(-1400, min(int(command.get("delta_y", 600)), 1400)))
290
+
291
+ now = time.time()
292
+ if now - last_frame_at >= 0.65:
293
+ try:
294
+ frame = page.screenshot(type="jpeg", quality=72, full_page=False, timeout=8000)
295
+ with self._lock:
296
+ self._frame = frame
297
+ except Exception as exc:
298
+ self._set_state(message=f"画面生成中:{str(exc)[:100]}")
299
+ last_frame_at = now
300
+ except Exception as exc:
301
+ self._set_state(done=True, error=str(exc), message="临时浏览器运行失败")
302
+ finally:
303
+ try:
304
+ if browser is not None:
305
+ browser.close()
306
+ except Exception:
307
+ pass
308
+ if xvfb is not None:
309
+ try:
310
+ xvfb.terminate()
311
+ xvfb.wait(timeout=3)
312
+ except Exception:
313
+ try:
314
+ xvfb.kill()
315
+ except Exception:
316
+ pass
317
+ if acquired:
318
+ _BROWSER_SEMAPHORE.release()
319
+ self._set_state(done=True)
requirements.txt CHANGED
@@ -1,2 +1,6 @@
1
- curl_cffi==0.15.0
2
- requests>=2.32,<3
 
 
 
 
 
1
+ Flask>=3.0,<4
2
+ certifi>=2024.12.14
3
+ curl_cffi>=0.16,<1
4
+ gunicorn>=23,<24
5
+ PySocks>=1.7.1,<2
6
+ requests>=2.32,<3
serve_direct.py DELETED
@@ -1,25 +0,0 @@
1
- import os
2
-
3
- from http.server import ThreadingHTTPServer
4
-
5
- from server import Handler
6
- from standalone_core.fingerprint_store import optimize_fingerprint_store
7
-
8
-
9
- class QuietHandler(Handler):
10
- def log_message(self, _format, *_args):
11
- return
12
-
13
-
14
- if __name__ == "__main__":
15
- host = os.environ.get("HOST", "127.0.0.1")
16
- port = int(os.environ.get("PORT", "5601"))
17
- fingerprint_region = os.environ.get("FINGERPRINT_REGION", "US")
18
- optimize_fingerprint_store(fingerprint_region)
19
- server = ThreadingHTTPServer((host, port), QuietHandler)
20
- try:
21
- server.serve_forever()
22
- except KeyboardInterrupt:
23
- pass
24
- finally:
25
- server.server_close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
server.py DELETED
@@ -1,419 +0,0 @@
1
- """Standalone direct-bind HTTP service on 127.0.0.1:5601."""
2
- from __future__ import annotations
3
-
4
- import json
5
- import re
6
- import threading
7
- import time
8
- import uuid
9
- from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
10
- from pathlib import Path
11
- from typing import Any
12
- from urllib.parse import unquote, urlsplit
13
-
14
- from standalone_flow import (
15
- allocate_fingerprint,
16
- allocate_fingerprints,
17
- fetch_billing_address,
18
- preflight,
19
- run_flow,
20
- validate_payload,
21
- )
22
- from standalone_core.fingerprint_store import optimize_fingerprint_store
23
-
24
- ROOT = Path(__file__).resolve().parent
25
- ALIGNED_BATCH_LIMIT = 50
26
- TASKS: dict[str, dict[str, Any]] = {}
27
- TASKS_LOCK = threading.Lock()
28
- STEP_EVENT_RE = re.compile(r"^FLOW_STEP:([a-z_]+):(start|done|error):(.*)$")
29
- STEP_LABELS = {
30
- "proxy": "分配代理",
31
- "card_method": "生成支付方式",
32
- "fingerprint": "加载指纹",
33
- "first_link": "首次提链",
34
- "bind": "绑卡",
35
- "payment_prepare": "验证支付方式",
36
- "second_link": "二次提链",
37
- "payment": "提交支付",
38
- "verify": "结果校验",
39
- }
40
-
41
-
42
- def _json_bytes(payload: dict[str, Any]) -> bytes:
43
- return json.dumps(payload, ensure_ascii=False).encode("utf-8")
44
-
45
-
46
- def _safe_error(value: Any) -> str:
47
- text = re.sub(r"\s+", " ", str(value or "")).strip()
48
- text = re.sub(
49
- r"(?i)(access_token|authorization|client_secret|payment_method|card_number|cvc)([=:])[^&\s,}]+",
50
- r"\1\2<REDACTED>",
51
- text,
52
- )
53
- lower = text.lower()
54
- if "curl: (35)" in lower or "tls connect error" in lower or "openssl_internal:invalid library" in lower:
55
- return "代理 TLS 握手失败,请检查代理协议、地址、端口和有效期。"
56
- if "card_declined" in lower or "your card was declined" in lower:
57
- return "绑卡未完成:发卡行拒绝了卡片,账号没有新增支付方式。"
58
- if "secret_key_required" in lower:
59
- return "支付接口权限不匹配,当前步骤没有获得所需的服务端权限。"
60
- if "invalidated" in lower or "token expired" in lower or "http 401" in lower:
61
- return "账号凭证已失效,请删除后重新导入。"
62
- if "at does not contain an account id" in lower or "at 缺少账号 id" in lower:
63
- return "该条不是可用的 AT(缺少账号 ID),请导入 access_token。"
64
- if "timeout" in lower or "timed out" in lower:
65
- return "请求超时,请检查代理速度后重试。"
66
- if "proxy" in lower and any(word in lower for word in ("connect", "failed", "error")):
67
- return "代理连接失败,请检查代理格式、节点状态和网络。"
68
- if "http 403" in lower:
69
- return "请求被拒绝(HTTP 403),请检查账号状态和接口权限。"
70
- if "http 402" in lower:
71
- return "支付请求被拒绝(HTTP 402),请检查卡片状态。"
72
- if "failed to perform, curl" in lower:
73
- return "网络请求失败,请检查代理和本机网络。"
74
- return text[:500]
75
-
76
-
77
- def _set_task(task_id: str, **values: Any) -> None:
78
- with TASKS_LOCK:
79
- task = TASKS.setdefault(task_id, {"id": task_id})
80
- task.update(values)
81
-
82
-
83
- def _initial_steps(mode: str) -> list[dict[str, str]]:
84
- keys = ["proxy"]
85
- if mode != "link_only":
86
- keys.append("card_method")
87
- keys.extend(["fingerprint", "first_link"])
88
- if mode == "bind_only":
89
- keys.append("bind")
90
- elif mode == "link_pay":
91
- keys.extend(["payment_prepare", "second_link", "payment", "verify"])
92
- elif mode != "link_only":
93
- keys.extend(["bind", "second_link", "payment", "verify"])
94
- return [
95
- {
96
- "key": key,
97
- "label": (
98
- "刷新支付链接"
99
- if mode == "link_pay" and key == "second_link"
100
- else STEP_LABELS[key]
101
- ),
102
- "status": "done" if key in {"proxy", "card_method"} else "pending",
103
- "detail": (
104
- ("提链代理已分配" if mode == "link_only" else "双代理已分配") if key == "proxy" else
105
- "浏览器支付方式已创建" if key == "card_method" else "等待执行"
106
- ),
107
- }
108
- for key in keys
109
- ]
110
-
111
-
112
- def _update_step(task_id: str, key: str, status: str, detail: str) -> None:
113
- with TASKS_LOCK:
114
- task = TASKS.setdefault(task_id, {"id": task_id})
115
- steps = list(task.get("steps") or [])
116
- step = next((item for item in steps if item.get("key") == key), None)
117
- if step is None:
118
- step = {
119
- "key": key,
120
- "label": STEP_LABELS.get(key, key),
121
- "status": "pending",
122
- "detail": "等待执行",
123
- }
124
- steps.append(step)
125
- step["status"] = status
126
- step["detail"] = _safe_error(detail)[:240] or step.get("detail", "")
127
- done = sum(1 for item in steps if item.get("status") == "done")
128
- progress = min(99, max(5, round(done * 100 / max(1, len(steps)))))
129
- task.update(
130
- steps=steps,
131
- progress=progress,
132
- current_step=key,
133
- stage=f"{step['label']}:{step['detail']}",
134
- )
135
-
136
-
137
- def _update_live_log(task_id: str, logs: list[str], text: str) -> None:
138
- with TASKS_LOCK:
139
- task = TASKS.setdefault(task_id, {"id": task_id})
140
- steps = list(task.get("steps") or [])
141
- running = next(
142
- (item for item in reversed(steps) if item.get("status") == "running"),
143
- None,
144
- )
145
- if running is not None:
146
- running["detail"] = text[:240]
147
- task["stage"] = f"{running['label']}:{running['detail']}"
148
- task["steps"] = steps
149
- task["logs"] = logs[-40:]
150
-
151
-
152
- def _fail_running_step(task_id: str, error: str) -> None:
153
- with TASKS_LOCK:
154
- task = TASKS.setdefault(task_id, {"id": task_id})
155
- steps = list(task.get("steps") or [])
156
- running = next(
157
- (item for item in reversed(steps) if item.get("status") == "running"),
158
- None,
159
- )
160
- if running is not None:
161
- running["status"] = "error"
162
- running["detail"] = error[:240]
163
- task["current_step"] = running.get("key")
164
- task["stage"] = f"{running['label']}失败:{error[:180]}"
165
- task["steps"] = steps
166
-
167
-
168
- def _run_task(
169
- task_id: str,
170
- payload: dict[str, Any],
171
- start_at_monotonic: float | None = None,
172
- start_group: str = "",
173
- ) -> None:
174
- logs: list[str] = []
175
-
176
- def log(message: str) -> None:
177
- event = STEP_EVENT_RE.match(str(message or ""))
178
- if event:
179
- key, state, detail = event.groups()
180
- _update_step(task_id, key, state, detail)
181
- return
182
- text = _safe_error(message)
183
- if text:
184
- logs.append(text)
185
- del logs[:-40]
186
- _update_live_log(task_id, logs, text)
187
-
188
- mode = str(payload.get("flow_mode") or "full").strip().lower()
189
- if start_at_monotonic is not None:
190
- _set_task(
191
- task_id,
192
- status="queued",
193
- progress=1,
194
- stage="等待同批账号同步起跑",
195
- start_group=start_group,
196
- )
197
- delay = start_at_monotonic - time.perf_counter()
198
- if delay > 0:
199
- time.sleep(delay)
200
- started_at_ns = time.time_ns()
201
- _set_task(
202
- task_id,
203
- status="running",
204
- progress=5,
205
- stage="准备执行账号流程",
206
- current_step="fingerprint",
207
- steps=_initial_steps(mode),
208
- logs=[],
209
- start_group=start_group,
210
- started_at=started_at_ns / 1_000_000_000,
211
- started_at_ns=started_at_ns,
212
- )
213
- try:
214
- result = run_flow(payload, logger=log)
215
- _set_task(
216
- task_id,
217
- status="done",
218
- progress=100,
219
- stage="独立 HTTP 流程完成",
220
- result={**result, "logs": logs[-40:]},
221
- finished_at=time.time(),
222
- )
223
- except Exception as exc: # noqa: BLE001
224
- safe_error = _safe_error(exc)
225
- _fail_running_step(task_id, safe_error)
226
- _set_task(
227
- task_id,
228
- status="error",
229
- progress=100,
230
- error=safe_error,
231
- logs=logs[-40:],
232
- finished_at=time.time(),
233
- )
234
-
235
-
236
- class Handler(SimpleHTTPRequestHandler):
237
- def __init__(self, *args: Any, **kwargs: Any) -> None:
238
- super().__init__(*args, directory=str(ROOT), **kwargs)
239
-
240
- def end_headers(self) -> None:
241
- path = self.path.split("?", 1)[0]
242
- if not path.startswith("/api/") and path != "/health":
243
- self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
244
- self.send_header("Pragma", "no-cache")
245
- self.send_header("Expires", "0")
246
- super().end_headers()
247
-
248
- def _send_json(self, status: int, payload: dict[str, Any]) -> None:
249
- body = _json_bytes(payload)
250
- self.send_response(status)
251
- self.send_header("Content-Type", "application/json; charset=utf-8")
252
- self.send_header("Cache-Control", "no-store")
253
- self.send_header("Content-Length", str(len(body)))
254
- self.end_headers()
255
- self.wfile.write(body)
256
-
257
- def do_GET(self) -> None: # noqa: N802
258
- path = self.path.split("?", 1)[0]
259
- if path == "/health":
260
- self._send_json(
261
- 200,
262
- {
263
- "ok": True,
264
- "service": "direct-bind-standalone",
265
- "port": self.server.server_port,
266
- },
267
- )
268
- return
269
- if path == "/api/standalone/info":
270
- self._send_json(
271
- 200,
272
- {
273
- "ok": True,
274
- "service": "direct-bind-standalone",
275
- "upstream_app": False,
276
- "project_database": False,
277
- "fingerprint_provider": "registration-profile",
278
- "fingerprint_sticky_per_account": True,
279
- "fingerprint_store_version": 3,
280
- "fingerprint_cross_layer_audit": True,
281
- "fingerprint_batch_limit": 500,
282
- "aligned_batch_limit": ALIGNED_BATCH_LIMIT,
283
- "task_count": len(TASKS),
284
- },
285
- )
286
- return
287
- if path.startswith("/api/standalone-flow/task/"):
288
- task_id = path.rsplit("/", 1)[-1]
289
- with TASKS_LOCK:
290
- task = dict(TASKS.get(task_id) or {})
291
- if not task:
292
- self._send_json(404, {"ok": False, "error": "task not found"})
293
- return
294
- self._send_json(200, {"ok": True, "task": task})
295
- return
296
- decoded_path = unquote(urlsplit(self.path).path or "/")
297
- static_path = decoded_path.startswith("/static/") and ".." not in decoded_path.split("/")
298
- if decoded_path in {"", "/"}:
299
- self.path = "/index.html"
300
- elif decoded_path == "/index.html" or static_path:
301
- self.path = decoded_path
302
- else:
303
- self._send_json(404, {"ok": False, "error": "static route not found"})
304
- return
305
- super().do_GET()
306
-
307
- def do_POST(self) -> None: # noqa: N802
308
- path = self.path.split("?", 1)[0]
309
- if path == "/api/standalone-flow/tasks/clear":
310
- with TASKS_LOCK:
311
- TASKS.clear()
312
- self._send_json(200, {"ok": True})
313
- return
314
- if path not in {
315
- "/api/fingerprint/allocate",
316
- "/api/fingerprint/allocate-batch",
317
- "/api/address",
318
- "/api/card-bind/session",
319
- "/api/standalone-flow/quick-checkout",
320
- "/api/standalone-flow/quick-checkout-batch",
321
- }:
322
- self._send_json(404, {"ok": False, "error": "route not found"})
323
- return
324
- try:
325
- length = int(self.headers.get("Content-Length") or 0)
326
- if length <= 0 or length > 2_000_000:
327
- raise ValueError("invalid request body length")
328
- payload = json.loads(self.rfile.read(length) or b"{}")
329
- if not isinstance(payload, dict):
330
- raise ValueError("request body must be an object")
331
- if path == "/api/card-bind/session":
332
- result = preflight(payload)
333
- if not str(result.get("publishable_key") or "").startswith("pk_"):
334
- raise RuntimeError("preflight did not return a publishable key")
335
- self._send_json(200, result)
336
- return
337
- if path == "/api/fingerprint/allocate":
338
- self._send_json(200, allocate_fingerprint(payload))
339
- return
340
- if path == "/api/fingerprint/allocate-batch":
341
- self._send_json(200, allocate_fingerprints(payload))
342
- return
343
- if path == "/api/address":
344
- self._send_json(200, fetch_billing_address(payload))
345
- return
346
- if path == "/api/standalone-flow/quick-checkout-batch":
347
- source = payload.get("tasks")
348
- if not isinstance(source, list) or not source:
349
- raise ValueError("tasks must be a non-empty list")
350
- if len(source) > ALIGNED_BATCH_LIMIT:
351
- raise ValueError(
352
- f"aligned batch cannot exceed {ALIGNED_BATCH_LIMIT} accounts"
353
- )
354
- prepared: list[tuple[str, dict[str, Any], str]] = []
355
- for item in source:
356
- if not isinstance(item, dict):
357
- raise ValueError("task item must be an object")
358
- client_id = str(item.get("client_id") or "")[:100]
359
- task_payload = item.get("payload")
360
- if not isinstance(task_payload, dict):
361
- raise ValueError("task payload must be an object")
362
- validate_payload(task_payload, require_payment_method=True)
363
- prepared.append((client_id, task_payload, uuid.uuid4().hex))
364
- start_group = uuid.uuid4().hex
365
- start_delay_ms = max(
366
- 100, min(1000, int(payload.get("start_delay_ms") or 250))
367
- )
368
- start_at_monotonic = time.perf_counter() + (start_delay_ms / 1000)
369
- start_at_epoch = time.time() + (start_delay_ms / 1000)
370
- for client_id, task_payload, task_id in prepared:
371
- _set_task(
372
- task_id,
373
- status="queued",
374
- progress=0,
375
- stage="等待同批账号同步起跑",
376
- start_group=start_group,
377
- )
378
- threading.Thread(
379
- target=_run_task,
380
- args=(task_id, task_payload, start_at_monotonic, start_group),
381
- daemon=True,
382
- ).start()
383
- self._send_json(
384
- 202,
385
- {
386
- "ok": True,
387
- "start_group": start_group,
388
- "start_at": start_at_epoch,
389
- "items": [
390
- {"client_id": client_id, "task_id": task_id}
391
- for client_id, _task_payload, task_id in prepared
392
- ],
393
- },
394
- )
395
- return
396
- validate_payload(payload, require_payment_method=True)
397
- task_id = uuid.uuid4().hex
398
- _set_task(task_id, status="queued", progress=0, stage="独立 HTTP 任务排队")
399
- threading.Thread(target=_run_task, args=(task_id, payload), daemon=True).start()
400
- self._send_json(202, {"ok": True, "task_id": task_id})
401
- except ValueError as exc:
402
- self._send_json(400, {"ok": False, "error": _safe_error(exc)})
403
- except Exception as exc: # noqa: BLE001
404
- self._send_json(502, {"ok": False, "error": _safe_error(exc)})
405
-
406
-
407
- if __name__ == "__main__":
408
- fingerprint_status = optimize_fingerprint_store("US")
409
- server = ThreadingHTTPServer(("127.0.0.1", 5601), Handler)
410
- print(
411
- "direct-bind standalone -> http://127.0.0.1:5601/ "
412
- f"fingerprints={fingerprint_status}"
413
- )
414
- try:
415
- server.serve_forever()
416
- except KeyboardInterrupt:
417
- pass
418
- finally:
419
- server.server_close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
server_confirmation_token.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ import os
6
+ import hmac
7
+ import hashlib
8
+ import sys
9
+ import time
10
+ import uuid
11
+ from typing import Any
12
+
13
+ import ph_checkout_protocol as protocol
14
+ from remote_browser import playwright_proxy
15
+
16
+
17
+ WORKER_HTML = """<!doctype html>
18
+ <html><head><meta charset="utf-8"><title>Stripe worker</title>
19
+ <script src="https://js.stripe.com/v3/"></script>
20
+ <style>html,body{margin:0;padding:16px;font-family:Arial}#payment-element{min-height:180px}</style>
21
+ </head><body><div id="payment-element"></div></body></html>"""
22
+
23
+
24
+ def checkout_payload(snapshot: dict[str, Any]) -> tuple[dict[str, Any], str, str, str]:
25
+ short_url = str(snapshot.get("short_url") or "").strip()
26
+ parts = short_url.split("/")
27
+ if len(parts) < 6:
28
+ raise ValueError("Checkout URL is invalid")
29
+ processor = str(parts[4])
30
+ session_id = str(snapshot.get("checkout_session_id") or parts[5])
31
+ payload = {
32
+ "short_url": short_url,
33
+ "processor_entity": processor,
34
+ "checkout_session_id": session_id,
35
+ "access_token": snapshot.get("access_token"),
36
+ "chatgpt_account_id": snapshot.get("chatgpt_account_id"),
37
+ "session_cookies": snapshot.get("session_cookies") or {},
38
+ "user_agent": snapshot.get("user_agent"),
39
+ "checkout_device_id": snapshot.get("checkout_device_id"),
40
+ "checkout_chatgpt_session_id": snapshot.get("checkout_chatgpt_session_id"),
41
+ "email": snapshot.get("email"),
42
+ "proxy": snapshot.get("checkout_proxy") or snapshot.get("proxy"),
43
+ "offer_proxy": (
44
+ snapshot.get("checkout_proxy")
45
+ if str(snapshot.get("proxy") or "").strip().upper() in {"", "DIRECT"}
46
+ else snapshot.get("proxy")
47
+ ) or snapshot.get("checkout_proxy"),
48
+ }
49
+ proxy = protocol.normalize_proxy(str(payload.get("proxy") or ""))
50
+ if not proxy:
51
+ raise ValueError("Checkout proxy is missing")
52
+ return payload, proxy, processor, session_id
53
+
54
+
55
+ def resolve_context(snapshot: dict[str, Any]) -> tuple[dict[str, Any], str, str]:
56
+ payload, proxy, processor, session_id = checkout_payload(snapshot)
57
+ cookies = dict(payload.get("session_cookies") or {})
58
+ device_id = str(payload.get("checkout_device_id") or cookies.get("oai-did") or uuid.uuid4())
59
+ http = protocol.build_identity_http(proxy, str(payload.get("user_agent") or ""))
60
+ protocol.install_cookies(http, cookies, device_id)
61
+ state = protocol.resolve_oaics_checkout(http, payload, processor, session_id, device_id)
62
+ initial_amount, initial_currency = protocol.oaics_total(state)
63
+ billing = protocol.default_billing("PH", str(payload.get("email") or ""), real_random=True)
64
+ tax_state = protocol.submit_checkout_taxes(
65
+ http,
66
+ payload,
67
+ processor,
68
+ session_id,
69
+ device_id,
70
+ billing,
71
+ initial_currency,
72
+ )
73
+ if tax_state:
74
+ state = {**state, **tax_state}
75
+ protocol.snapshot_billing(http, payload, processor, session_id, device_id, billing)
76
+ state = protocol.resolve_oaics_checkout(http, payload, processor, session_id, device_id)
77
+
78
+ offer_check_ok = False
79
+ offer_eligible = False
80
+ offer_campaign_id = ""
81
+ offer_label = ""
82
+ try:
83
+ offer_headers = {
84
+ "Authorization": f"Bearer {str(payload.get('access_token') or '')}",
85
+ "Accept": "application/json",
86
+ "Origin": "https://chatgpt.com",
87
+ "Referer": "https://chatgpt.com/",
88
+ "User-Agent": str(payload.get("user_agent") or ""),
89
+ "OAI-Device-Id": device_id,
90
+ }
91
+ account_id = str(payload.get("chatgpt_account_id") or "")
92
+ if account_id:
93
+ offer_headers["ChatGPT-Account-ID"] = account_id
94
+ offer_proxy = protocol.normalize_proxy(str(payload.get("offer_proxy") or "")) or proxy
95
+ offer_http = protocol.build_identity_http(offer_proxy, str(payload.get("user_agent") or ""))
96
+ protocol.install_cookies(offer_http, cookies, device_id)
97
+ offer_response = offer_http.get(
98
+ "https://chatgpt.com/backend-api/accounts/check/v4-2023-04-27",
99
+ headers=offer_headers,
100
+ timeout=40,
101
+ )
102
+ if getattr(offer_response, "status_code", 0) == 200:
103
+ offer_check_ok = True
104
+ offer_payload = offer_response.json() or {}
105
+ accounts = offer_payload.get("accounts") or {}
106
+ candidates = []
107
+ if account_id and isinstance(accounts.get(account_id), dict):
108
+ candidates.append(accounts.get(account_id))
109
+ if isinstance(accounts.get("default"), dict):
110
+ candidates.append(accounts.get("default"))
111
+ candidates.extend(value for value in accounts.values() if isinstance(value, dict))
112
+ for account in candidates:
113
+ plus = ((account.get("eligible_promo_campaigns") or {}).get("plus") or {})
114
+ campaign_id = str(plus.get("id") or plus.get("campaign_id") or "").strip()
115
+ if not campaign_id:
116
+ continue
117
+ offer_eligible = True
118
+ offer_campaign_id = campaign_id
119
+ metadata = plus.get("metadata") or {}
120
+ discount = (metadata.get("discount") or {}).get("percentage")
121
+ duration = metadata.get("duration") or {}
122
+ if discount == 100 and duration.get("num_periods") == 1 and duration.get("period") == "month":
123
+ offer_label = "Plus first month free"
124
+ else:
125
+ offer_label = str(metadata.get("promotion_type_label") or metadata.get("title") or campaign_id)
126
+ break
127
+ except Exception:
128
+ pass
129
+
130
+ amount, currency = protocol.oaics_total(state)
131
+ methods = [str(item).lower() for item in (state.get("payment_method_types") or [])]
132
+ customer_session = str(state.get("customer_session_client_secret") or "")
133
+ publishable_key = str(state.get("publishable_key") or "")
134
+ if not publishable_key.startswith("pk_") or not customer_session.startswith("cuss_secret_"):
135
+ raise RuntimeError("Checkout customer context is incomplete")
136
+ context = {
137
+ "publishable_key": publishable_key,
138
+ "customer_session_client_secret": customer_session,
139
+ "mode": "setup" if int(amount) == 0 else "subscription",
140
+ "amount": int(amount),
141
+ "currency": str(currency).lower(),
142
+ "payment_method_types": methods or ["card"],
143
+ "setup_future_usage": "off_session",
144
+ "return_url": str(state.get("confirm_return_url") or payload["short_url"]),
145
+ "can_confirm": bool((state.get("checkout_state") or {}).get("canConfirm")),
146
+ "offer_check_ok": offer_check_ok,
147
+ "offer_eligible": offer_eligible,
148
+ "offer_campaign_id": offer_campaign_id,
149
+ "offer_label": offer_label,
150
+ "checkout_trial_flag": state.get("one_click_trial_eligible"),
151
+ "promo_campaign_id": str((state.get("promo_campaign") or {}).get("promo_campaign_id") or ""),
152
+ }
153
+ return context, proxy, str(payload.get("user_agent") or ""), payload
154
+
155
+
156
+ def create_token(
157
+ context: dict[str, Any],
158
+ proxy: str,
159
+ user_agent: str,
160
+ identity: dict[str, Any],
161
+ ) -> str:
162
+ confirm_headers = asyncio.run(protocol.sentinel_headers(
163
+ proxy,
164
+ "checkout_session_approval",
165
+ str(identity.get("checkout_device_id") or ""),
166
+ str(identity.get("checkout_device_id") or ""),
167
+ ))
168
+ context["confirm_headers"] = confirm_headers
169
+ context["checkout_session_id"] = str(identity.get("checkout_session_id") or "")
170
+
171
+ from playwright.sync_api import sync_playwright
172
+
173
+ proxy_cfg = playwright_proxy(proxy) or {}
174
+ proxy_cfg["bypass"] = "127.0.0.1,localhost"
175
+ with sync_playwright() as pw:
176
+ browser = pw.chromium.launch(
177
+ headless=True,
178
+ executable_path="/usr/bin/chromium",
179
+ proxy=proxy_cfg,
180
+ args=[
181
+ "--no-sandbox",
182
+ "--disable-dev-shm-usage",
183
+ "--disable-background-networking",
184
+ "--window-size=1280,900",
185
+ ],
186
+ )
187
+ try:
188
+ opts: dict[str, Any] = {
189
+ "viewport": {"width": 1280, "height": 900},
190
+ "locale": "en-PH",
191
+ "timezone_id": "Asia/Manila",
192
+ }
193
+ if user_agent:
194
+ opts["user_agent"] = user_agent
195
+ browser_context = browser.new_context(**opts)
196
+ cookie_values = {
197
+ str(name): str(value)
198
+ for name, value in dict(identity.get("session_cookies") or {}).items()
199
+ if str(name).strip() and str(value)
200
+ }
201
+ device_id = str(identity.get("checkout_device_id") or cookie_values.get("oai-did") or "")
202
+ if device_id:
203
+ cookie_values["oai-did"] = device_id
204
+ if cookie_values:
205
+ browser_context.add_cookies([
206
+ {
207
+ "name": name,
208
+ "value": value,
209
+ "domain": "chatgpt.com",
210
+ "path": "/",
211
+ "secure": True,
212
+ "sameSite": "Lax",
213
+ }
214
+ for name, value in cookie_values.items()
215
+ ])
216
+ page = browser_context.new_page()
217
+ access_token = str(identity.get("access_token") or "")
218
+ account_id = str(identity.get("chatgpt_account_id") or "")
219
+ if access_token:
220
+ def inject_auth(route, request):
221
+ headers = dict(request.headers)
222
+ headers["authorization"] = f"Bearer {access_token}"
223
+ if account_id:
224
+ headers["chatgpt-account-id"] = account_id
225
+ if device_id:
226
+ headers["oai-device-id"] = device_id
227
+ route.continue_(headers=headers)
228
+ page.route("https://chatgpt.com/backend-api/**", inject_auth)
229
+ worker_url = str(identity.get("short_url") or context.get("return_url") or "")
230
+ page.goto(worker_url, wait_until="commit", timeout=45000)
231
+ if "chatgpt.com/checkout/" not in str(page.url):
232
+ # A raw AT may be fully valid for backend APIs while having no
233
+ # ChatGPT web-session cookie. Keep the official checkout origin,
234
+ # but serve the minimal Stripe worker document locally; backend
235
+ # calls below still carry the supplied Bearer AT/account headers.
236
+ page.route(
237
+ worker_url,
238
+ lambda route: route.fulfill(
239
+ status=200,
240
+ content_type="text/html; charset=utf-8",
241
+ body=WORKER_HTML,
242
+ ),
243
+ )
244
+ page.goto(worker_url, wait_until="domcontentloaded", timeout=45000)
245
+ if "chatgpt.com/checkout/" not in str(page.url):
246
+ raise RuntimeError(f"Checkout worker origin unavailable: {page.url}")
247
+ page.wait_for_timeout(800)
248
+ try:
249
+ page.evaluate("window.stop()")
250
+ except Exception:
251
+ pass
252
+ page.add_script_tag(url="https://js.stripe.com/v3/")
253
+ page.wait_for_function("typeof window.Stripe === 'function'", timeout=30000)
254
+ page.evaluate("""() => {
255
+ document.body.innerHTML = '<div id="payment-element" style="min-height:180px;padding:16px"></div>';
256
+ }""")
257
+ result = page.evaluate(
258
+ """async (cfg) => {
259
+ const stripe = Stripe(cfg.publishable_key);
260
+ const elementOptions = {
261
+ mode: cfg.mode || 'subscription',
262
+ currency: String(cfg.currency || 'php').toLowerCase(),
263
+ paymentMethodTypes: cfg.payment_method_types || ['card'],
264
+ customerSessionClientSecret: cfg.customer_session_client_secret,
265
+ setupFutureUsage: cfg.setup_future_usage || 'off_session',
266
+ appearance: {theme: 'stripe', variables: {borderRadius: '12px', fontSizeBase: '16px'}}
267
+ };
268
+ if (elementOptions.mode !== 'setup') elementOptions.amount = Number(cfg.amount || 0);
269
+ const elements = stripe.elements(elementOptions);
270
+ const payment = elements.create('payment', {layout: 'tabs'});
271
+ await new Promise((resolve, reject) => {
272
+ let settled = false;
273
+ const timer = setTimeout(() => {
274
+ if (!settled) { settled = true; reject(new Error('Payment Element ready timeout')); }
275
+ }, 30000);
276
+ payment.on('ready', () => {
277
+ if (!settled) { settled = true; clearTimeout(timer); resolve(); }
278
+ });
279
+ payment.mount('#payment-element');
280
+ });
281
+ await new Promise(resolve => setTimeout(resolve, 1800));
282
+ const submitted = await elements.submit();
283
+ if (submitted && submitted.error) {
284
+ return {ok:false,error:submitted.error.message || submitted.error.code || 'elements.submit failed'};
285
+ }
286
+ const created = await stripe.createConfirmationToken({
287
+ elements,
288
+ params: {return_url: cfg.return_url},
289
+ allow_redisplay: 'always'
290
+ });
291
+ if (created.error) {
292
+ return {ok:false,error:created.error.message || created.error.code || 'createConfirmationToken failed'};
293
+ }
294
+ const token = created.confirmationToken && created.confirmationToken.id;
295
+ const response = await fetch('/backend-api/payments/checkout/confirm', {
296
+ method: 'POST',
297
+ credentials: 'include',
298
+ headers: {'Content-Type':'application/json', ...(cfg.confirm_headers || {})},
299
+ body: JSON.stringify({
300
+ checkout_session_id: cfg.checkout_session_id,
301
+ confirm_token: token
302
+ })
303
+ });
304
+ const responseText = await response.text();
305
+ let confirmResult = {};
306
+ try { confirmResult = JSON.parse(responseText || '{}'); }
307
+ catch { confirmResult = {raw: responseText.slice(0, 500)}; }
308
+ return {
309
+ ok:true,
310
+ token,
311
+ confirm_http_status: response.status,
312
+ checkout_confirm: confirmResult
313
+ };
314
+ }""",
315
+ context,
316
+ )
317
+ if not isinstance(result, dict) or not result.get("ok"):
318
+ raise RuntimeError(str((result or {}).get("error") or "Stripe.js token generation failed"))
319
+ token = str(result.get("token") or "")
320
+ if not token.startswith("ctoken_"):
321
+ raise RuntimeError("Stripe.js did not return a ConfirmationToken")
322
+ return result
323
+ finally:
324
+ browser.close()
325
+
326
+
327
+ def main() -> int:
328
+ snapshot = json.loads(sys.stdin.read() or "{}")
329
+ context, proxy, user_agent, identity = resolve_context(snapshot)
330
+ if context.get("offer_check_ok") and not context.get("offer_eligible"):
331
+ print(json.dumps({
332
+ "ok": False,
333
+ "error_code": "OFFER_NOT_ELIGIBLE",
334
+ "error": "The account promo catalog does not contain eligible_promo_campaigns.plus",
335
+ "offer_check_ok": True,
336
+ "offer_eligible": False,
337
+ "offer_campaign_id": "",
338
+ }, ensure_ascii=True))
339
+ return 0
340
+ result = create_token(context, proxy, user_agent, identity)
341
+ print(json.dumps({
342
+ "ok": True,
343
+ "confirmation_token": result.get("token"),
344
+ "confirm_http_status": result.get("confirm_http_status"),
345
+ "checkout_confirm": result.get("checkout_confirm") or {},
346
+ "can_confirm": context.get("can_confirm"),
347
+ "offer_check_ok": context.get("offer_check_ok"),
348
+ "offer_eligible": context.get("offer_eligible"),
349
+ "offer_campaign_id": context.get("offer_campaign_id"),
350
+ "offer_label": context.get("offer_label"),
351
+ "checkout_trial_flag": context.get("checkout_trial_flag"),
352
+ "promo_campaign_id": context.get("promo_campaign_id"),
353
+ }, ensure_ascii=True))
354
+ return 0
355
+
356
+
357
+ if __name__ == "__main__":
358
+ try:
359
+ raise SystemExit(main())
360
+ except Exception as exc:
361
+ print(json.dumps({"ok": False, "error": f"{type(exc).__name__}: {exc}"}, ensure_ascii=True))
362
+ raise
standalone_config.json DELETED
@@ -1,24 +0,0 @@
1
- {
2
- "country": "PH",
3
- "currency": "PHP",
4
- "fingerprint_region": "US",
5
- "bind_country": "US",
6
- "bind_currency": "USD",
7
- "promo_campaign": "plus-1-month-free",
8
- "reject_nonzero": true,
9
- "timeout": 90,
10
- "preflight_cache_ttl": 600,
11
- "coupon_diagnostic": false,
12
- "fast_verify": true,
13
- "address_generator": "https://addressgen.top/api/v1/address?country_code=us&area_code=DE",
14
- "billing": {
15
- "name": "",
16
- "line1": "",
17
- "line2": "",
18
- "city": "",
19
- "state": "",
20
- "postal_code": "",
21
- "country": "",
22
- "phone": ""
23
- }
24
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
standalone_core/__init__.py DELETED
@@ -1 +0,0 @@
1
- """Vendored HTTP-only flow core for the standalone direct-bind service."""
 
 
standalone_core/card_payment.py DELETED
@@ -1,1225 +0,0 @@
1
- """Protocol card-payment flow for the account-opening pipeline.
2
-
3
- The implementation mirrors the documented sequence while keeping card data,
4
- tokens and customer identifiers in process memory only. Callers receive a
5
- small result summary; logs contain stage/status information and masked values.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import json
11
- import random
12
- import re
13
- import time
14
- import uuid
15
- from dataclasses import dataclass, field
16
- from typing import Any, Callable
17
- from urllib.parse import urlencode
18
-
19
- try:
20
- from curl_cffi import requests as curl_requests
21
- except Exception: # pragma: no cover - optional dependency fallback
22
- curl_requests = None
23
-
24
- try:
25
- import requests as plain_requests
26
- except Exception: # pragma: no cover - optional dependency fallback
27
- plain_requests = None
28
-
29
-
30
- APP_BASE = "https://chatgpt.com"
31
- STRIPE_BASE = "https://api.stripe.com"
32
- CHECKOUT_URL = f"{APP_BASE}/backend-api/payments/checkout"
33
- STRIPE_VERSION = "2025-03-31.basil"
34
- STRIPE_BETAS = (
35
- "2025-03-31.basil; checkout_server_update_beta=v1; "
36
- "checkout_manual_approval_preview=v1"
37
- )
38
- DEFAULT_TIMEOUT = 60
39
- STRIPE_HCAPTCHA_SITE_KEY = "463b917e-e264-403f-ad34-34af0ee10294"
40
- STRIPE_HCAPTCHA_URL = (
41
- "https://b.stripecdn.com/stripethirdparty-srv/assets/"
42
- "v33.5/HCaptchaInvisible.html"
43
- )
44
- KNOWN_SETUP_PUBLISHABLE_KEYS = {
45
- "KslHRdbaPg": "pk_live_51Pj377KslHRdbaPgTJYjThzH3f5dt1N1vK7LUp0qh0yNSarhfZ6nfbG7FFlh8KLxVkvdMWN5o6Mc4Vda6NHaSnaV00C2Sbl8Zs",
46
- "C6h1nxGoI3": "pk_live_51HOrSwC6h1nxGoI3lTAgRjYVrz4dU3fVOabyCcKR3pbEJguCVAlqCxdxCUvoRh1XWwRacViovU3kLKvpkjh7IqkW00iXQsjo3n",
47
- }
48
-
49
-
50
- class CardPaymentError(RuntimeError):
51
- """A stage-labelled payment error with safe diagnostic text."""
52
-
53
-
54
- @dataclass(slots=True)
55
- class CardPaymentConfig:
56
- token: str
57
- account_id: str = ""
58
- country: str = "US"
59
- currency: str = "USD"
60
- promo_campaign: str = "plus-1-month-free"
61
- billing: dict[str, str] = field(default_factory=dict)
62
- card: dict[str, str] = field(default_factory=dict)
63
- session_token: str = ""
64
- cookies: list[dict[str, Any]] = field(default_factory=list)
65
- device_id: str = ""
66
- fingerprint_profile: dict[str, str] = field(default_factory=dict)
67
- timeout: int = DEFAULT_TIMEOUT
68
- max_setup_confirm_attempts: int = 1
69
- hcaptcha_token: str = ""
70
- checkout_id: str = ""
71
- payment_page_id: str = ""
72
- processor_entity: str = ""
73
- publishable_key: str = ""
74
- locale: str = "zh-CN"
75
- timezone: str = "Asia/Shanghai"
76
- captcha_provider: str = ""
77
- captcha_key: str = ""
78
- captcha_api_url: str = ""
79
- hcaptcha_site_key: str = STRIPE_HCAPTCHA_SITE_KEY
80
- hcaptcha_website_url: str = STRIPE_HCAPTCHA_URL
81
- bind_country: str = "US"
82
- bind_currency: str = "USD"
83
- strong_bind_direct: bool = True
84
- stop_after_bind: bool = False
85
- flow_mode: str = "full"
86
- payment_method_id: str = ""
87
- card_last4: str = ""
88
- fast_verify: bool = False
89
-
90
-
91
- def _text(value: Any) -> str:
92
- return str(value or "").strip()
93
-
94
-
95
- def _mask(value: Any, head: int = 8, tail: int = 4) -> str:
96
- raw = _text(value)
97
- if not raw:
98
- return ""
99
- if len(raw) <= head + tail:
100
- return "***"
101
- return f"{raw[:head]}…{raw[-tail:]}"
102
-
103
-
104
- def _safe_error(value: Any) -> str:
105
- raw = re.sub(r"\s+", " ", _text(value))
106
- raw = re.sub(
107
- r"(?i)(client_secret|confirmation_token|access_token|authorization|"
108
- r"card\]?\[?(?:number|cvc|cvv)|password)([=:])[^&\s,}]+",
109
- r"\1\2<REDACTED>",
110
- raw,
111
- )
112
- return raw[:500]
113
-
114
-
115
- def _log(logger: Callable[[str], None], message: str) -> None:
116
- try:
117
- logger(_safe_error(message))
118
- except Exception:
119
- pass
120
-
121
-
122
- def _check_cancel(is_cancelled: Callable[[], bool] | None) -> None:
123
- if is_cancelled and is_cancelled():
124
- raise CardPaymentError("payment cancelled")
125
-
126
-
127
- def _response_json(response: Any) -> dict[str, Any]:
128
- try:
129
- value = response.json() or {}
130
- except Exception:
131
- value = {}
132
- return value if isinstance(value, dict) else {}
133
-
134
-
135
- def _response_error(response: Any) -> str:
136
- status = int(getattr(response, "status_code", 0) or 0)
137
- payload = _response_json(response)
138
- if payload:
139
- error = payload.get("error")
140
- if isinstance(error, dict):
141
- code = _text(error.get("code"))
142
- message = _text(error.get("message"))
143
- return f"HTTP {status} {code} {message}".strip()
144
- return f"HTTP {status} {_text(payload.get('message') or payload.get('detail'))}".strip()
145
- return f"HTTP {status}".strip()
146
-
147
-
148
- def _walk(value: Any):
149
- if isinstance(value, dict):
150
- yield value
151
- for item in value.values():
152
- yield from _walk(item)
153
- elif isinstance(value, list):
154
- for item in value:
155
- yield from _walk(item)
156
-
157
-
158
- def _find_key(payload: Any, names: tuple[str, ...]) -> str:
159
- wanted = {item.lower() for item in names}
160
- for item in _walk(payload):
161
- for key, value in item.items():
162
- if key.lower() in wanted and isinstance(value, (str, int, float)):
163
- text = _text(value)
164
- if text:
165
- return text
166
- return ""
167
-
168
-
169
- def _find_identifier(payload: Any, prefixes: tuple[str, ...]) -> str:
170
- for item in _walk(payload):
171
- for value in item.values():
172
- if not isinstance(value, (str, int, float)):
173
- continue
174
- text = _text(value)
175
- if any(text.startswith(prefix) for prefix in prefixes):
176
- return text
177
- return ""
178
-
179
-
180
- def _find_client_secret(payload: Any) -> str:
181
- value = _find_key(payload, ("client_secret", "clientSecret"))
182
- if value:
183
- return value
184
- for item in _walk(payload):
185
- for value in item.values():
186
- text = _text(value)
187
- if "_secret_" in text and text.startswith(("seti_", "pi_", "cs_")):
188
- return text
189
- return ""
190
-
191
-
192
- def _setup_intent_id(payload: Any, client_secret: str = "") -> str:
193
- """Prefer the SetupIntent id over the similarly-prefixed client secret."""
194
- direct = _find_key(payload, ("setup_intent_id", "setupIntentId", "id"))
195
- if direct.startswith("seti_") and "_secret_" not in direct:
196
- return direct
197
- secret_base = _text(client_secret).split("_secret_", 1)[0]
198
- if secret_base.startswith("seti_"):
199
- return secret_base
200
- candidate = _find_identifier(payload, ("seti_",))
201
- if "_secret_" in candidate:
202
- candidate = candidate.split("_secret_", 1)[0]
203
- return candidate if candidate.startswith("seti_") else ""
204
-
205
-
206
- def _require_setup_succeeded(payload: Any, stage: str) -> str:
207
- """Reject HTTP-200 Stripe responses that still need action or failed."""
208
- status = _text(_find_key(payload, ("status",))).lower()
209
- if status == "succeeded":
210
- return status
211
- if status == "requires_action":
212
- raise CardPaymentError(f"{stage}: requires_action (3DS verification required)")
213
- if status:
214
- raise CardPaymentError(f"{stage}: unexpected SetupIntent status {status}")
215
- raise CardPaymentError(f"{stage}: missing SetupIntent status")
216
-
217
-
218
- def _publishable_key_for_setup(client_secret: str, fallback: str = "") -> str:
219
- secret = _text(client_secret)
220
- for fragment, key in KNOWN_SETUP_PUBLISHABLE_KEYS.items():
221
- if fragment in secret:
222
- return key
223
- return _text(fallback)
224
-
225
-
226
- def _checkout_id(payload: Any) -> str:
227
- return _find_key(
228
- payload,
229
- ("checkout_session_id", "checkoutSessionId", "session_id", "sessionId"),
230
- ) or _find_identifier(payload, ("oaics_", "cs_live_", "cs_test_", "cs_"))
231
-
232
-
233
- def _processor_entity(payload: Any, country: str) -> str:
234
- return _find_key(payload, ("processor_entity", "processorEntity")) or (
235
- "openai_llc" if country.upper() in {"US", "AU"} else "openai_ie"
236
- )
237
-
238
-
239
- def _card_fields(card: dict[str, Any]) -> dict[str, str]:
240
- number = re.sub(r"\D", "", _text(card.get("card_number") or card.get("number")))
241
- cvc = re.sub(r"\D", "", _text(card.get("cvv") or card.get("cvc")))
242
- month = re.sub(r"\D", "", _text(card.get("exp_month") or card.get("month"))).zfill(2)
243
- year = re.sub(r"\D", "", _text(card.get("exp_year") or card.get("year")))
244
- if len(year) == 2:
245
- year = f"20{year}"
246
- if not number or not cvc or len(month) != 2 or len(year) != 4:
247
- raise CardPaymentError("invalid card fields")
248
- if len(number) < 12 or len(number) > 19:
249
- raise CardPaymentError("invalid card number length")
250
- if len(cvc) not in {3, 4}:
251
- raise CardPaymentError("invalid card security code length")
252
- return {"number": number, "cvc": cvc, "exp_month": month, "exp_year": year}
253
-
254
-
255
- def _billing_fields(config: CardPaymentConfig) -> dict[str, str]:
256
- source = {str(k): _text(v) for k, v in (config.billing or {}).items()}
257
- return {
258
- "name": source.get("name") or "",
259
- "email": source.get("email"),
260
- "line1": source.get("line1") or source.get("address") or "",
261
- "line2": source.get("line2"),
262
- "city": source.get("city"),
263
- "state": source.get("state"),
264
- "postal_code": source.get("postal_code") or source.get("zip") or "",
265
- "country": source.get("country") or "",
266
- "phone": source.get("phone"),
267
- }
268
-
269
-
270
- def _payment_card_last4(config: CardPaymentConfig) -> str:
271
- external_last4 = re.sub(r"\D", "", _text(config.card_last4))[-4:]
272
- if len(external_last4) == 4:
273
- return external_last4
274
- if config.card:
275
- return _card_fields(config.card)["number"][-4:]
276
- return ""
277
-
278
-
279
- def _new_session(config: CardPaymentConfig, proxy: str = "") -> Any:
280
- fingerprint = dict(config.fingerprint_profile or {})
281
- impersonate = _text(fingerprint.get("tls_impersonate")) or "chrome146"
282
- if curl_requests is not None:
283
- session = curl_requests.Session(impersonate=impersonate)
284
- elif plain_requests is not None:
285
- session = plain_requests.Session()
286
- else:
287
- raise CardPaymentError("missing HTTP dependency: install curl_cffi")
288
- if hasattr(session, "trust_env"):
289
- session.trust_env = False
290
- device_id = _text(config.device_id) or str(uuid.uuid4())
291
- user_agent = _text(fingerprint.get("ua")) or (
292
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
293
- "AppleWebKit/537.36 (KHTML, like Gecko) "
294
- "Chrome/146.0.0.0 Safari/537.36"
295
- )
296
- major = _text(fingerprint.get("major")) or "146"
297
- platform = _text(fingerprint.get("platform")) or "Windows"
298
- sec_ch_ua = _text(fingerprint.get("sec_ch_ua")) or (
299
- f'"Not;A=Brand";v="8", "Chromium";v="{major}", '
300
- f'"Google Chrome";v="{major}"'
301
- )
302
- accept_language = _text(fingerprint.get("accept_language")) or (
303
- _text(config.locale) or "en-US"
304
- )
305
- oai_language = _text(fingerprint.get("oai_language")) or (
306
- _text(config.locale) or "en-US"
307
- )
308
- session.headers.update({
309
- "User-Agent": user_agent,
310
- "Accept": "*/*",
311
- "Accept-Language": accept_language,
312
- "Authorization": f"Bearer {_text(config.token)}",
313
- "Origin": APP_BASE,
314
- "Referer": f"{APP_BASE}/",
315
- "Content-Type": "application/json",
316
- "oai-device-id": device_id,
317
- "oai-language": oai_language,
318
- "sec-ch-ua": sec_ch_ua,
319
- "sec-ch-ua-mobile": _text(fingerprint.get("mobile")) or "?0",
320
- "sec-ch-ua-platform": f'"{platform.strip(chr(34))}"',
321
- "priority": "u=1, i",
322
- })
323
- if fingerprint:
324
- session.headers.update({
325
- "sec-ch-ua-arch": f'"{_text(fingerprint.get("arch")) or "x86"}"',
326
- "sec-ch-ua-bitness": f'"{_text(fingerprint.get("bitness")) or "64"}"',
327
- "sec-ch-ua-model": '""',
328
- "sec-ch-ua-full-version": f'"{_text(fingerprint.get("full")) or major}"',
329
- "sec-ch-ua-full-version-list": _text(
330
- fingerprint.get("sec_ch_ua_full_version_list")
331
- ) or sec_ch_ua,
332
- "sec-ch-ua-platform-version": (
333
- f'"{_text(fingerprint.get("platform_version")) or "15.0.0"}"'
334
- ),
335
- })
336
- if _text(proxy):
337
- session.proxies = {"http": proxy, "https": proxy}
338
- if hasattr(session, "cookies"):
339
- try:
340
- session.cookies.set(
341
- "oai-did",
342
- device_id,
343
- domain=".chatgpt.com",
344
- path="/",
345
- )
346
- except Exception:
347
- pass
348
- if _text(config.session_token) and hasattr(session, "cookies"):
349
- try:
350
- session.cookies.set(
351
- "__Secure-next-auth.session-token",
352
- _text(config.session_token),
353
- domain=".chatgpt.com",
354
- path="/",
355
- )
356
- except Exception:
357
- pass
358
- for cookie in config.cookies or []:
359
- if not isinstance(cookie, dict) or not _text(cookie.get("name")):
360
- continue
361
- try:
362
- session.cookies.set(
363
- _text(cookie.get("name")),
364
- _text(cookie.get("value")),
365
- domain=_text(cookie.get("domain")) or ".chatgpt.com",
366
- path=_text(cookie.get("path")) or "/",
367
- )
368
- except Exception:
369
- pass
370
- return session
371
-
372
-
373
- def _app_headers(referer: str = "", route: str = "") -> dict[str, str]:
374
- headers = {
375
- "Origin": APP_BASE,
376
- "Referer": referer or f"{APP_BASE}/",
377
- "Content-Type": "application/json",
378
- }
379
- if route:
380
- headers["x-openai-target-path"] = route
381
- headers["x-openai-target-route"] = route
382
- return headers
383
-
384
-
385
- def _stripe_headers(
386
- publishable_key: str,
387
- referer: str,
388
- *,
389
- stripe_version: str = "",
390
- ) -> dict[str, str]:
391
- headers = {
392
- "Authorization": f"Bearer {publishable_key}",
393
- "Origin": "https://js.stripe.com",
394
- "Referer": "https://js.stripe.com/",
395
- "Accept": "application/json",
396
- "Content-Type": "application/x-www-form-urlencoded",
397
- }
398
- if _text(stripe_version):
399
- headers["Stripe-Version"] = _text(stripe_version)
400
- return headers
401
-
402
-
403
- def _post_json(
404
- session: Any,
405
- url: str,
406
- body: dict[str, Any],
407
- *,
408
- timeout: int,
409
- stage: str,
410
- referer: str = "",
411
- route: str = "",
412
- ) -> dict[str, Any]:
413
- response = session.post(
414
- url,
415
- json=body,
416
- headers=_app_headers(referer, route),
417
- timeout=timeout,
418
- )
419
- if int(getattr(response, "status_code", 0) or 0) >= 400:
420
- raise CardPaymentError(f"{stage}: {_response_error(response)}")
421
- return _response_json(response)
422
-
423
-
424
- def _post_form(
425
- session: Any,
426
- url: str,
427
- body: dict[str, Any],
428
- *,
429
- key: str,
430
- referer: str,
431
- timeout: int,
432
- stage: str,
433
- stripe_version: str = "",
434
- ) -> tuple[Any, dict[str, Any]]:
435
- response = session.post(
436
- url,
437
- data=urlencode(body, doseq=True),
438
- headers=_stripe_headers(key, referer, stripe_version=stripe_version),
439
- timeout=timeout,
440
- )
441
- return response, _response_json(response)
442
-
443
-
444
- def _checkout_create(
445
- session: Any,
446
- config: CardPaymentConfig,
447
- *,
448
- country: str = "",
449
- currency: str = "",
450
- promo_campaign: str | None = None,
451
- ) -> dict[str, Any]:
452
- checkout_country = (_text(country) or config.country).upper()
453
- checkout_currency = (_text(currency) or config.currency).upper()
454
- body: dict[str, Any] = {
455
- "entry_point": "all_plans_pricing_modal",
456
- "plan_name": "chatgptplusplan",
457
- "billing_details": {
458
- "country": checkout_country,
459
- "currency": checkout_currency,
460
- },
461
- "checkout_ui_mode": "custom",
462
- }
463
- campaign = config.promo_campaign if promo_campaign is None else promo_campaign
464
- if _text(campaign):
465
- body["promo_campaign"] = {
466
- "promo_campaign_id": _text(campaign),
467
- "is_coupon_from_query_param": False,
468
- }
469
- return _post_json(
470
- session,
471
- CHECKOUT_URL,
472
- body,
473
- timeout=config.timeout,
474
- stage="checkout create",
475
- route="/backend-api/payments/checkout",
476
- )
477
-
478
-
479
- def _init_payment_page(session: Any, config: CardPaymentConfig, payment_page_id: str, publishable_key: str, processor_entity: str) -> tuple[dict[str, Any], str]:
480
- stripe_js_id = str(uuid.uuid4())
481
- page = f"{APP_BASE}/checkout/{processor_entity}/{config.checkout_id or payment_page_id}"
482
- locale = _text(config.locale) or "zh-CN"
483
- body = {
484
- "browser_locale": locale,
485
- "browser_timezone": _text(config.timezone) or "Asia/Shanghai",
486
- "elements_session_client[client_betas][0]": "custom_checkout_server_updates_1",
487
- "elements_session_client[client_betas][1]": "custom_checkout_manual_approval_1",
488
- "elements_session_client[elements_init_source]": "custom_checkout",
489
- "elements_session_client[referrer_host]": "chatgpt.com",
490
- "elements_session_client[stripe_js_id]": stripe_js_id,
491
- "elements_session_client[locale]": locale,
492
- "elements_session_client[is_aggregation_expected]": "false",
493
- "elements_options_client[saved_payment_method][enable_save]": "auto",
494
- "elements_options_client[saved_payment_method][enable_redisplay]": "auto",
495
- "key": publishable_key,
496
- "_stripe_version": STRIPE_BETAS,
497
- }
498
- response, payload = _post_form(
499
- session,
500
- f"{STRIPE_BASE}/v1/payment_pages/{payment_page_id}/init",
501
- body,
502
- key=publishable_key,
503
- referer=page,
504
- timeout=config.timeout,
505
- stage="payment page init",
506
- )
507
- if int(getattr(response, "status_code", 0) or 0) >= 400:
508
- raise CardPaymentError(f"payment page init: {_response_error(response)}")
509
- return payload, stripe_js_id
510
-
511
-
512
- def _create_elements_session(
513
- session: Any,
514
- config: CardPaymentConfig,
515
- init_payload: dict[str, Any],
516
- payment_page_id: str,
517
- publishable_key: str,
518
- stripe_js_id: str,
519
- ) -> dict[str, Any]:
520
- options = (
521
- init_payload.get("elements_options")
522
- if isinstance(init_payload.get("elements_options"), dict)
523
- else {}
524
- )
525
- amount = options.get("amount")
526
- currency = _text(options.get("currency") or init_payload.get("currency"))
527
- payment_config = _text(options.get("payment_method_configuration"))
528
- method_types = options.get("payment_method_types")
529
- if not isinstance(method_types, list) or not method_types:
530
- method_types = ["card", "paypal"]
531
- params: dict[str, Any] = {
532
- "client_betas[0]": "custom_checkout_server_updates_1",
533
- "client_betas[1]": "custom_checkout_manual_approval_1",
534
- "deferred_intent[mode]": "subscription",
535
- "deferred_intent[amount]": str(amount if amount is not None else "2000"),
536
- "deferred_intent[currency]": currency or _text(config.bind_currency).lower() or "usd",
537
- "deferred_intent[setup_future_usage]": "off_session",
538
- "currency": currency or _text(config.bind_currency).lower() or "usd",
539
- "key": publishable_key,
540
- "_stripe_version": STRIPE_BETAS,
541
- "elements_init_source": "custom_checkout",
542
- "referrer_host": "chatgpt.com",
543
- "stripe_js_id": stripe_js_id,
544
- "locale": (_text(config.locale).split("-", 1)[0] or "zh"),
545
- "type": "deferred_intent",
546
- "checkout_session_id": payment_page_id,
547
- }
548
- for index, method_type in enumerate(method_types[:4]):
549
- params[f"deferred_intent[payment_method_types][{index}]"] = _text(
550
- method_type
551
- )
552
- if payment_config:
553
- params[
554
- "deferred_intent[payment_method_configuration][id]"
555
- ] = payment_config
556
- response = session.get(
557
- f"{STRIPE_BASE}/v1/elements/sessions",
558
- params=params,
559
- headers=_stripe_headers(publishable_key, "https://js.stripe.com/"),
560
- timeout=config.timeout,
561
- )
562
- if int(getattr(response, "status_code", 0) or 0) >= 400:
563
- raise CardPaymentError(f"elements session: {_response_error(response)}")
564
- payload = _response_json(response)
565
- if not payload:
566
- raise CardPaymentError("elements session: empty response")
567
- return payload
568
-
569
-
570
- def _setup_confirm(
571
- session: Any,
572
- config: CardPaymentConfig,
573
- init_payload: dict[str, Any],
574
- checkout_id: str,
575
- processor: str,
576
- publishable_key: str,
577
- setup_id: str,
578
- client_secret: str,
579
- stripe_js_id: str,
580
- *,
581
- attempt: int,
582
- ) -> tuple[Any, dict[str, Any]]:
583
- external_payment_method = _text(config.payment_method_id)
584
- billing = _billing_fields(config)
585
- elements_session_id = _find_identifier(init_payload, ("elements_session_",))
586
- wallet_config_id = _find_key(init_payload, ("wallet_config_id",))
587
- guid = f"{uuid.uuid4()}{uuid.uuid4().hex[:6]}"
588
- muid = f"{uuid.uuid4()}{uuid.uuid4().hex[:6]}"
589
- sid = f"{uuid.uuid4()}{uuid.uuid4().hex[:6]}"
590
- body: dict[str, Any] = {
591
- "set_as_default_payment_method": "true",
592
- "expected_payment_method_type": "card",
593
- "use_stripe_sdk": "true",
594
- "key": publishable_key,
595
- "_stripe_version": STRIPE_VERSION,
596
- "client_attribution_metadata[client_session_id]": stripe_js_id,
597
- "client_attribution_metadata[merchant_integration_source]": "elements",
598
- "client_attribution_metadata[merchant_integration_subtype]": "card-element",
599
- "client_attribution_metadata[merchant_integration_version]": "2017",
600
- "client_secret": client_secret,
601
- }
602
- if external_payment_method:
603
- body["payment_method"] = external_payment_method
604
- else:
605
- card = _card_fields(config.card)
606
- body.update({
607
- "payment_method_data[type]": "card",
608
- "payment_method_data[billing_details][name]": billing["name"],
609
- "payment_method_data[allow_redisplay]": "always",
610
- "payment_method_data[card][number]": card["number"],
611
- "payment_method_data[card][cvc]": card["cvc"],
612
- "payment_method_data[card][exp_month]": card["exp_month"],
613
- "payment_method_data[card][exp_year]": card["exp_year"],
614
- "payment_method_data[guid]": guid,
615
- "payment_method_data[muid]": muid,
616
- "payment_method_data[sid]": sid,
617
- "payment_method_data[pasted_fields]": "number,exp,cvc",
618
- "payment_method_data[payment_user_agent]": "stripe.js/3704557c13; stripe-js-v3/3704557c13; card-element",
619
- "payment_method_data[referrer]": APP_BASE,
620
- "payment_method_data[time_on_page]": str(random.randint(300_000, 750_000)),
621
- "payment_method_data[client_attribution_metadata][client_session_id]": stripe_js_id,
622
- "payment_method_data[client_attribution_metadata][merchant_integration_source]": "elements",
623
- "payment_method_data[client_attribution_metadata][merchant_integration_subtype]": "card-element",
624
- "payment_method_data[client_attribution_metadata][merchant_integration_version]": "2017",
625
- })
626
- if billing["email"]:
627
- body["payment_method_data[billing_details][email]"] = billing["email"]
628
- for field in ("line1", "line2", "city", "state", "postal_code", "country"):
629
- value = billing.get(field, "")
630
- if value:
631
- body[f"payment_method_data[billing_details][address][{field}]"] = (
632
- value.upper() if field == "country" else value
633
- )
634
- if billing["phone"]:
635
- body["payment_method_data[billing_details][phone]"] = billing["phone"]
636
- if billing["postal_code"]:
637
- body["payment_method_data[pasted_fields]"] = "number,exp,cvc,zip"
638
- if _text(config.hcaptcha_token):
639
- body["radar_options[hcaptcha_token]"] = _text(config.hcaptcha_token)
640
- if elements_session_id and not external_payment_method:
641
- body["payment_method_data[client_attribution_metadata][elements_session_id]"] = elements_session_id
642
- if wallet_config_id and not external_payment_method:
643
- body["payment_method_data[client_attribution_metadata][wallet_config_id]"] = wallet_config_id
644
- body["client_attribution_metadata[wallet_config_id]"] = wallet_config_id
645
- response, payload = _post_form(
646
- session,
647
- f"{STRIPE_BASE}/v1/setup_intents/{setup_id}/confirm",
648
- body,
649
- key=publishable_key,
650
- referer=f"{APP_BASE}/checkout/{processor}/{checkout_id}",
651
- timeout=config.timeout,
652
- stage=f"setup confirm attempt {attempt}",
653
- )
654
- return response, payload
655
-
656
-
657
- def _prepare_hcaptcha_token(
658
- config: CardPaymentConfig,
659
- *,
660
- proxy: str,
661
- logger: Callable[[str], None],
662
- ) -> str:
663
- supplied = _text(config.hcaptcha_token)
664
- if supplied:
665
- return supplied
666
- provider = _text(config.captcha_provider).lower()
667
- api_key = _text(config.captcha_key)
668
- api_url = _text(config.captcha_api_url)
669
- if not provider or not api_key:
670
- return ""
671
- if provider != "aixiangshu" and "aixiangshu.com" not in api_url.lower():
672
- _log(logger, f"Stripe hCaptcha provider not wired for card flow: {provider}")
673
- return ""
674
- try:
675
- from .paypal_plus.signup import _solve_aixiangshu_gateway
676
-
677
- token, _solution = _solve_aixiangshu_gateway(
678
- api_url=api_url or "https://sub.aixiangshu.com/captcha",
679
- api_key=api_key,
680
- task={
681
- "type": "HCaptchaTask",
682
- "websiteURL": _text(config.hcaptcha_website_url)
683
- or STRIPE_HCAPTCHA_URL,
684
- "websiteKey": _text(config.hcaptcha_site_key)
685
- or STRIPE_HCAPTCHA_SITE_KEY,
686
- "isInvisible": True,
687
- "proxy": _text(proxy),
688
- },
689
- timeout=max(60, min(300, int(config.timeout or DEFAULT_TIMEOUT))),
690
- label="stripe-hcaptcha",
691
- token_fields=("gRecaptchaResponse", "hcaptchaToken", "token"),
692
- )
693
- except Exception as exc:
694
- raise CardPaymentError(
695
- f"Stripe hCaptcha solve failed: {type(exc).__name__}"
696
- ) from exc
697
- if not token:
698
- raise CardPaymentError("Stripe hCaptcha solve returned no token")
699
- _log(logger, "Stripe hCaptcha token ready")
700
- return token
701
-
702
-
703
- def run_card_payment(
704
- config: CardPaymentConfig,
705
- *,
706
- proxy: str = "",
707
- logger: Callable[[str], None] | None = None,
708
- is_cancelled: Callable[[], bool] | None = None,
709
- session_factory: Callable[[CardPaymentConfig, str], Any] | None = None,
710
- refresh_checkout: Callable[[], dict[str, Any]] | None = None,
711
- ) -> dict[str, Any]:
712
- """Run bind-card -> checkout-confirm -> subscription verification."""
713
- log = logger or (lambda _message: None)
714
- config.token = _text(config.token)
715
- if not config.token:
716
- raise CardPaymentError("missing access token")
717
- external_payment_method = _text(config.payment_method_id)
718
- if external_payment_method:
719
- if not re.fullmatch(r"pm_[A-Za-z0-9_-]+", external_payment_method):
720
- raise CardPaymentError("invalid browser PaymentMethod id")
721
- else:
722
- _card_fields(config.card)
723
- session = session_factory(config, proxy) if session_factory else _new_session(config, proxy)
724
- checkout: dict[str, Any] = {}
725
- init_payload: dict[str, Any] = {}
726
- try:
727
- _check_cancel(is_cancelled)
728
- bind_checkout: dict[str, Any] = {}
729
- if _text(config.checkout_id):
730
- checkout = {
731
- "checkout_session_id": _text(config.checkout_id),
732
- "processor_entity": _text(config.processor_entity),
733
- "publishable_key": _text(config.publishable_key),
734
- }
735
- log(f"using canonical zero-amount checkout: {_mask(config.checkout_id)}")
736
- else:
737
- checkout = _checkout_create(session, config)
738
- checkout_id = _checkout_id(checkout)
739
- if not checkout_id:
740
- raise CardPaymentError("checkout create: missing checkout id")
741
- processor = _processor_entity(checkout, config.country)
742
- publishable_key = _text(config.publishable_key) or _find_key(
743
- checkout, ("publishable_key", "publishableKey")
744
- )
745
- config.checkout_id = checkout_id
746
- account_id = _text(config.account_id) or _find_key(
747
- checkout, ("account_id", "accountId")
748
- )
749
- if not account_id:
750
- raise CardPaymentError("payment method prepare: missing account id")
751
-
752
- stripe_js_id = str(uuid.uuid4())
753
- bind_step_key = (
754
- "payment_prepare" if _text(config.flow_mode) == "link_pay" else "bind"
755
- )
756
- bind_step_label = (
757
- "正在验证账号支付方式"
758
- if bind_step_key == "payment_prepare"
759
- else "正在执行绑卡"
760
- )
761
- log(f"FLOW_STEP:{bind_step_key}:start:{bind_step_label}")
762
- if config.strong_bind_direct:
763
- if not checkout_id.startswith("oaics_"):
764
- raise CardPaymentError(
765
- "strong bind: expected PH oaics checkout context"
766
- )
767
- checkout_context = session.get(
768
- f"{APP_BASE}/backend-api/payments/checkout/{processor}/{checkout_id}",
769
- headers=_app_headers(
770
- f"{APP_BASE}/checkout/{processor}/{checkout_id}",
771
- "/backend-api/payments/checkout/{processor_entity}/{checkout_session_id}",
772
- ),
773
- timeout=config.timeout,
774
- )
775
- if int(getattr(checkout_context, "status_code", 0) or 0) >= 400:
776
- raise CardPaymentError(
777
- f"strong bind checkout context: {_response_error(checkout_context)}"
778
- )
779
- payment_method_prepare_payload = _post_json(
780
- session,
781
- f"{APP_BASE}/backend-api/payments/payment_method",
782
- {"account_id": account_id},
783
- timeout=config.timeout,
784
- stage="payment method prepare",
785
- route="/backend-api/payments/payment_method",
786
- )
787
- stripe_context = {
788
- "payment_method_prepare": payment_method_prepare_payload
789
- }
790
- setup_secret = _find_client_secret(payment_method_prepare_payload)
791
- setup_id = _setup_intent_id(
792
- payment_method_prepare_payload, setup_secret
793
- )
794
- publishable_key = _publishable_key_for_setup(
795
- setup_secret, publishable_key
796
- )
797
- log(f"PH oaics strong-bind SetupIntent ready: {_mask(setup_id)}")
798
- else:
799
- payment_page_id = _text(config.payment_page_id)
800
- if not payment_page_id:
801
- bind_checkout = _checkout_create(
802
- session,
803
- config,
804
- country=_text(config.bind_country) or "US",
805
- currency=_text(config.bind_currency) or "USD",
806
- promo_campaign="",
807
- )
808
- payment_page_id = _find_identifier(
809
- bind_checkout, ("cs_live_", "cs_test_", "cs_")
810
- )
811
- if not payment_page_id.startswith(("cs_live_", "cs_test_", "cs_")):
812
- raise CardPaymentError("bind checkout: invalid Stripe payment page id")
813
- publishable_key = _find_key(
814
- bind_checkout, ("publishable_key", "publishableKey")
815
- ) or publishable_key or _find_identifier(
816
- bind_checkout, ("pk_live_", "pk_test_")
817
- )
818
- init_payload, stripe_js_id = _init_payment_page(
819
- session, config, payment_page_id, publishable_key, processor
820
- )
821
- elements_payload = _create_elements_session(
822
- session,
823
- config,
824
- init_payload,
825
- payment_page_id,
826
- publishable_key,
827
- stripe_js_id,
828
- )
829
- payment_method_prepare_payload = _post_json(
830
- session,
831
- f"{APP_BASE}/backend-api/payments/payment_method",
832
- {"account_id": account_id},
833
- timeout=config.timeout,
834
- stage="payment method prepare",
835
- route="/backend-api/payments/payment_method",
836
- )
837
- stripe_context = {
838
- "init": init_payload,
839
- "elements": elements_payload,
840
- "payment_method_prepare": payment_method_prepare_payload,
841
- }
842
- setup_secret = (
843
- _find_client_secret(payment_method_prepare_payload)
844
- or _find_client_secret(elements_payload)
845
- or _find_client_secret(init_payload)
846
- )
847
- setup_id = (
848
- _setup_intent_id(payment_method_prepare_payload, setup_secret)
849
- or _setup_intent_id(elements_payload, setup_secret)
850
- or _setup_intent_id(init_payload, setup_secret)
851
- )
852
- log(f"Stripe payment-page SetupIntent ready: {_mask(setup_id)}")
853
- if not setup_id or not setup_secret:
854
- raise CardPaymentError("strong bind: missing SetupIntent credentials")
855
- if not publishable_key.startswith(("pk_live_", "pk_test_")):
856
- raise CardPaymentError("strong bind: missing matching publishable key")
857
-
858
- config.hcaptcha_token = _prepare_hcaptcha_token(
859
- config,
860
- proxy=proxy,
861
- logger=log,
862
- )
863
-
864
- confirm_response = None
865
- confirm_payload: dict[str, Any] = {}
866
- max_attempts = max(1, min(3, int(config.max_setup_confirm_attempts or 1)))
867
- for attempt in range(1, max_attempts + 1):
868
- _check_cancel(is_cancelled)
869
- confirm_response, confirm_payload = _setup_confirm(
870
- session,
871
- config,
872
- stripe_context,
873
- checkout_id,
874
- processor,
875
- publishable_key,
876
- setup_id,
877
- setup_secret,
878
- stripe_js_id,
879
- attempt=attempt,
880
- )
881
- status = int(getattr(confirm_response, "status_code", 0) or 0)
882
- if status == 200:
883
- break
884
- if status == 402 and attempt < max_attempts:
885
- log(f"setup confirm returned 402; retry {attempt + 1}/{max_attempts}")
886
- continue
887
- raise CardPaymentError(f"setup confirm: {_response_error(confirm_response)}")
888
- _require_setup_succeeded(confirm_payload, "setup confirm")
889
- payment_method_id = _find_key(confirm_payload, ("payment_method", "payment_method_id")) or _find_identifier(confirm_payload, ("pm_",))
890
- if not payment_method_id:
891
- raise CardPaymentError("setup confirm: missing PaymentMethod")
892
- log(f"payment method created: {_mask(payment_method_id)}")
893
-
894
- customer = _find_identifier(
895
- {"stripe_context": stripe_context, "setup_confirm": confirm_payload},
896
- ("cus_",),
897
- ) or _find_identifier(bind_checkout or checkout, ("cus_",))
898
- if not customer:
899
- for payload in (
900
- confirm_payload,
901
- stripe_context,
902
- bind_checkout,
903
- checkout,
904
- ):
905
- candidate = _find_key(payload, ("customer", "customer_id", "customerId"))
906
- if isinstance(candidate, str) and candidate:
907
- customer = candidate
908
- break
909
-
910
- app_payment_methods_status = 0
911
- if account_id:
912
- payment_methods = session.get(
913
- f"{APP_BASE}/backend-api/payments/payment_methods",
914
- params={"account_id": account_id},
915
- headers=_app_headers(
916
- f"{APP_BASE}/",
917
- "/backend-api/payments/payment_methods",
918
- ),
919
- timeout=config.timeout,
920
- )
921
- app_payment_methods_status = int(getattr(payment_methods, "status_code", 0) or 0)
922
- if app_payment_methods_status >= 400:
923
- raise CardPaymentError(f"payment methods sync: {_response_error(payment_methods)}")
924
-
925
- stripe_payment_methods_status = 0
926
- if customer:
927
- stripe_payment_methods = session.get(
928
- f"{STRIPE_BASE}/v1/payment_methods",
929
- params={"customer": customer, "type": "card", "limit": 30},
930
- headers=_stripe_headers(
931
- publishable_key,
932
- f"{APP_BASE}/checkout/{processor}/{checkout_id}",
933
- ),
934
- timeout=config.timeout,
935
- )
936
- stripe_payment_methods_status = int(
937
- getattr(stripe_payment_methods, "status_code", 0) or 0
938
- )
939
- if stripe_payment_methods_status >= 400:
940
- raise CardPaymentError(
941
- f"stripe payment methods: {_response_error(stripe_payment_methods)}"
942
- )
943
-
944
- log(
945
- f"FLOW_STEP:{bind_step_key}:done:支付方式 {_mask(payment_method_id)} 已确认并同步"
946
- )
947
-
948
- if config.stop_after_bind:
949
- log("card bind completed; stopped before checkout refresh and payment")
950
- return {
951
- "ok": True,
952
- "checkout_id": checkout_id,
953
- "processor_entity": processor,
954
- "payment_method": _mask(payment_method_id),
955
- "card_last4": _payment_card_last4(config),
956
- "setup_status": _text(confirm_payload.get("status")) or "succeeded",
957
- "app_payment_methods_status": app_payment_methods_status,
958
- "stripe_payment_methods_status": stripe_payment_methods_status,
959
- "bind_only": True,
960
- }
961
-
962
- if refresh_checkout is not None:
963
- _check_cancel(is_cancelled)
964
- refreshed_checkout = refresh_checkout() or {}
965
- refreshed_id = _checkout_id(refreshed_checkout)
966
- refreshed_amount = _text(refreshed_checkout.get("amount"))
967
- if not refreshed_id.startswith("oaics_"):
968
- raise CardPaymentError(
969
- "checkout refresh: missing canonical oaics checkout id"
970
- )
971
- if refreshed_amount != "0":
972
- raise CardPaymentError(
973
- f"checkout refresh: expected zero amount, got {refreshed_amount or 'unknown'}"
974
- )
975
- checkout_id = refreshed_id
976
- processor = _processor_entity(refreshed_checkout, config.country)
977
- refreshed_key = _text(
978
- refreshed_checkout.get("_publishable_key")
979
- )
980
- if refreshed_key.startswith(("pk_live_", "pk_test_")):
981
- publishable_key = refreshed_key
982
- refreshed_currency = _text(refreshed_checkout.get("currency"))
983
- if refreshed_currency:
984
- config.currency = refreshed_currency.upper()
985
- config.checkout_id = checkout_id
986
- log(f"checkout refreshed after card bind: {_mask(checkout_id)}")
987
-
988
- log("FLOW_STEP:payment:start:正在提交支付确认")
989
-
990
- checkout_context = session.get(
991
- f"{APP_BASE}/backend-api/payments/checkout/{processor}/{checkout_id}",
992
- headers=_app_headers(
993
- f"{APP_BASE}/checkout/{processor}/{checkout_id}",
994
- "/backend-api/payments/checkout/{processor_entity}/{checkout_session_id}",
995
- ),
996
- timeout=config.timeout,
997
- )
998
- if int(getattr(checkout_context, "status_code", 0) or 0) >= 400:
999
- raise CardPaymentError(
1000
- f"canonical checkout restore: {_response_error(checkout_context)}"
1001
- )
1002
-
1003
- billing_country = _billing_fields(config).get("country") or config.country.upper()
1004
- _post_json(
1005
- session,
1006
- f"{APP_BASE}/backend-api/payments/checkout/taxes",
1007
- {
1008
- "checkout_session_id": checkout_id,
1009
- "processor_entity": processor,
1010
- "billing_country": billing_country.upper(),
1011
- "billing_currency": config.currency.upper(),
1012
- "currency": config.currency.upper(),
1013
- },
1014
- timeout=config.timeout,
1015
- stage="checkout taxes",
1016
- referer=f"{APP_BASE}/checkout/{processor}/{checkout_id}",
1017
- route="/backend-api/payments/checkout/taxes",
1018
- )
1019
-
1020
- # Billing details are attached while the PaymentMethod is created by
1021
- # the SetupIntent confirmation above. Updating /v1/payment_methods/{id}
1022
- # afterwards is a secret-key-only operation and is redundant here.
1023
- log("billing details supplied during SetupIntent confirmation")
1024
-
1025
- token_body: dict[str, Any] = {
1026
- "payment_method": payment_method_id,
1027
- "setup_future_usage": "off_session",
1028
- "set_as_default_payment_method": "true",
1029
- "client_context[currency]": config.currency.lower(),
1030
- "client_context[mode]": "subscription",
1031
- "client_context[payment_method_types][0]": "card",
1032
- "client_context[payment_method_types][1]": "link",
1033
- "client_attribution_metadata[client_session_id]": stripe_js_id,
1034
- "client_attribution_metadata[merchant_integration_source]": "elements",
1035
- "client_attribution_metadata[merchant_integration_subtype]": "payment-element",
1036
- "client_attribution_metadata[merchant_integration_version]": "2021",
1037
- "client_attribution_metadata[payment_intent_creation_flow]": "deferred",
1038
- "client_attribution_metadata[payment_method_selection_flow]": "automatic",
1039
- "client_attribution_metadata[merchant_integration_additional_elements][0]": "expressCheckout",
1040
- "client_attribution_metadata[merchant_integration_additional_elements][1]": "payment",
1041
- "client_attribution_metadata[merchant_integration_additional_elements][2]": "address",
1042
- "key": publishable_key,
1043
- }
1044
- if customer:
1045
- token_body["client_context[customer]"] = customer
1046
- elements_session_id = _find_key(
1047
- stripe_context, ("elements_session_id", "elementsSessionId")
1048
- ) or _find_identifier(stripe_context, ("elements_session_",))
1049
- elements_session_config_id = _find_key(
1050
- stripe_context,
1051
- ("elements_session_config_id", "elementsSessionConfigId", "config_id"),
1052
- )
1053
- if elements_session_id:
1054
- token_body["client_attribution_metadata[elements_session_id]"] = (
1055
- elements_session_id
1056
- )
1057
- if elements_session_config_id:
1058
- token_body[
1059
- "client_attribution_metadata[elements_session_config_id]"
1060
- ] = elements_session_config_id
1061
- response, token_payload = _post_form(
1062
- session,
1063
- f"{STRIPE_BASE}/v1/confirmation_tokens",
1064
- token_body,
1065
- key=publishable_key,
1066
- referer=f"{APP_BASE}/checkout/{processor}/{checkout_id}",
1067
- timeout=config.timeout,
1068
- stage="confirmation token",
1069
- stripe_version=STRIPE_BETAS,
1070
- )
1071
- if int(getattr(response, "status_code", 0) or 0) >= 400:
1072
- raise CardPaymentError(f"confirmation token: {_response_error(response)}")
1073
- confirmation_token = _find_key(token_payload, ("confirmation_token", "confirmationToken")) or _find_identifier(token_payload, ("ctoken_", "ct_"))
1074
- if not confirmation_token:
1075
- raise CardPaymentError("confirmation token: missing token")
1076
-
1077
- app_confirm_payload = _post_json(
1078
- session,
1079
- f"{APP_BASE}/backend-api/payments/checkout/confirm",
1080
- {},
1081
- timeout=config.timeout,
1082
- stage="checkout confirm",
1083
- referer=f"{APP_BASE}/checkout/{processor}/{checkout_id}",
1084
- route="/backend-api/payments/checkout/confirm",
1085
- )
1086
- final_secret = (
1087
- _find_client_secret(app_confirm_payload)
1088
- or _find_client_secret(token_payload)
1089
- or _find_client_secret(confirm_payload)
1090
- or setup_secret
1091
- )
1092
- final_setup_id = (
1093
- _setup_intent_id(app_confirm_payload, final_secret)
1094
- or _setup_intent_id(token_payload, final_secret)
1095
- or _setup_intent_id(confirm_payload, final_secret)
1096
- or setup_id
1097
- )
1098
- if not final_setup_id or not final_secret:
1099
- raise CardPaymentError("checkout confirm: missing final SetupIntent credentials")
1100
- return_url = (
1101
- f"{APP_BASE}/checkout/verify?stripe_session_id={checkout_id}"
1102
- f"&processor_entity={processor}&plan_type=plus"
1103
- )
1104
- final_body = {
1105
- "client_secret": final_secret,
1106
- "confirmation_token": confirmation_token,
1107
- "key": publishable_key,
1108
- "return_url": return_url,
1109
- "use_stripe_sdk": "true",
1110
- "_stripe_version": STRIPE_BETAS,
1111
- "client_attribution_metadata[client_session_id]": stripe_js_id,
1112
- "client_attribution_metadata[merchant_integration_source]": "l1",
1113
- }
1114
- response, final_payload = _post_form(
1115
- session,
1116
- f"{STRIPE_BASE}/v1/setup_intents/{final_setup_id}/confirm",
1117
- final_body,
1118
- key=publishable_key,
1119
- referer=f"{APP_BASE}/checkout/{processor}/{checkout_id}",
1120
- timeout=config.timeout,
1121
- stage="final setup confirm",
1122
- )
1123
- if int(getattr(response, "status_code", 0) or 0) >= 400:
1124
- raise CardPaymentError(f"final setup confirm: {_response_error(response)}")
1125
- final_setup_status = _require_setup_succeeded(
1126
- final_payload, "final setup confirm"
1127
- )
1128
- _check_cancel(is_cancelled)
1129
-
1130
- log("FLOW_STEP:payment:done:支付确认已提交")
1131
- log("FLOW_STEP:verify:start:正在校验 Checkout 与订阅状态")
1132
-
1133
- verify = session.get(
1134
- f"{APP_BASE}/backend-api/payments/checkout/{processor}/{checkout_id}",
1135
- headers=_app_headers(
1136
- f"{APP_BASE}/checkout/verify",
1137
- "/backend-api/payments/checkout/{processor_entity}/{checkout_session_id}",
1138
- ),
1139
- timeout=config.timeout,
1140
- )
1141
- if int(getattr(verify, "status_code", 0) or 0) >= 400:
1142
- raise CardPaymentError(f"checkout verify: {_response_error(verify)}")
1143
- verify_page = None
1144
- success_data = None
1145
- auth_session = None
1146
- if not config.fast_verify:
1147
- verify_page = session.get(
1148
- f"{APP_BASE}/checkout/verify",
1149
- params={
1150
- "stripe_session_id": checkout_id,
1151
- "processor_entity": processor,
1152
- "plan_type": "plus",
1153
- },
1154
- headers=_app_headers(f"{APP_BASE}/checkout/{processor}/{checkout_id}"),
1155
- timeout=config.timeout,
1156
- )
1157
- success_data = session.get(
1158
- f"{APP_BASE}/payments/success.data",
1159
- params={"stripe_session_id": checkout_id},
1160
- headers=_app_headers(f"{APP_BASE}/checkout/verify"),
1161
- timeout=config.timeout,
1162
- )
1163
- auth_session = session.get(
1164
- f"{APP_BASE}/api/auth/session",
1165
- params={"reason": "checkout_success"},
1166
- headers=_app_headers(f"{APP_BASE}/checkout/verify"),
1167
- timeout=config.timeout,
1168
- )
1169
- subscription = None
1170
- subscription_plan = ""
1171
- # The subscription endpoint can lag a successful zero-amount SetupIntent
1172
- # by a fraction of a second. Poll briefly, but never report success from
1173
- # HTTP 200 alone: the account must actually show the Plus plan.
1174
- for subscription_attempt in range(1, 4):
1175
- _check_cancel(is_cancelled)
1176
- subscription = session.get(
1177
- f"{APP_BASE}/backend-api/subscriptions",
1178
- params={"account_id": account_id},
1179
- headers=_app_headers(
1180
- f"{APP_BASE}/", "/backend-api/subscriptions"
1181
- ),
1182
- timeout=config.timeout,
1183
- )
1184
- subscription_http = int(
1185
- getattr(subscription, "status_code", 0) or 0
1186
- )
1187
- if subscription_http >= 400:
1188
- raise CardPaymentError(
1189
- f"subscription verify: {_response_error(subscription)}"
1190
- )
1191
- subscription_payload = _response_json(subscription)
1192
- subscription_plan = _text(subscription_payload.get("plan_type"))
1193
- if subscription_plan.lower() == "plus":
1194
- break
1195
- if subscription_attempt < 3:
1196
- time.sleep(0.35)
1197
- if subscription_plan.lower() != "plus":
1198
- raise CardPaymentError(
1199
- "subscription verify: Plus plan was not activated"
1200
- )
1201
- log("payment succeeded and checkout verified")
1202
- log("FLOW_STEP:verify:done:Checkout 与订阅状态校验完成")
1203
- return {
1204
- "ok": True,
1205
- "checkout_id": checkout_id,
1206
- "processor_entity": processor,
1207
- "payment_method": _mask(payment_method_id),
1208
- "card_last4": _payment_card_last4(config),
1209
- "setup_status": final_setup_status,
1210
- "verify_status": int(getattr(verify, "status_code", 0) or 0),
1211
- "verify_page_status": int(getattr(verify_page, "status_code", 0) or 0),
1212
- "success_data_status": int(getattr(success_data, "status_code", 0) or 0),
1213
- "auth_session_status": int(getattr(auth_session, "status_code", 0) or 0),
1214
- "app_payment_methods_status": app_payment_methods_status,
1215
- "stripe_payment_methods_status": stripe_payment_methods_status,
1216
- "subscription_status": int(getattr(subscription, "status_code", 0) or 0) if subscription is not None else 0,
1217
- "subscription_plan": subscription_plan,
1218
- }
1219
- finally:
1220
- close = getattr(session, "close", None)
1221
- if callable(close):
1222
- try:
1223
- close()
1224
- except Exception:
1225
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
standalone_core/fingerprint_store.py DELETED
@@ -1,365 +0,0 @@
1
- """Sticky per-account browser profiles shared by every standalone HTTP stage.
2
-
3
- The profile implementation is vendored from the registration project so this
4
- service remains independent from the parent application at runtime.
5
- """
6
- from __future__ import annotations
7
-
8
- import hashlib
9
- import json
10
- import shutil
11
- import threading
12
- import uuid
13
- from datetime import datetime, timezone
14
- from pathlib import Path
15
- from typing import Any
16
-
17
- from .register_profile import (
18
- Profile,
19
- apply_region_fingerprint,
20
- choose_tls_impersonate,
21
- profile_from_json,
22
- profile_headers,
23
- profile_summary,
24
- profile_to_json,
25
- random_profile,
26
- validate_profile,
27
- )
28
-
29
-
30
- STORE_PATH = Path(__file__).resolve().parents[1] / "fingerprint_profiles.json"
31
- _LOCK = threading.RLock()
32
- _STORE_CACHE: dict[str, Any] | None = None
33
- _STORE_CACHE_PATH = ""
34
- _STORE_CACHE_MTIME_NS = -1
35
-
36
-
37
- def _text(value: Any) -> str:
38
- return str(value or "").strip()
39
-
40
-
41
- def _account_key(account_id: str) -> str:
42
- return hashlib.sha256(_text(account_id).encode("utf-8")).hexdigest()
43
-
44
-
45
- def _device_id(account_id: str) -> str:
46
- return str(uuid.uuid5(uuid.NAMESPACE_URL, f"direct-bind:{_text(account_id)}"))
47
-
48
-
49
- def _profile_id(profile: Profile, device_id: str) -> str:
50
- material = f"{profile_to_json(profile)}\n{_text(device_id)}".encode("utf-8")
51
- return hashlib.sha256(material).hexdigest()[:16]
52
-
53
-
54
- def _device_identity(account_id: str, platform_os: str) -> tuple[str, str]:
55
- digest = hashlib.blake2s(
56
- f"{platform_os}:{_text(account_id)}".encode("utf-8"), digest_size=8
57
- ).digest()
58
- alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
59
- suffix = "".join(alphabet[item % len(alphabet)] for item in digest[:7])
60
- if platform_os == "macOS":
61
- name = f"iMac-{suffix[:5]}"
62
- separator = ":"
63
- else:
64
- prefix = ("DESKTOP", "LAPTOP", "USER-PC")[digest[7] % 3]
65
- name = f"{prefix}-{suffix}"
66
- separator = "-"
67
- mac = bytearray(digest[:6])
68
- mac[0] = (mac[0] | 0x02) & 0xFE
69
- return name, separator.join(f"{part:02X}" for part in mac)
70
-
71
-
72
- def _read_store(path: Path) -> dict[str, Any] | None:
73
- if not path.exists():
74
- return None
75
- try:
76
- payload = json.loads(path.read_text(encoding="utf-8-sig") or "{}")
77
- except (OSError, ValueError, json.JSONDecodeError):
78
- return None
79
- if not isinstance(payload, dict):
80
- return None
81
- accounts = payload.get("accounts")
82
- if not isinstance(accounts, dict):
83
- return None
84
- return {"version": 3, "accounts": accounts}
85
-
86
-
87
- def _load_store() -> dict[str, Any]:
88
- global _STORE_CACHE, _STORE_CACHE_PATH, _STORE_CACHE_MTIME_NS
89
- cache_path = str(STORE_PATH.resolve())
90
- try:
91
- mtime_ns = STORE_PATH.stat().st_mtime_ns
92
- except OSError:
93
- mtime_ns = -1
94
- if (
95
- _STORE_CACHE is not None
96
- and cache_path == _STORE_CACHE_PATH
97
- and mtime_ns == _STORE_CACHE_MTIME_NS
98
- ):
99
- return _STORE_CACHE
100
- primary = _read_store(STORE_PATH)
101
- if primary is not None:
102
- payload = primary
103
- else:
104
- backup = _read_store(STORE_PATH.with_suffix(".json.bak"))
105
- payload = backup if backup is not None else {"version": 3, "accounts": {}}
106
- _STORE_CACHE = payload
107
- _STORE_CACHE_PATH = cache_path
108
- _STORE_CACHE_MTIME_NS = mtime_ns
109
- return payload
110
-
111
-
112
- def _save_store(payload: dict[str, Any]) -> None:
113
- global _STORE_CACHE, _STORE_CACHE_PATH, _STORE_CACHE_MTIME_NS
114
- temporary = STORE_PATH.with_suffix(".json.tmp")
115
- backup = STORE_PATH.with_suffix(".json.bak")
116
- payload["version"] = 3
117
- temporary.write_text(
118
- json.dumps(payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True),
119
- encoding="utf-8",
120
- )
121
- if STORE_PATH.exists() and _read_store(STORE_PATH) is not None:
122
- shutil.copy2(STORE_PATH, backup)
123
- temporary.replace(STORE_PATH)
124
- _STORE_CACHE = payload
125
- _STORE_CACHE_PATH = str(STORE_PATH.resolve())
126
- _STORE_CACHE_MTIME_NS = STORE_PATH.stat().st_mtime_ns
127
-
128
-
129
- def audit_fingerprint(profile: Profile, device_id: str) -> dict[str, Any]:
130
- """Validate cross-layer fields before the first outbound request."""
131
- validation = validate_profile(profile)
132
- errors = list(validation.errors)
133
- try:
134
- uuid.UUID(_text(device_id))
135
- except (ValueError, AttributeError):
136
- errors.append("device id must be a UUID")
137
- headers = profile_headers(profile, high_entropy=True)
138
- if headers.get("user-agent") != profile.user_agent:
139
- errors.append("profile user-agent header drift")
140
- if headers.get("sec-ch-ua") != profile.sec_ch_ua:
141
- errors.append("profile sec-ch-ua header drift")
142
- if headers.get("accept-language") != profile.locale:
143
- errors.append("profile locale header drift")
144
- return {
145
- "ok": not errors,
146
- "errors": errors,
147
- "warnings": list(validation.warnings),
148
- "fingerprint_id": _profile_id(profile, device_id),
149
- }
150
-
151
-
152
- def _ensure_account_fingerprint(
153
- store: dict[str, Any], account_id: str, region: str
154
- ) -> tuple[Profile, str, bool]:
155
- raw_account_id = _text(account_id)
156
- if not raw_account_id:
157
- raise ValueError("account id is required for fingerprint allocation")
158
- key = _account_key(raw_account_id)
159
- accounts = store["accounts"]
160
- old_entry = accounts.get(key)
161
- entry = dict(old_entry) if isinstance(old_entry, dict) else {}
162
- profile: Profile | None = None
163
- if entry:
164
- try:
165
- profile = profile_from_json(entry.get("profile"))
166
- except ValueError:
167
- profile = None
168
- requested_region = _text(region).upper() or "US"
169
- dirty = False
170
- if profile is None:
171
- profile = random_profile(region=requested_region)
172
- dirty = True
173
- elif profile.browser in {"chrome", "edge"} and profile.browser_major == 144:
174
- # The bundled curl transport has no chrome144 preset. Replace the old
175
- # mixed UA144/TLS142 snapshot once, then keep the upgraded identity sticky.
176
- device_name, mac_address = profile.device_name, profile.mac_address
177
- profile = random_profile(
178
- region=requested_region,
179
- browser=profile.browser,
180
- platform_os=profile.platform_os,
181
- chrome_major=146,
182
- hardware_profile=profile.hardware_profile,
183
- )
184
- profile.device_name = device_name
185
- profile.mac_address = mac_address
186
- dirty = True
187
- validation = validate_profile(profile)
188
- if not validation.valid:
189
- raise ValueError("fingerprint profile mismatch: " + "; ".join(validation.errors))
190
- device_id = _text(entry.get("device_id")) or _device_id(raw_account_id)
191
- # Account/browser identity belongs to bind/payment pool 1. Link pool 2 may
192
- # use another exit country, but must not rewrite this sticky profile.
193
- if profile.region != requested_region:
194
- apply_region_fingerprint(profile, requested_region)
195
- dirty = True
196
- expected_tls = choose_tls_impersonate(
197
- browser=profile.browser,
198
- chrome_major=profile.browser_major,
199
- platform_os=profile.platform_os,
200
- )
201
- if profile.tls_impersonate != expected_tls:
202
- profile.tls_impersonate = expected_tls
203
- dirty = True
204
- if not profile.device_name or not profile.mac_address:
205
- profile.device_name, profile.mac_address = _device_identity(
206
- raw_account_id, profile.platform_os
207
- )
208
- dirty = True
209
- audit = audit_fingerprint(profile, device_id)
210
- if not audit["ok"]:
211
- raise ValueError("fingerprint bundle mismatch: " + "; ".join(audit["errors"]))
212
- serialized = profile_to_json(profile)
213
- now = datetime.now(timezone.utc).isoformat()
214
- updated = {
215
- **entry,
216
- "created_at": entry.get("created_at") or now,
217
- "device_id": device_id,
218
- "fingerprint_id": audit["fingerprint_id"],
219
- "profile": serialized,
220
- }
221
- if (
222
- updated.get("device_id") != entry.get("device_id")
223
- or updated.get("fingerprint_id") != entry.get("fingerprint_id")
224
- or updated.get("profile") != entry.get("profile")
225
- ):
226
- dirty = True
227
- if dirty:
228
- updated["updated_at"] = now
229
- accounts[key] = updated
230
- return profile, device_id, dirty
231
-
232
-
233
- def get_account_fingerprints(
234
- items: list[dict[str, Any]],
235
- ) -> list[tuple[Profile, str]]:
236
- """Allocate up to 500 sticky profiles with one store load and one atomic save."""
237
- if not isinstance(items, list) or not items:
238
- return []
239
- if len(items) > 500:
240
- raise ValueError("fingerprint batch cannot exceed 500 accounts")
241
- with _LOCK:
242
- store = _load_store()
243
- results: list[tuple[Profile, str]] = []
244
- dirty = False
245
- for item in items:
246
- profile, device_id, changed = _ensure_account_fingerprint(
247
- store,
248
- _text(item.get("account_id")),
249
- _text(item.get("region") or "US"),
250
- )
251
- results.append((profile, device_id))
252
- dirty = dirty or changed
253
- if dirty:
254
- _save_store(store)
255
- return results
256
-
257
-
258
- def get_account_fingerprint(
259
- account_id: str,
260
- *,
261
- region: str = "US",
262
- proxy: str = "",
263
- ) -> tuple[Profile, str]:
264
- """Return one persistent registration Profile and device id per account."""
265
- del proxy # Region is fixed by the bind/payment role, never inferred here.
266
- return get_account_fingerprints(
267
- [{"account_id": account_id, "region": region}]
268
- )[0]
269
-
270
-
271
- def optimize_fingerprint_store(region: str = "US") -> dict[str, int]:
272
- """Migrate stored profiles in one pass and one atomic write."""
273
- requested_region = _text(region).upper() or "US"
274
- with _LOCK:
275
- store = _load_store()
276
- accounts = store["accounts"]
277
- scanned = migrated = invalid = 0
278
- for key, raw_entry in list(accounts.items()):
279
- scanned += 1
280
- if not isinstance(raw_entry, dict):
281
- invalid += 1
282
- continue
283
- entry = dict(raw_entry)
284
- try:
285
- profile = profile_from_json(entry.get("profile"))
286
- except ValueError:
287
- invalid += 1
288
- continue
289
- if profile is None:
290
- invalid += 1
291
- continue
292
- changed = False
293
- if profile.browser in {"chrome", "edge"} and profile.browser_major == 144:
294
- device_name, mac_address = profile.device_name, profile.mac_address
295
- profile = random_profile(
296
- region=requested_region,
297
- browser=profile.browser,
298
- platform_os=profile.platform_os,
299
- chrome_major=146,
300
- hardware_profile=profile.hardware_profile,
301
- )
302
- profile.device_name = device_name
303
- profile.mac_address = mac_address
304
- changed = True
305
- if profile.region != requested_region:
306
- apply_region_fingerprint(profile, requested_region)
307
- changed = True
308
- expected_tls = choose_tls_impersonate(
309
- browser=profile.browser,
310
- chrome_major=profile.browser_major,
311
- platform_os=profile.platform_os,
312
- )
313
- if profile.tls_impersonate != expected_tls:
314
- profile.tls_impersonate = expected_tls
315
- changed = True
316
- device_id = _text(entry.get("device_id"))
317
- audit = audit_fingerprint(profile, device_id)
318
- if not audit["ok"]:
319
- invalid += 1
320
- continue
321
- serialized = profile_to_json(profile)
322
- if (
323
- serialized != entry.get("profile")
324
- or audit["fingerprint_id"] != entry.get("fingerprint_id")
325
- ):
326
- changed = True
327
- if changed:
328
- entry["profile"] = serialized
329
- entry["fingerprint_id"] = audit["fingerprint_id"]
330
- entry["updated_at"] = datetime.now(timezone.utc).isoformat()
331
- accounts[key] = entry
332
- migrated += 1
333
- if migrated:
334
- _save_store(store)
335
- return {"scanned": scanned, "migrated": migrated, "invalid": invalid}
336
-
337
-
338
- def extractor_profile(profile: Profile, device_id: str = "") -> dict[str, str]:
339
- """Adapt a registration Profile to the link extractor's header schema."""
340
- headers = profile_headers(profile, high_entropy=True)
341
- return {
342
- "name": f"register:{profile.browser}/{profile.browser_full_version}:{profile.hardware_profile}",
343
- "ua": profile.user_agent,
344
- "major": str(profile.browser_major),
345
- "full": profile.browser_full_version,
346
- "platform": profile.sec_ch_ua_platform.strip('"') or profile.platform_os,
347
- "arch": profile.architecture,
348
- "bitness": profile.bitness,
349
- "mobile": "?1" if profile.mobile else "?0",
350
- "platform_version": profile.platform_version,
351
- "sec_ch_ua": profile.sec_ch_ua,
352
- "sec_ch_ua_full_version_list": headers.get(
353
- "sec-ch-ua-full-version-list", profile.sec_ch_ua
354
- ),
355
- "accept_language": profile.locale,
356
- "oai_language": profile.language,
357
- "tls_impersonate": profile.tls_impersonate,
358
- "timezone": profile.timezone_id,
359
- "region": profile.region,
360
- "summary": profile_summary(profile),
361
- "fingerprint_id": _profile_id(
362
- profile,
363
- _text(device_id) or "profile-only",
364
- ),
365
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
standalone_core/ph_shortlink_extractor.py DELETED
@@ -1,1349 +0,0 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """
4
- 模式8独立提炼器
5
-
6
- 只保留模式8的两阶段短链流程:
7
- 1. 代理池1:创建 custom checkout,并携带优惠参数。
8
- 2. 代理池2:更新同一 checkout,激活优惠参数。
9
- 3. 校验金额与 oaics_,输出 ChatGPT checkout 短链。
10
-
11
- 脚本不内置 Token、代理、服务器密钥或其他模式。
12
-
13
- 推荐依赖:
14
- pip install curl_cffi
15
-
16
- 备用依赖:
17
- pip install requests
18
-
19
- 直接运行会打开图形界面:
20
- python mode8_standalone.py
21
-
22
- 命令行示例:
23
- python mode8_standalone.py --token-file token.txt \
24
- --pool1-file pool1.txt --pool2-file pool2.txt
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- import argparse
30
- import json
31
- import queue
32
- import random
33
- import re
34
- import sys
35
- import threading
36
- import time
37
- import uuid
38
- from dataclasses import dataclass
39
- from decimal import Decimal, InvalidOperation
40
- from pathlib import Path
41
- from typing import Any, Callable, Iterable
42
- from urllib.parse import urlsplit
43
-
44
- try:
45
- from curl_cffi import requests as curl_requests
46
- except Exception:
47
- curl_requests = None
48
-
49
- try:
50
- import requests as plain_requests
51
- except Exception:
52
- plain_requests = None
53
-
54
-
55
- CHECKOUT_URL = "https://chatgpt.com/backend-api/payments/checkout"
56
- CHECKOUT_UPDATE_URL = "https://chatgpt.com/backend-api/payments/checkout/update"
57
- CHECKOUT_TAXES_URL = "https://chatgpt.com/backend-api/payments/checkout/taxes"
58
- COUPON_CHECK_URL = "https://chatgpt.com/backend-api/promo_campaign/check_coupon"
59
- DEFAULT_TIMEOUT = 45
60
-
61
- FINGERPRINT_PROFILES = [
62
- {
63
- "name": "mac_chrome149_m2",
64
- "ua": (
65
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
66
- "AppleWebKit/537.36 (KHTML, like Gecko) "
67
- "Chrome/149.0.7827.102 Safari/537.36"
68
- ),
69
- "major": "149",
70
- "full": "149.0.7827.102",
71
- "platform": "macOS",
72
- "platform_version": "15.7.0",
73
- "arch": "arm",
74
- },
75
- {
76
- "name": "mac_chrome148_intel",
77
- "ua": (
78
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
79
- "AppleWebKit/537.36 (KHTML, like Gecko) "
80
- "Chrome/148.0.7748.91 Safari/537.36"
81
- ),
82
- "major": "148",
83
- "full": "148.0.7748.91",
84
- "platform": "macOS",
85
- "platform_version": "14.7.2",
86
- "arch": "x86",
87
- },
88
- {
89
- "name": "win_chrome146",
90
- "ua": (
91
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
92
- "AppleWebKit/537.36 (KHTML, like Gecko) "
93
- "Chrome/146.0.7423.118 Safari/537.36"
94
- ),
95
- "major": "146",
96
- "full": "146.0.7423.118",
97
- "platform": "Windows",
98
- "platform_version": "15.0.0",
99
- "arch": "x86",
100
- },
101
- {
102
- "name": "win_chrome145",
103
- "ua": (
104
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
105
- "AppleWebKit/537.36 (KHTML, like Gecko) "
106
- "Chrome/145.0.7339.207 Safari/537.36"
107
- ),
108
- "major": "145",
109
- "full": "145.0.7339.207",
110
- "platform": "Windows",
111
- "platform_version": "19.0.0",
112
- "arch": "x86",
113
- },
114
- ]
115
-
116
- HAR_PAYMENT_FINGERPRINT = {
117
- "name": "win_chrome150_har",
118
- "ua": (
119
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
120
- "AppleWebKit/537.36 (KHTML, like Gecko) "
121
- "Chrome/150.0.0.0 Safari/537.36"
122
- ),
123
- "major": "150",
124
- "full": "150.0.0.0",
125
- "platform": "Windows",
126
- "platform_version": "",
127
- "arch": "x86",
128
- "sec_ch_ua": (
129
- '"Not;A=Brand";v="8", "Chromium";v="150", '
130
- '"Google Chrome";v="150"'
131
- ),
132
- "accept_language": "zh-CN,zh;q=0.9",
133
- "oai_language": "zh-CN",
134
- "har_exact": "1",
135
- }
136
-
137
-
138
- class Mode8Error(RuntimeError):
139
- """模式8流程中的可读错误。"""
140
-
141
-
142
- def _find_token(value: Any) -> str:
143
- if isinstance(value, dict):
144
- for key in ("accessToken", "access_token", "token"):
145
- token = str(value.get(key) or "").strip()
146
- if token:
147
- return token
148
- for item in value.values():
149
- token = _find_token(item)
150
- if token:
151
- return token
152
- elif isinstance(value, list):
153
- for item in value:
154
- token = _find_token(item)
155
- if token:
156
- return token
157
- return ""
158
-
159
-
160
- def normalize_access_token(raw: str) -> str:
161
- token = str(raw or "").strip()
162
- if not token:
163
- return ""
164
- if token.startswith(("{", "[")):
165
- try:
166
- token = _find_token(json.loads(token)) or token
167
- except json.JSONDecodeError:
168
- pass
169
- if token.lower().startswith("bearer "):
170
- token = token.split(None, 1)[1].strip()
171
- chunks = [item for item in re.split(r"\s+", token) if item]
172
- for candidate in chunks:
173
- if candidate.count(".") == 2:
174
- return candidate
175
- return re.sub(r"\s+", "", token)
176
-
177
-
178
- def normalize_proxy(raw: str) -> str:
179
- """
180
- 接受以下格式:
181
- http://user:pass@host:port
182
- https://user:pass@host:port
183
- socks4://user:pass@host:port
184
- socks4a://user:pass@host:port
185
- socks5://user:pass@host:port
186
- socks5h://user:pass@host:port
187
- user:pass@host:port
188
- host:port
189
- host:port:user:pass
190
- """
191
- value = str(raw or "").strip().strip("\"'")
192
- if not value:
193
- return ""
194
-
195
- prefixed_four_part = re.match(
196
- r"^(?P<scheme>https?|socks4a?|socks5h?)://"
197
- r"(?P<host>\[[^\]]+\]|[^:/\s]+):(?P<port>\d+):"
198
- r"(?P<user>[^:\s]+):(?P<password>.+)$",
199
- value,
200
- flags=re.IGNORECASE,
201
- )
202
- if prefixed_four_part:
203
- item = prefixed_four_part.groupdict()
204
- value = (
205
- f"{item['scheme'].lower()}://{item['user']}:{item['password']}"
206
- f"@{item['host']}:{item['port']}"
207
- )
208
-
209
- if "://" not in value:
210
- parts = value.split(":")
211
- if len(parts) >= 4 and parts[1].isdigit():
212
- host, port, username = parts[0], parts[1], parts[2]
213
- password = ":".join(parts[3:])
214
- value = f"http://{username}:{password}@{host}:{port}"
215
- else:
216
- value = f"http://{value}"
217
-
218
- scheme_match = re.match(r"^(?P<scheme>[a-z][a-z0-9+.-]*)://", value, re.IGNORECASE)
219
- if not scheme_match:
220
- return ""
221
- scheme = scheme_match.group("scheme").lower()
222
- aliases = {"socks": "socks5h"}
223
- scheme = aliases.get(scheme, scheme)
224
- supported = {"http", "https", "socks4", "socks4a", "socks5", "socks5h"}
225
- if scheme not in supported:
226
- raise ValueError(
227
- "代理协议不受支持;可用 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H"
228
- )
229
- return f"{scheme}://{value.split('://', 1)[1]}"
230
-
231
-
232
- def split_proxy_pool(raw: str, limit: int = 500) -> list[str]:
233
- items: list[str] = []
234
- seen: set[str] = set()
235
- for part in re.split(r"[\r\n,;]+", str(raw or "")):
236
- candidate = normalize_proxy(part)
237
- if candidate and candidate not in seen:
238
- seen.add(candidate)
239
- items.append(candidate)
240
- if len(items) >= limit:
241
- break
242
- return items
243
-
244
-
245
- def mask_proxy(proxy: str) -> str:
246
- if not proxy:
247
- return "直连"
248
- try:
249
- parsed = urlsplit(proxy)
250
- host = parsed.hostname or "custom"
251
- port = f":{parsed.port}" if parsed.port else ""
252
- auth = "***@" if parsed.username else ""
253
- return f"{parsed.scheme or 'http'}://{auth}{host}{port}"
254
- except Exception:
255
- return "custom"
256
-
257
-
258
- def resolve_proxy_placeholders(proxy: str) -> str:
259
- value = str(proxy or "")
260
- replacements = {
261
- "{sid}": uuid.uuid4().hex[:12],
262
- "{{sid}}": uuid.uuid4().hex[:12],
263
- "{ts}": str(int(time.time())),
264
- "{{ts}}": str(int(time.time())),
265
- "{ms}": str(int(time.time() * 1000)),
266
- "{{ms}}": str(int(time.time() * 1000)),
267
- "{uuid}": uuid.uuid4().hex,
268
- "{{uuid}}": uuid.uuid4().hex,
269
- "{rand}": str(random.randint(100000, 999999)),
270
- "{{rand}}": str(random.randint(100000, 999999)),
271
- }
272
- for marker, replacement in replacements.items():
273
- value = value.replace(marker, replacement)
274
- return value
275
-
276
-
277
- def random_fingerprint() -> dict[str, str]:
278
- profile = dict(random.choice(FINGERPRINT_PROFILES))
279
- grease_short, grease_full = random.choice(
280
- [
281
- ('"Not_A Brand";v="24"', '"Not_A Brand";v="24.0.0.0"'),
282
- ('"Not.A/Brand";v="8"', '"Not.A/Brand";v="8.0.0.0"'),
283
- ]
284
- )
285
- major = profile["major"]
286
- full = profile["full"]
287
- profile["sec_ch_ua"] = (
288
- f'"Google Chrome";v="{major}", "Chromium";v="{major}", {grease_short}'
289
- )
290
- profile["sec_ch_ua_full_version_list"] = (
291
- f'"Google Chrome";v="{full}", "Chromium";v="{full}", {grease_full}'
292
- )
293
- return profile
294
-
295
-
296
- def default_session_factory(impersonate: str = "chrome146") -> Any:
297
- if curl_requests is not None:
298
- session = curl_requests.Session(impersonate=impersonate or "chrome146")
299
- elif plain_requests is not None:
300
- session = plain_requests.Session()
301
- else:
302
- raise Mode8Error("缺少 HTTP 依赖,请执行:pip install curl_cffi")
303
- if hasattr(session, "trust_env"):
304
- session.trust_env = False
305
- return session
306
-
307
-
308
- def build_session(
309
- token: str,
310
- proxy: str,
311
- session_factory: Callable[[], Any] = default_session_factory,
312
- fingerprint_profile: dict[str, str] | None = None,
313
- device_id: str = "",
314
- ) -> tuple[Any, str]:
315
- fingerprint = (
316
- dict(fingerprint_profile)
317
- if isinstance(fingerprint_profile, dict) and fingerprint_profile
318
- else random_fingerprint()
319
- )
320
- if session_factory is default_session_factory:
321
- session = default_session_factory(
322
- fingerprint.get("tls_impersonate", "chrome146")
323
- )
324
- else:
325
- session = session_factory()
326
- runtime_device_id = str(device_id or "").strip() or str(uuid.uuid4())
327
- headers = {
328
- "User-Agent": fingerprint["ua"],
329
- "Accept": "*/*",
330
- "Accept-Language": fingerprint.get(
331
- "accept_language", "en-US,en;q=0.9"
332
- ),
333
- "Authorization": f"Bearer {token}",
334
- "Origin": "https://chatgpt.com",
335
- "Referer": "https://chatgpt.com/",
336
- "Content-Type": "application/json",
337
- "oai-device-id": runtime_device_id,
338
- "oai-language": fingerprint.get("oai_language", "en-US"),
339
- "sec-ch-ua": fingerprint["sec_ch_ua"],
340
- "sec-ch-ua-mobile": fingerprint.get("mobile", "?0"),
341
- "sec-ch-ua-platform": f'"{fingerprint["platform"]}"',
342
- "sec-fetch-dest": "empty",
343
- "sec-fetch-mode": "cors",
344
- "sec-fetch-site": "same-origin",
345
- "priority": "u=1, i",
346
- }
347
- if not fingerprint.get("har_exact"):
348
- headers.update(
349
- {
350
- "sec-ch-ua-arch": f'"{fingerprint["arch"]}"',
351
- "sec-ch-ua-bitness": f'"{fingerprint.get("bitness", "64")}"',
352
- "sec-ch-ua-model": '""',
353
- "sec-ch-ua-full-version": f'"{fingerprint["full"]}"',
354
- "sec-ch-ua-full-version-list": fingerprint[
355
- "sec_ch_ua_full_version_list"
356
- ],
357
- "sec-ch-ua-platform-version": (
358
- f'"{fingerprint["platform_version"]}"'
359
- ),
360
- }
361
- )
362
- session.headers.update(headers)
363
- if hasattr(session, "cookies"):
364
- try:
365
- session.cookies.set(
366
- "oai-did",
367
- runtime_device_id,
368
- domain=".chatgpt.com",
369
- path="/",
370
- )
371
- except Exception:
372
- pass
373
- runtime_proxy = resolve_proxy_placeholders(proxy)
374
- if runtime_proxy:
375
- session.proxies = {"http": runtime_proxy, "https": runtime_proxy}
376
- return session, fingerprint["name"]
377
-
378
-
379
- def response_json(response: Any) -> dict[str, Any]:
380
- try:
381
- payload = response.json() or {}
382
- except Exception as exc:
383
- text = str(getattr(response, "text", "") or "")
384
- raise Mode8Error(f"上游未返回 JSON:{text[:240]}") from exc
385
- if not isinstance(payload, dict):
386
- raise Mode8Error(f"上游 JSON 类型异常:{type(payload).__name__}")
387
- return payload
388
-
389
-
390
- def summarize_http_error(response: Any) -> str:
391
- status = int(getattr(response, "status_code", 0) or 0)
392
- text = str(getattr(response, "text", "") or "").strip()
393
- try:
394
- payload = response.json()
395
- except Exception:
396
- payload = None
397
- if isinstance(payload, dict):
398
- error = payload.get("error")
399
- if isinstance(error, dict):
400
- code = str(error.get("code") or "").strip()
401
- message = str(error.get("message") or "").strip()
402
- return " / ".join(
403
- part
404
- for part in (
405
- f"HTTP {status}",
406
- f"code={code}" if code else "",
407
- message[:300],
408
- )
409
- if part
410
- )
411
- detail = str(payload.get("detail") or payload.get("message") or "").strip()
412
- if detail:
413
- return f"HTTP {status} / {detail[:300]}"
414
- if re.search(r"<\s*(?:!doctype|html|head|body)\b", text, re.I):
415
- return f"HTTP {status} / 上游返回 HTML 拦截页"
416
- compact = re.sub(r"\s+", " ", text)[:300]
417
- return f"HTTP {status}{f' / {compact}' if compact else ''}"
418
-
419
-
420
- def extract_checkout_id(payload: Any) -> str:
421
- if isinstance(payload, dict):
422
- for key in ("checkout_session_id", "session_id", "id"):
423
- value = str(payload.get(key) or "").strip()
424
- if value.startswith(("oaics_", "cs_")):
425
- return value
426
- for key in ("checkout_session", "checkout", "session", "data", "raw"):
427
- value = payload.get(key)
428
- found = extract_checkout_id(value)
429
- if found:
430
- return found
431
- text = json.dumps(payload, ensure_ascii=False)
432
- match = re.search(
433
- r"(?:oaics_[A-Za-z0-9]+|cs_(?:live|test)_[A-Za-z0-9]+|cs_[A-Za-z0-9]+)",
434
- text,
435
- )
436
- return match.group(0) if match else ""
437
- if isinstance(payload, list):
438
- for item in payload:
439
- found = extract_checkout_id(item)
440
- if found:
441
- return found
442
- return ""
443
-
444
-
445
- def extract_processor_entity(payload: Any, country: str) -> str:
446
- if isinstance(payload, dict):
447
- direct = payload.get("processor_entity") or payload.get("processorEntity")
448
- if direct:
449
- return str(direct).strip()
450
- for key in ("checkout_session", "checkout", "session", "data", "raw"):
451
- nested = payload.get(key)
452
- if isinstance(nested, dict):
453
- found = extract_processor_entity(nested, "")
454
- if found:
455
- return found
456
- if not str(country or "").strip():
457
- return ""
458
- return "openai_llc" if str(country).upper() in {"US", "AU"} else "openai_ie"
459
-
460
-
461
- def extract_publishable_key(payload: Any) -> str:
462
- """Extract the Stripe publishable key for the checkout handoff."""
463
- if isinstance(payload, dict):
464
- for key in ("publishable_key", "publishableKey"):
465
- value = str(payload.get(key) or "").strip()
466
- if value.startswith(("pk_live_", "pk_test_")):
467
- return value
468
- for value in payload.values():
469
- found = extract_publishable_key(value)
470
- if found:
471
- return found
472
- elif isinstance(payload, list):
473
- for value in payload:
474
- found = extract_publishable_key(value)
475
- if found:
476
- return found
477
- return ""
478
-
479
-
480
- def amount_state(payload: Any) -> tuple[Decimal, str]:
481
- candidates: list[tuple[str, dict[str, Any]]] = []
482
- queue: list[tuple[str, Any]] = [("", payload)]
483
- while queue:
484
- path, value = queue.pop(0)
485
- if isinstance(value, dict):
486
- candidates.append((path, value))
487
- for key, nested in value.items():
488
- nested_path = f"{path}.{key}" if path else str(key)
489
- if isinstance(nested, (dict, list)):
490
- queue.append((nested_path, nested))
491
- elif isinstance(value, list):
492
- for index, nested in enumerate(value):
493
- if isinstance(nested, (dict, list)):
494
- queue.append((f"{path}[{index}]", nested))
495
-
496
- # Prefer payable totals anywhere in the response before looking at broader
497
- # totals or individual line items. Current checkout responses sometimes
498
- # wrap these fields several levels below data/checkout_session.
499
- for path, candidate in candidates:
500
- total_summary = candidate.get("total_summary")
501
- if isinstance(total_summary, dict) and total_summary.get("due") is not None:
502
- try:
503
- source = f"{path + '.' if path else ''}total_summary.due"
504
- return Decimal(str(total_summary["due"])), source
505
- except InvalidOperation:
506
- pass
507
- invoice = candidate.get("invoice")
508
- if isinstance(invoice, dict) and invoice.get("amount_due") is not None:
509
- try:
510
- source = f"{path + '.' if path else ''}invoice.amount_due"
511
- return Decimal(str(invoice["amount_due"])), source
512
- except InvalidOperation:
513
- pass
514
-
515
- for path, candidate in candidates:
516
- for key in ("amount_due", "amount_total", "total"):
517
- if candidate.get(key) is not None:
518
- try:
519
- source = f"{path + '.' if path else ''}{key}"
520
- return Decimal(str(candidate[key])), source
521
- except InvalidOperation:
522
- pass
523
-
524
- for path, candidate in candidates:
525
- line_items = candidate.get("line_items")
526
- if isinstance(line_items, list):
527
- values: list[Decimal] = []
528
- for item in line_items:
529
- if isinstance(item, dict) and item.get("amount") is not None:
530
- try:
531
- values.append(Decimal(str(item["amount"])))
532
- except InvalidOperation:
533
- pass
534
- if values:
535
- source = f"{path + '.' if path else ''}line_items.amount"
536
- return sum(values, Decimal("0")), source
537
- return Decimal("0"), ""
538
-
539
-
540
- def compact_checkout_diagnostic(payload: Any) -> dict[str, Any]:
541
- candidate: dict[str, Any] = payload if isinstance(payload, dict) else {}
542
- for key in ("checkout_session", "checkout", "session", "data", "raw"):
543
- nested = candidate.get(key)
544
- if isinstance(nested, dict) and nested:
545
- candidate = nested
546
- break
547
- billing = (
548
- candidate.get("billing_details")
549
- if isinstance(candidate.get("billing_details"), dict)
550
- else {}
551
- )
552
- promo = (
553
- candidate.get("promo_campaign")
554
- if isinstance(candidate.get("promo_campaign"), dict)
555
- else {}
556
- )
557
- amount, source = amount_state(payload)
558
- return {
559
- "id": extract_checkout_id(payload) or "missing",
560
- "billing": f"{billing.get('country') or ''}/{billing.get('currency') or ''}",
561
- "promo": str(promo.get("promo_campaign_id") or ""),
562
- "status": str(candidate.get("status") or candidate.get("checkout_state") or ""),
563
- "payment_status": str(candidate.get("payment_status") or ""),
564
- "methods": (
565
- candidate.get("payment_method_types")[:8]
566
- if isinstance(candidate.get("payment_method_types"), list)
567
- else []
568
- ),
569
- "amount": str(amount) if source else "unknown",
570
- "amount_source": source,
571
- "fields": sorted(candidate.keys())[:24],
572
- }
573
-
574
-
575
- def is_retryable_status(status: int) -> bool:
576
- return status in {403, 408, 409, 425, 429, 500, 502, 503, 504}
577
-
578
-
579
- def is_retryable_network_error(exc: Exception) -> bool:
580
- text = str(exc).lower()
581
- markers = (
582
- "proxy",
583
- "connect",
584
- "connection",
585
- "timed out",
586
- "timeout",
587
- "ssl",
588
- "tls",
589
- "reset",
590
- "remote end closed",
591
- "failed to perform",
592
- )
593
- return any(marker in text for marker in markers)
594
-
595
-
596
- @dataclass
597
- class Mode8Config:
598
- token: str
599
- country: str = "PH"
600
- currency: str = "PHP"
601
- promo_campaign: str = "plus-1-month-free"
602
- require_oaics: bool = True
603
- reject_nonzero: bool = True
604
- timeout: int = DEFAULT_TIMEOUT
605
- diagnose_coupon: bool = True
606
- fingerprint_profile: dict[str, str] | None = None
607
- device_id: str = ""
608
-
609
-
610
- class Mode8Extractor:
611
- def __init__(
612
- self,
613
- config: Mode8Config,
614
- *,
615
- logger: Callable[[str], None] | None = None,
616
- session_factory: Callable[[], Any] = default_session_factory,
617
- ) -> None:
618
- self.config = config
619
- self.log = logger or print
620
- self.session_factory = session_factory
621
-
622
- def _session(self, proxy: str) -> Any:
623
- session, fingerprint = build_session(
624
- normalize_access_token(self.config.token),
625
- proxy,
626
- self.session_factory,
627
- self.config.fingerprint_profile,
628
- self.config.device_id,
629
- )
630
- self.log(f"纯 HTTP 指纹档案:{fingerprint}")
631
- return session
632
-
633
- def _coupon_diagnostic(self, session: Any) -> dict[str, Any]:
634
- campaign = self.config.promo_campaign.strip()
635
- if not campaign:
636
- return {"campaign": "none", "checked": False}
637
- try:
638
- response = session.get(
639
- COUPON_CHECK_URL,
640
- params={
641
- "coupon": campaign,
642
- "is_coupon_from_query_param": "true",
643
- },
644
- headers={
645
- "Referer": "https://chatgpt.com/",
646
- "x-openai-target-path": "/backend-api/promo_campaign/check_coupon",
647
- "x-openai-target-route": "/backend-api/promo_campaign/check_coupon",
648
- },
649
- timeout=self.config.timeout,
650
- )
651
- result: dict[str, Any] = {
652
- "campaign": campaign,
653
- "checked": True,
654
- "http_status": int(response.status_code),
655
- }
656
- if response.status_code < 400:
657
- data = response_json(response)
658
- redemption = (
659
- data.get("redemption")
660
- if isinstance(data.get("redemption"), dict)
661
- else {}
662
- )
663
- result.update(
664
- {
665
- "state": str(data.get("state") or ""),
666
- "redeemed": redemption.get("redeemed"),
667
- "redeemed_by_user": redemption.get("redeemed_by_user"),
668
- }
669
- )
670
- return result
671
- except Exception as exc:
672
- return {
673
- "campaign": campaign,
674
- "checked": False,
675
- "error": type(exc).__name__,
676
- }
677
-
678
- def _create_checkout(self, session: Any) -> dict[str, Any]:
679
- cfg = self.config
680
- body: dict[str, Any] = {
681
- "entry_point": "all_plans_pricing_modal",
682
- "plan_name": "chatgptplusplan",
683
- "billing_details": {
684
- "country": cfg.country.upper(),
685
- "currency": cfg.currency.upper(),
686
- },
687
- "checkout_ui_mode": "custom",
688
- }
689
- if cfg.promo_campaign.strip():
690
- body["promo_campaign"] = {
691
- "promo_campaign_id": cfg.promo_campaign.strip(),
692
- "is_coupon_from_query_param": False,
693
- }
694
- response = session.post(
695
- CHECKOUT_URL,
696
- json=body,
697
- headers={
698
- "Referer": "https://chatgpt.com/",
699
- "x-openai-target-path": "/backend-api/payments/checkout",
700
- "x-openai-target-route": "/backend-api/payments/checkout",
701
- },
702
- timeout=cfg.timeout,
703
- )
704
- if response.status_code >= 400:
705
- raise Mode8Error(
706
- f"阶段1 checkout create failed:{summarize_http_error(response)}"
707
- )
708
- return response_json(response)
709
-
710
- def _update_checkout(
711
- self,
712
- session: Any,
713
- checkout_id: str,
714
- processor_entity: str,
715
- ) -> dict[str, Any]:
716
- cfg = self.config
717
- body = {
718
- "checkout_session_id": checkout_id,
719
- "processor_entity": processor_entity,
720
- "plan_name": "chatgptplusplan",
721
- "price_interval": "month",
722
- "seat_quantity": 1,
723
- "billing_details": {
724
- "country": cfg.country.upper(),
725
- "currency": cfg.currency.upper(),
726
- },
727
- "promo_campaign": {
728
- "promo_campaign_id": cfg.promo_campaign.strip(),
729
- "is_coupon_from_query_param": False,
730
- },
731
- "checkout_ui_mode": "custom",
732
- }
733
- response = session.post(
734
- CHECKOUT_UPDATE_URL,
735
- json=body,
736
- headers={
737
- "Origin": "https://chatgpt.com",
738
- "Referer": (
739
- f"https://chatgpt.com/checkout/{processor_entity}/{checkout_id}"
740
- ),
741
- "x-openai-target-path": "/backend-api/payments/checkout/update",
742
- "x-openai-target-route": "/backend-api/payments/checkout/update",
743
- },
744
- timeout=cfg.timeout,
745
- )
746
- if response.status_code >= 400:
747
- error = Mode8Error(
748
- f"阶段2 checkout update failed:{summarize_http_error(response)}"
749
- )
750
- setattr(error, "http_status", int(response.status_code))
751
- raise error
752
- return response_json(response)
753
-
754
- def _checkout_taxes(
755
- self,
756
- session: Any,
757
- checkout_id: str,
758
- processor_entity: str,
759
- ) -> dict[str, Any]:
760
- cfg = self.config
761
- response = session.post(
762
- CHECKOUT_TAXES_URL,
763
- json={
764
- "checkout_session_id": checkout_id,
765
- "processor_entity": processor_entity,
766
- "billing_country": cfg.country.upper(),
767
- "billing_currency": cfg.currency.upper(),
768
- "currency": cfg.currency.upper(),
769
- },
770
- headers={
771
- "Origin": "https://chatgpt.com",
772
- "Referer": (
773
- f"https://chatgpt.com/checkout/{processor_entity}/{checkout_id}"
774
- ),
775
- "x-openai-target-path": "/backend-api/payments/checkout/taxes",
776
- "x-openai-target-route": "/backend-api/payments/checkout/taxes",
777
- },
778
- timeout=cfg.timeout,
779
- )
780
- if response.status_code >= 400:
781
- raise Mode8Error(
782
- f"checkout taxes failed:{summarize_http_error(response)}"
783
- )
784
- return response_json(response)
785
-
786
- def run(self, pool1_text: str = "", pool2_text: str = "") -> dict[str, Any]:
787
- token = normalize_access_token(self.config.token)
788
- if not token:
789
- raise Mode8Error("Access Token 为空")
790
- self.config.token = token
791
-
792
- pool1 = split_proxy_pool(pool1_text)
793
- pool2 = split_proxy_pool(pool2_text)
794
- stage1_proxy = random.choice(pool1) if pool1 else ""
795
- self.log("模式8两阶段流程开始")
796
- self.log(
797
- f"配置:country={self.config.country.upper()}, "
798
- f"currency={self.config.currency.upper()}, "
799
- f"promo={self.config.promo_campaign or 'none'}, ui=custom"
800
- )
801
- self.log(f"[阶段1/2] 建单出口:{mask_proxy(stage1_proxy)}")
802
-
803
- stage1_session = self._session(stage1_proxy)
804
- coupon = (
805
- self._coupon_diagnostic(stage1_session)
806
- if self.config.diagnose_coupon
807
- else {"campaign": self.config.promo_campaign.strip() or "none", "checked": False}
808
- )
809
- self.log(
810
- "[阶段1/2] 优惠资格诊断:"
811
- + json.dumps(coupon, ensure_ascii=False, separators=(",", ":"))
812
- )
813
- create_payload = self._create_checkout(stage1_session)
814
- checkout_id = extract_checkout_id(create_payload)
815
- if not checkout_id:
816
- raise Mode8Error(
817
- "阶段1返回中没有 checkout_session_id:"
818
- + json.dumps(create_payload, ensure_ascii=False)[:500]
819
- )
820
- processor_entity = extract_processor_entity(
821
- create_payload, self.config.country
822
- )
823
- self.log(
824
- f"[阶段1/2] 建单成功:id={checkout_id[:24]}..., "
825
- f"processor={processor_entity}"
826
- )
827
- self.log(
828
- "[阶段1/2] 返回摘要:"
829
- + json.dumps(
830
- compact_checkout_diagnostic(create_payload),
831
- ensure_ascii=False,
832
- separators=(",", ":"),
833
- )
834
- )
835
-
836
- update_payload: dict[str, Any] = {}
837
- stage2_proxy = ""
838
- validation_session = stage1_session
839
- campaign = self.config.promo_campaign.strip()
840
- if campaign:
841
- candidates = list(pool2) if pool2 else [""]
842
- if stage1_proxy in candidates:
843
- candidates.remove(stage1_proxy)
844
- candidates.insert(0, stage1_proxy)
845
- elif len(candidates) > 1:
846
- start = random.randrange(len(candidates))
847
- candidates = candidates[start:] + candidates[:start]
848
- candidates = candidates[:4]
849
- last_error: Exception | None = None
850
- for index, candidate in enumerate(candidates, start=1):
851
- stage2_proxy = candidate
852
- self.log(
853
- f"[阶段2/2] 激活优惠,第 {index}/{len(candidates)} 次,"
854
- f"出口={mask_proxy(candidate)}"
855
- )
856
- try:
857
- stage2_session = (
858
- stage1_session if candidate == stage1_proxy else self._session(candidate)
859
- )
860
- validation_session = stage2_session
861
- update_payload = self._update_checkout(
862
- stage2_session, checkout_id, processor_entity
863
- )
864
- last_error = None
865
- break
866
- except Exception as exc:
867
- last_error = exc
868
- status = int(getattr(exc, "http_status", 0) or 0)
869
- can_retry = (
870
- index < len(candidates)
871
- and (
872
- is_retryable_status(status)
873
- or is_retryable_network_error(exc)
874
- )
875
- )
876
- self.log(f"[阶段2/2] 本次失败:{exc}")
877
- if not can_retry:
878
- raise
879
- if last_error is not None:
880
- raise last_error
881
-
882
- updated_id = extract_checkout_id(update_payload)
883
- if updated_id:
884
- checkout_id = updated_id
885
- updated_entity = extract_processor_entity(
886
- update_payload, self.config.country
887
- )
888
- if updated_entity:
889
- processor_entity = updated_entity
890
- self.log(
891
- f"[阶段2/2] 优惠更新成功:id={checkout_id[:24]}..."
892
- )
893
- self.log(
894
- "[阶段2/2] 返回摘要:"
895
- + json.dumps(
896
- compact_checkout_diagnostic(update_payload),
897
- ensure_ascii=False,
898
- separators=(",", ":"),
899
- )
900
- )
901
- else:
902
- self.log("[阶段2/2] promo 为空,跳过优惠更新")
903
-
904
- amount_payload = update_payload or create_payload
905
- amount, amount_source = amount_state(amount_payload)
906
- if not amount_source:
907
- taxes_payload = self._checkout_taxes(
908
- validation_session,
909
- checkout_id,
910
- processor_entity,
911
- )
912
- if taxes_payload:
913
- amount_payload = taxes_payload
914
- amount, amount_source = amount_state(amount_payload)
915
- if amount_source:
916
- self.log(f"金额校验:amount={amount}, source={amount_source}")
917
- if self.config.reject_nonzero and amount != 0:
918
- raise Mode8Error(
919
- f"零元校验失败:amount={amount}, source={amount_source}"
920
- )
921
- else:
922
- self.log("金额校验:上游没有返回可验证的金额字段")
923
- if self.config.reject_nonzero:
924
- raise Mode8Error(
925
- "金额校验失败:上游没有返回可验证的金额字段"
926
- )
927
-
928
- if self.config.require_oaics and not checkout_id.startswith("oaics_"):
929
- raise Mode8Error(
930
- f"短链类型校验失败:返回 {checkout_id[:20]}...,期望 oaics_"
931
- )
932
-
933
- result_url = (
934
- f"https://chatgpt.com/checkout/{processor_entity}/{checkout_id}"
935
- )
936
- result = {
937
- "ok": True,
938
- "checkout_id": checkout_id,
939
- "processor_entity": processor_entity,
940
- "country": self.config.country.upper(),
941
- "currency": self.config.currency.upper(),
942
- "promo_campaign": campaign or "none",
943
- "amount": str(amount) if amount_source else "unknown",
944
- "amount_source": amount_source,
945
- "stage1_proxy": mask_proxy(stage1_proxy),
946
- "stage2_proxy": mask_proxy(stage2_proxy),
947
- "url": result_url,
948
- # Internal handoff only. The app adapter removes this before JSON output.
949
- "_publishable_key": extract_publishable_key(update_payload)
950
- or extract_publishable_key(create_payload),
951
- }
952
- self.log(f"模式8结果:{result_url}")
953
- return result
954
-
955
-
956
- class _FakeResponse:
957
- def __init__(self, status_code: int, payload: dict[str, Any]) -> None:
958
- self.status_code = status_code
959
- self._payload = payload
960
- self.text = json.dumps(payload)
961
-
962
- def json(self) -> dict[str, Any]:
963
- return self._payload
964
-
965
-
966
- class _FakeSession:
967
- def __init__(self) -> None:
968
- self.headers: dict[str, str] = {}
969
- self.proxies: dict[str, str] = {}
970
-
971
- def get(self, url: str, **_: Any) -> _FakeResponse:
972
- if url == COUPON_CHECK_URL:
973
- return _FakeResponse(
974
- 200,
975
- {
976
- "state": "eligible",
977
- "redemption": {"redeemed": False},
978
- },
979
- )
980
- raise AssertionError(f"unexpected GET {url}")
981
-
982
- def post(self, url: str, **kwargs: Any) -> _FakeResponse:
983
- body = kwargs.get("json") or {}
984
- if url == CHECKOUT_URL:
985
- assert body["checkout_ui_mode"] == "custom"
986
- assert body["promo_campaign"]["promo_campaign_id"] == (
987
- "plus-1-month-free"
988
- )
989
- return _FakeResponse(
990
- 200,
991
- {
992
- "checkout_session_id": "oaics_fixture123",
993
- "processor_entity": "openai_ie",
994
- "billing_details": {"country": "PH", "currency": "PHP"},
995
- "promo_campaign": {
996
- "promo_campaign_id": "plus-1-month-free"
997
- },
998
- "payment_method_types": ["card", "link"],
999
- "status": "open",
1000
- },
1001
- )
1002
- if url == CHECKOUT_UPDATE_URL:
1003
- assert body["checkout_session_id"] == "oaics_fixture123"
1004
- assert body["promo_campaign"]["promo_campaign_id"] == (
1005
- "plus-1-month-free"
1006
- )
1007
- return _FakeResponse(
1008
- 200,
1009
- {
1010
- "checkout_session_id": "oaics_fixture123",
1011
- "processor_entity": "openai_ie",
1012
- "billing_details": {"country": "PH", "currency": "PHP"},
1013
- "total_summary": {"due": 0},
1014
- "payment_method_types": ["card", "link"],
1015
- "status": "open",
1016
- },
1017
- )
1018
- raise AssertionError(f"unexpected POST {url}")
1019
-
1020
-
1021
- def run_self_test() -> None:
1022
- logs: list[str] = []
1023
- extractor = Mode8Extractor(
1024
- Mode8Config(token="header.payload.signature"),
1025
- logger=logs.append,
1026
- session_factory=_FakeSession,
1027
- )
1028
- result = extractor.run("", "")
1029
- expected = (
1030
- "https://chatgpt.com/checkout/openai_ie/oaics_fixture123"
1031
- )
1032
- assert result["url"] == expected, result
1033
- assert result["amount"] == "0", result
1034
- assert result["amount_source"] == "total_summary.due", result
1035
- assert split_proxy_pool(
1036
- "host:8080:user:pass\nhttp://host2:8081"
1037
- ) == [
1038
- "http://user:pass@host:8080",
1039
- "http://host2:8081",
1040
- ]
1041
- assert normalize_access_token(
1042
- '{"accessToken":"header.payload.signature"}'
1043
- ) == "header.payload.signature"
1044
- print("SELF-TEST PASS")
1045
- print(expected)
1046
-
1047
-
1048
- def _read_text_file(path: str) -> str:
1049
- if not path:
1050
- return ""
1051
- return Path(path).expanduser().read_text(encoding="utf-8-sig")
1052
-
1053
-
1054
- def run_cli(args: argparse.Namespace) -> int:
1055
- token = args.token or _read_text_file(args.token_file)
1056
- pool1 = args.pool1 or _read_text_file(args.pool1_file)
1057
- pool2 = args.pool2 or _read_text_file(args.pool2_file)
1058
- config = Mode8Config(
1059
- token=token,
1060
- country=args.country,
1061
- currency=args.currency,
1062
- promo_campaign=args.promo,
1063
- require_oaics=not args.allow_cs,
1064
- reject_nonzero=not args.allow_nonzero,
1065
- timeout=args.timeout,
1066
- )
1067
- try:
1068
- result = Mode8Extractor(config).run(pool1, pool2)
1069
- except Exception as exc:
1070
- print(f"ERROR: {exc}", file=sys.stderr)
1071
- return 1
1072
- print(json.dumps(result, ensure_ascii=False, indent=2))
1073
- return 0
1074
-
1075
-
1076
- def launch_gui() -> None:
1077
- try:
1078
- import tkinter as tk
1079
- from tkinter import messagebox, scrolledtext, ttk
1080
- except Exception as exc:
1081
- raise Mode8Error(f"Tkinter 不可用:{exc}") from exc
1082
-
1083
- class Mode8App(tk.Tk):
1084
- def __init__(self) -> None:
1085
- super().__init__()
1086
- self.title("模式8独立提炼器")
1087
- self.geometry("960x780")
1088
- self.minsize(820, 680)
1089
- self.events: queue.Queue[tuple[str, Any]] = queue.Queue()
1090
- self.running = False
1091
-
1092
- self.country_var = tk.StringVar(value="PH")
1093
- self.currency_var = tk.StringVar(value="PHP")
1094
- self.promo_var = tk.StringVar(value="plus-1-month-free")
1095
- self.require_oaics_var = tk.BooleanVar(value=True)
1096
- self.reject_nonzero_var = tk.BooleanVar(value=True)
1097
- self.result_var = tk.StringVar()
1098
- self.status_var = tk.StringVar(value="就绪")
1099
-
1100
- self.columnconfigure(0, weight=1)
1101
- self.rowconfigure(4, weight=1)
1102
-
1103
- title = ttk.Label(
1104
- self,
1105
- text="模式8 · 两阶段独立提炼",
1106
- font=("Microsoft YaHei UI", 16, "bold"),
1107
- )
1108
- title.grid(row=0, column=0, sticky="w", padx=16, pady=(14, 4))
1109
- ttk.Label(
1110
- self,
1111
- text=(
1112
- "阶段1使用代理池1创建 checkout;阶段2使用代理池2更新同一 "
1113
- "checkout 并激活优惠。脚本没有内置代理。"
1114
- ),
1115
- ).grid(row=1, column=0, sticky="w", padx=16, pady=(0, 10))
1116
-
1117
- form = ttk.Frame(self, padding=(16, 0))
1118
- form.grid(row=2, column=0, sticky="ew")
1119
- form.columnconfigure(1, weight=1)
1120
- form.columnconfigure(3, weight=1)
1121
-
1122
- ttk.Label(form, text="国家").grid(row=0, column=0, sticky="w")
1123
- ttk.Entry(form, textvariable=self.country_var, width=10).grid(
1124
- row=0, column=1, sticky="w", padx=(8, 20)
1125
- )
1126
- ttk.Label(form, text="货币").grid(row=0, column=2, sticky="w")
1127
- ttk.Entry(form, textvariable=self.currency_var, width=10).grid(
1128
- row=0, column=3, sticky="w", padx=(8, 20)
1129
- )
1130
- ttk.Label(form, text="优惠参数").grid(row=0, column=4, sticky="w")
1131
- ttk.Entry(form, textvariable=self.promo_var, width=28).grid(
1132
- row=0, column=5, sticky="ew", padx=(8, 0)
1133
- )
1134
-
1135
- ttk.Label(form, text="Access Token").grid(
1136
- row=1, column=0, sticky="nw", pady=(12, 0)
1137
- )
1138
- self.token_text = scrolledtext.ScrolledText(
1139
- form, height=4, wrap="word", font=("Consolas", 9)
1140
- )
1141
- self.token_text.grid(
1142
- row=1, column=1, columnspan=5, sticky="ew", padx=(8, 0), pady=(12, 0)
1143
- )
1144
-
1145
- pools = ttk.Frame(self, padding=(16, 12))
1146
- pools.grid(row=3, column=0, sticky="nsew")
1147
- pools.columnconfigure(0, weight=1)
1148
- pools.columnconfigure(1, weight=1)
1149
-
1150
- left = ttk.LabelFrame(
1151
- pools, text="代理池1(阶段1:创建 checkout)", padding=8
1152
- )
1153
- right = ttk.LabelFrame(
1154
- pools, text="代理池2(阶段2:激活优惠)", padding=8
1155
- )
1156
- left.grid(row=0, column=0, sticky="nsew", padx=(0, 6))
1157
- right.grid(row=0, column=1, sticky="nsew", padx=(6, 0))
1158
- left.columnconfigure(0, weight=1)
1159
- right.columnconfigure(0, weight=1)
1160
-
1161
- ttk.Label(left, text="每行一个;留空则该阶段直连").grid(
1162
- row=0, column=0, sticky="w"
1163
- )
1164
- ttk.Label(right, text="每行一个;失败时最多轮换 4 个").grid(
1165
- row=0, column=0, sticky="w"
1166
- )
1167
- self.pool1_text = scrolledtext.ScrolledText(
1168
- left, height=7, wrap="none", font=("Consolas", 9)
1169
- )
1170
- self.pool2_text = scrolledtext.ScrolledText(
1171
- right, height=7, wrap="none", font=("Consolas", 9)
1172
- )
1173
- self.pool1_text.grid(row=1, column=0, sticky="nsew", pady=(6, 0))
1174
- self.pool2_text.grid(row=1, column=0, sticky="nsew", pady=(6, 0))
1175
-
1176
- output = ttk.Frame(self, padding=(16, 0, 16, 16))
1177
- output.grid(row=4, column=0, sticky="nsew")
1178
- output.columnconfigure(0, weight=1)
1179
- output.rowconfigure(3, weight=1)
1180
-
1181
- options = ttk.Frame(output)
1182
- options.grid(row=0, column=0, sticky="ew")
1183
- ttk.Checkbutton(
1184
- options,
1185
- text="只接受 oaics_ 短链",
1186
- variable=self.require_oaics_var,
1187
- ).pack(side="left")
1188
- ttk.Checkbutton(
1189
- options,
1190
- text="检测到非0金额时停止",
1191
- variable=self.reject_nonzero_var,
1192
- ).pack(side="left", padx=(18, 0))
1193
- self.start_button = ttk.Button(
1194
- options, text="开始提炼", command=self.start
1195
- )
1196
- self.start_button.pack(side="right")
1197
-
1198
- result_row = ttk.Frame(output)
1199
- result_row.grid(row=1, column=0, sticky="ew", pady=(10, 8))
1200
- result_row.columnconfigure(1, weight=1)
1201
- ttk.Label(result_row, text="结果链接").grid(row=0, column=0)
1202
- ttk.Entry(
1203
- result_row, textvariable=self.result_var, state="readonly"
1204
- ).grid(row=0, column=1, sticky="ew", padx=8)
1205
- ttk.Button(result_row, text="复制", command=self.copy_result).grid(
1206
- row=0, column=2
1207
- )
1208
-
1209
- ttk.Label(output, textvariable=self.status_var).grid(
1210
- row=2, column=0, sticky="w"
1211
- )
1212
- self.log_text = scrolledtext.ScrolledText(
1213
- output,
1214
- height=12,
1215
- wrap="word",
1216
- state="disabled",
1217
- font=("Consolas", 9),
1218
- )
1219
- self.log_text.grid(row=3, column=0, sticky="nsew", pady=(6, 0))
1220
- self.after(100, self.drain_events)
1221
-
1222
- def append_log(self, line: str) -> None:
1223
- timestamp = time.strftime("%H:%M:%S")
1224
- self.log_text.configure(state="normal")
1225
- self.log_text.insert("end", f"[{timestamp}] {line}\n")
1226
- self.log_text.see("end")
1227
- self.log_text.configure(state="disabled")
1228
-
1229
- def start(self) -> None:
1230
- if self.running:
1231
- return
1232
- token = self.token_text.get("1.0", "end").strip()
1233
- if not normalize_access_token(token):
1234
- messagebox.showerror("模式8", "请先填写 Access Token")
1235
- return
1236
- self.running = True
1237
- self.start_button.configure(state="disabled")
1238
- self.result_var.set("")
1239
- self.status_var.set("运行中")
1240
- config = Mode8Config(
1241
- token=token,
1242
- country=self.country_var.get().strip() or "PH",
1243
- currency=self.currency_var.get().strip() or "PHP",
1244
- promo_campaign=self.promo_var.get().strip(),
1245
- require_oaics=self.require_oaics_var.get(),
1246
- reject_nonzero=self.reject_nonzero_var.get(),
1247
- )
1248
- pool1 = self.pool1_text.get("1.0", "end")
1249
- pool2 = self.pool2_text.get("1.0", "end")
1250
-
1251
- def worker() -> None:
1252
- try:
1253
- result = Mode8Extractor(
1254
- config,
1255
- logger=lambda line: self.events.put(("log", line)),
1256
- ).run(pool1, pool2)
1257
- self.events.put(("success", result))
1258
- except Exception as exc:
1259
- self.events.put(("error", f"{type(exc).__name__}: {exc}"))
1260
-
1261
- threading.Thread(target=worker, daemon=True).start()
1262
-
1263
- def drain_events(self) -> None:
1264
- try:
1265
- while True:
1266
- kind, payload = self.events.get_nowait()
1267
- if kind == "log":
1268
- self.append_log(str(payload))
1269
- elif kind == "success":
1270
- self.running = False
1271
- self.start_button.configure(state="normal")
1272
- self.result_var.set(str(payload["url"]))
1273
- self.status_var.set("成功")
1274
- self.append_log("提炼完成")
1275
- elif kind == "error":
1276
- self.running = False
1277
- self.start_button.configure(state="normal")
1278
- self.status_var.set("失败")
1279
- self.append_log(str(payload))
1280
- messagebox.showerror("模式8提炼失败", str(payload))
1281
- except queue.Empty:
1282
- pass
1283
- self.after(100, self.drain_events)
1284
-
1285
- def copy_result(self) -> None:
1286
- value = self.result_var.get().strip()
1287
- if not value:
1288
- return
1289
- self.clipboard_clear()
1290
- self.clipboard_append(value)
1291
- self.status_var.set("结果已复制")
1292
-
1293
- Mode8App().mainloop()
1294
-
1295
-
1296
- def build_parser() -> argparse.ArgumentParser:
1297
- parser = argparse.ArgumentParser(description="模式8独立两阶段短链提炼器")
1298
- parser.add_argument("--token", default="", help="Access Token")
1299
- parser.add_argument("--token-file", default="", help="Token 文件")
1300
- parser.add_argument("--pool1", default="", help="代理池1,多项用逗号分隔")
1301
- parser.add_argument("--pool1-file", default="", help="代理池1文件,每行一个")
1302
- parser.add_argument("--pool2", default="", help="代理池2,多项用逗号分隔")
1303
- parser.add_argument("--pool2-file", default="", help="代理池2文件,每行一个")
1304
- parser.add_argument("--country", default="PH")
1305
- parser.add_argument("--currency", default="PHP")
1306
- parser.add_argument("--promo", default="plus-1-month-free")
1307
- parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT)
1308
- parser.add_argument(
1309
- "--allow-cs",
1310
- action="store_true",
1311
- help="允许 cs_,不强制 oaics_",
1312
- )
1313
- parser.add_argument(
1314
- "--allow-nonzero",
1315
- action="store_true",
1316
- help="金额非0时仍返回链接",
1317
- )
1318
- parser.add_argument(
1319
- "--self-test",
1320
- action="store_true",
1321
- help="运行离线自测,不访问网络",
1322
- )
1323
- return parser
1324
-
1325
-
1326
- def main(argv: Iterable[str] | None = None) -> int:
1327
- parser = build_parser()
1328
- args = parser.parse_args(list(argv) if argv is not None else None)
1329
- if args.self_test:
1330
- run_self_test()
1331
- return 0
1332
- cli_requested = any(
1333
- (
1334
- args.token,
1335
- args.token_file,
1336
- args.pool1,
1337
- args.pool1_file,
1338
- args.pool2,
1339
- args.pool2_file,
1340
- )
1341
- )
1342
- if cli_requested:
1343
- return run_cli(args)
1344
- launch_gui()
1345
- return 0
1346
-
1347
-
1348
- if __name__ == "__main__":
1349
- raise SystemExit(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
standalone_core/register_profile.py DELETED
@@ -1,1845 +0,0 @@
1
- """浏览器指纹元数据(UA / SecChUA / Locale / Timezone)。
2
-
3
- 每个注册任务生成一份 Profile,并在整条 OAuth/Sentinel 链路上保持一致。
4
- 优先按代理 region(或出口 IP 国家)对齐语言与时区,降低 IP-指纹错配风险。
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- import hashlib
10
- import json
11
- import re
12
- import secrets
13
- from dataclasses import asdict, dataclass, fields
14
- from datetime import datetime
15
- from typing import Optional
16
- from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
17
-
18
-
19
- # Pick one exact bundled TLS/HTTP2 preset per account and keep it sticky for
20
- # that account's complete registration/OAuth transaction.
21
- # Protocol registration must advertise the exact browser major implemented by
22
- # both installed TLS stacks. Hardware/locale/persona diversity stays broad;
23
- # inventing Chrome 148/150 above a chrome_146 handshake is not diversity, it is
24
- # a cross-layer contradiction.
25
- _REALISTIC_MAJORS: tuple[int, ...] = (145, 146)
26
- _WINDOWS_UA_PLATFORM = "Windows NT 10.0; Win64; x64"
27
- _MAC_UA_PLATFORMS: tuple[str, ...] = (
28
- "Macintosh; Intel Mac OS X 10_15_7",
29
- "Macintosh; Intel Mac OS X 13_6_7",
30
- "Macintosh; Intel Mac OS X 14_5",
31
- )
32
-
33
- # Accept-Language, navigator.language
34
- _LOCALES_GENERIC: tuple[tuple[str, str], ...] = (
35
- ("en-US,en;q=0.9", "en-US"),
36
- ("en-GB,en;q=0.9", "en-GB"),
37
- ("en-US,en;q=0.9,zh-CN;q=0.8", "en-US"),
38
- )
39
-
40
- _LOCALES_BY_REGION: dict[str, tuple[tuple[str, str], ...]] = {
41
- "US": (("en-US,en;q=0.9", "en-US"), ("en-US,en;q=0.9,es;q=0.7", "en-US")),
42
- "CA": (("en-CA,en;q=0.9", "en-CA"), ("en-US,en;q=0.9", "en-US")),
43
- "GB": (("en-GB,en;q=0.9", "en-GB"), ("en-GB,en;q=0.9,en-US;q=0.8", "en-GB")),
44
- "UK": (("en-GB,en;q=0.9", "en-GB"),),
45
- "IE": (("en-IE,en;q=0.9", "en-IE"), ("en-GB,en;q=0.9", "en-GB")),
46
- "AU": (("en-AU,en;q=0.9", "en-AU"), ("en-US,en;q=0.9", "en-US")),
47
- "NZ": (("en-NZ,en;q=0.9", "en-NZ"), ("en-AU,en;q=0.9", "en-AU")),
48
- "DE": (("de-DE,de;q=0.9,en;q=0.8", "de-DE"), ("en-US,en;q=0.9", "en-US")),
49
- "FR": (("fr-FR,fr;q=0.9,en;q=0.8", "fr-FR"), ("en-US,en;q=0.9", "en-US")),
50
- "NL": (("nl-NL,nl;q=0.9,en;q=0.8", "nl-NL"), ("en-US,en;q=0.9", "en-US")),
51
- "IT": (("it-IT,it;q=0.9,en;q=0.8", "it-IT"), ("en-US,en;q=0.9", "en-US")),
52
- "ES": (("es-ES,es;q=0.9,en;q=0.8", "es-ES"), ("en-US,en;q=0.9", "en-US")),
53
- "PT": (("pt-PT,pt;q=0.9,en;q=0.8", "pt-PT"), ("en-US,en;q=0.9", "en-US")),
54
- "BR": (("pt-BR,pt;q=0.9,en;q=0.8", "pt-BR"), ("en-US,en;q=0.9", "en-US")),
55
- "JP": (("ja-JP,ja;q=0.9,en-US;q=0.8,en;q=0.7", "ja-JP"),),
56
- "KR": (("ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7", "ko-KR"),),
57
- "SG": (("en-SG,en;q=0.9", "en-SG"), ("en-US,en;q=0.9,zh-CN;q=0.7", "en-US")),
58
- "HK": (("zh-HK,zh;q=0.9,en;q=0.8", "zh-HK"), ("en-HK,en;q=0.9", "en-HK")),
59
- "TW": (("zh-TW,zh;q=0.9,en;q=0.8", "zh-TW"), ("en-US,en;q=0.9", "en-US")),
60
- "MY": (("en-MY,en;q=0.9", "en-MY"), ("ms-MY,ms;q=0.9,en;q=0.8", "ms-MY")),
61
- "PH": (("en-PH,en;q=0.9", "en-PH"), ("en-US,en;q=0.9", "en-US")),
62
- "TH": (("th-TH,th;q=0.9,en;q=0.8", "th-TH"), ("en-US,en;q=0.9", "en-US")),
63
- "VN": (("vi-VN,vi;q=0.9,en;q=0.8", "vi-VN"), ("en-US,en;q=0.9", "en-US")),
64
- "ID": (("id-ID,id;q=0.9,en;q=0.8", "id-ID"), ("en-US,en;q=0.9", "en-US")),
65
- "IN": (("en-IN,en;q=0.9", "en-IN"), ("hi-IN,hi;q=0.9,en;q=0.8", "hi-IN")),
66
- "TR": (("tr-TR,tr;q=0.9,en;q=0.8", "tr-TR"), ("en-US,en;q=0.9", "en-US")),
67
- "AE": (("ar-AE,ar;q=0.9,en;q=0.8", "ar-AE"), ("en-US,en;q=0.9", "en-US")),
68
- "SA": (("ar-SA,ar;q=0.9,en;q=0.8", "ar-SA"), ("en-US,en;q=0.9", "en-US")),
69
- "MX": (("es-MX,es;q=0.9,en;q=0.8", "es-MX"), ("en-US,en;q=0.9", "en-US")),
70
- "AR": (("es-AR,es;q=0.9,en;q=0.8", "es-AR"), ("en-US,en;q=0.9", "en-US")),
71
- "CL": (("es-CL,es;q=0.9,en;q=0.8", "es-CL"), ("en-US,en;q=0.9", "en-US")),
72
- "CO": (("es-CO,es;q=0.9,en;q=0.8", "es-CO"), ("en-US,en;q=0.9", "en-US")),
73
- }
74
-
75
- _HISTORY_LENGTHS: tuple[int, ...] = (2, 3, 4, 5, 6, 7, 8, 10)
76
-
77
- # Hardware values are sampled as a persona instead of independently. This
78
- # avoids impossible/rare joins such as a 1366x768 desktop, 32 GB RAM, 4 cores
79
- # and ten touch points. Consumers may pin a persona for a sticky account.
80
- _HARDWARE_PERSONAS: dict[str, dict[str, object]] = {
81
- "win_mainstream": {
82
- "weight": 14,
83
- "platform": "Windows",
84
- "resolutions": ("1920x1080", "1536x864", "1600x900", "1366x768"),
85
- "cores": (8, 12, 16),
86
- "memory": (8.0, 16.0),
87
- "touch": (0,),
88
- "architecture": "x86",
89
- "platform_versions": ("10.0.0", "15.0.0", "19.0.0"),
90
- "webgl": (
91
- (
92
- "Google Inc. (Intel)",
93
- "ANGLE (Intel, Intel(R) UHD Graphics 630, Direct3D11 vs_5_0 ps_5_0, D3D11)",
94
- ),
95
- (
96
- "Google Inc. (NVIDIA)",
97
- "ANGLE (NVIDIA, NVIDIA GeForce GTX 1650, Direct3D11 vs_5_0 ps_5_0, D3D11)",
98
- ),
99
- ),
100
- },
101
- "win_gaming": {
102
- "weight": 8,
103
- "platform": "Windows",
104
- "resolutions": ("1920x1080", "2560x1440", "3440x1440"),
105
- "cores": (12, 16, 20, 24),
106
- "memory": (16.0, 32.0),
107
- "touch": (0,),
108
- "architecture": "x86",
109
- "platform_versions": ("15.0.0", "19.0.0"),
110
- "webgl": (
111
- (
112
- "Google Inc. (NVIDIA)",
113
- "ANGLE (NVIDIA, NVIDIA GeForce GTX 1660 SUPER, Direct3D11 vs_5_0 ps_5_0, D3D11)",
114
- ),
115
- (
116
- "Google Inc. (NVIDIA)",
117
- "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060, Direct3D11 vs_5_0 ps_5_0, D3D11)",
118
- ),
119
- (
120
- "Google Inc. (AMD)",
121
- "ANGLE (AMD, AMD Radeon RX 6600 XT, Direct3D11 vs_5_0 ps_5_0, D3D11)",
122
- ),
123
- ),
124
- },
125
- "win_gtx1660": {
126
- "weight": 1,
127
- "platform": "Windows",
128
- "resolutions": ("1920x1080",),
129
- "cores": (20,),
130
- "memory": (8.0,),
131
- "touch": (0,),
132
- "architecture": "x86",
133
- "platform_versions": ("15.0.0",),
134
- "webgl": (
135
- (
136
- "Google Inc. (NVIDIA)",
137
- "ANGLE (NVIDIA, NVIDIA GeForce GTX 1660 SUPER, Direct3D11 vs_5_0 ps_5_0, D3D11)",
138
- ),
139
- ),
140
- },
141
- "win_touch_laptop": {
142
- "weight": 3,
143
- "platform": "Windows",
144
- "resolutions": ("1920x1080", "1536x864", "1280x800"),
145
- "cores": (8, 12, 16),
146
- "memory": (8.0, 16.0),
147
- "touch": (10,),
148
- "architecture": "x86",
149
- "platform_versions": ("15.0.0", "19.0.0"),
150
- "webgl": (
151
- (
152
- "Google Inc. (Intel)",
153
- "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics, Direct3D11 vs_5_0 ps_5_0, D3D11)",
154
- ),
155
- ),
156
- },
157
- "mac_intel": {
158
- "weight": 5,
159
- "platform": "macOS",
160
- "resolutions": ("1440x900", "1680x1050", "2560x1600"),
161
- "cores": (8, 12),
162
- "memory": (8.0, 16.0),
163
- "touch": (0,),
164
- "architecture": "x86",
165
- "platform_versions": ("13.6.0", "14.5.0"),
166
- "webgl": (
167
- (
168
- "Google Inc. (Intel Inc.)",
169
- "ANGLE (Intel Inc., Intel(R) Iris(TM) Plus Graphics, OpenGL 4.1)",
170
- ),
171
- ),
172
- },
173
- "win_office_uhd630": {
174
- "weight": 10,
175
- "platform": "Windows",
176
- "resolutions": ("1920x1080", "1600x900", "1366x768"),
177
- "cores": (4, 8),
178
- "memory": (8.0, 16.0),
179
- "touch": (0,),
180
- "architecture": "x86",
181
- "platform_versions": ("10.0.0", "15.0.0"),
182
- "webgl": ((
183
- "Google Inc. (Intel)",
184
- "ANGLE (Intel, Intel(R) UHD Graphics 630, Direct3D11 vs_5_0 ps_5_0, D3D11)",
185
- ),),
186
- },
187
- "win_office_vega8": {
188
- "weight": 7,
189
- "platform": "Windows",
190
- "resolutions": ("1920x1080", "1600x900", "1366x768"),
191
- "cores": (8, 12),
192
- "memory": (8.0, 16.0),
193
- "touch": (0,),
194
- "architecture": "x86",
195
- "platform_versions": ("10.0.0", "15.0.0"),
196
- "webgl": ((
197
- "Google Inc. (AMD)",
198
- "ANGLE (AMD, AMD Radeon(TM) Vega 8 Graphics, Direct3D11 vs_5_0 ps_5_0, D3D11)",
199
- ),),
200
- },
201
- "win_laptop_iris_xe": {
202
- "weight": 12,
203
- "platform": "Windows",
204
- "resolutions": ("1920x1080", "1920x1200", "1536x864", "1366x768"),
205
- "cores": (8, 12, 16),
206
- "memory": (8.0, 16.0),
207
- "touch": (0,),
208
- "architecture": "x86",
209
- "platform_versions": ("15.0.0", "19.0.0"),
210
- "webgl": ((
211
- "Google Inc. (Intel)",
212
- "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics, Direct3D11 vs_5_0 ps_5_0, D3D11)",
213
- ),),
214
- },
215
- "win_laptop_amd_780m": {
216
- "weight": 6,
217
- "platform": "Windows",
218
- "resolutions": ("1920x1080", "1920x1200", "2560x1600"),
219
- "cores": (12, 16),
220
- "memory": (16.0, 32.0),
221
- "touch": (0,),
222
- "architecture": "x86",
223
- "platform_versions": ("15.0.0", "19.0.0"),
224
- "webgl": ((
225
- "Google Inc. (AMD)",
226
- "ANGLE (AMD, AMD Radeon 780M Graphics, Direct3D11 vs_5_0 ps_5_0, D3D11)",
227
- ),),
228
- },
229
- "win_gaming_rtx2060": {
230
- "weight": 4,
231
- "platform": "Windows",
232
- "resolutions": ("1920x1080", "2560x1440"),
233
- "cores": (12, 16),
234
- "memory": (16.0, 32.0),
235
- "touch": (0,),
236
- "architecture": "x86",
237
- "platform_versions": ("10.0.0", "15.0.0"),
238
- "webgl": ((
239
- "Google Inc. (NVIDIA)",
240
- "ANGLE (NVIDIA, NVIDIA GeForce RTX 2060, Direct3D11 vs_5_0 ps_5_0, D3D11)",
241
- ),),
242
- },
243
- "win_gaming_rtx3060": {
244
- "weight": 8,
245
- "platform": "Windows",
246
- "resolutions": ("1920x1080", "2560x1440"),
247
- "cores": (12, 16, 20),
248
- "memory": (16.0, 32.0),
249
- "touch": (0,),
250
- "architecture": "x86",
251
- "platform_versions": ("15.0.0", "19.0.0"),
252
- "webgl": ((
253
- "Google Inc. (NVIDIA)",
254
- "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060, Direct3D11 vs_5_0 ps_5_0, D3D11)",
255
- ),),
256
- },
257
- "win_gaming_rtx3070": {
258
- "weight": 4,
259
- "platform": "Windows",
260
- "resolutions": ("1920x1080", "2560x1440", "3440x1440"),
261
- "cores": (16, 20, 24),
262
- "memory": (16.0, 32.0),
263
- "touch": (0,),
264
- "architecture": "x86",
265
- "platform_versions": ("15.0.0", "19.0.0"),
266
- "webgl": ((
267
- "Google Inc. (NVIDIA)",
268
- "ANGLE (NVIDIA, NVIDIA GeForce RTX 3070, Direct3D11 vs_5_0 ps_5_0, D3D11)",
269
- ),),
270
- },
271
- "win_gaming_rtx4060": {
272
- "weight": 7,
273
- "platform": "Windows",
274
- "resolutions": ("1920x1080", "2560x1440"),
275
- "cores": (16, 20, 24),
276
- "memory": (16.0, 32.0),
277
- "touch": (0,),
278
- "architecture": "x86",
279
- "platform_versions": ("15.0.0", "19.0.0"),
280
- "webgl": ((
281
- "Google Inc. (NVIDIA)",
282
- "ANGLE (NVIDIA, NVIDIA GeForce RTX 4060, Direct3D11 vs_5_0 ps_5_0, D3D11)",
283
- ),),
284
- },
285
- "win_gaming_rtx4070": {
286
- "weight": 3,
287
- "platform": "Windows",
288
- "resolutions": ("2560x1440", "3440x1440", "3840x2160"),
289
- "cores": (20, 24, 32),
290
- "memory": (32.0, 64.0),
291
- "touch": (0,),
292
- "architecture": "x86",
293
- "platform_versions": ("19.0.0",),
294
- "webgl": ((
295
- "Google Inc. (NVIDIA)",
296
- "ANGLE (NVIDIA, NVIDIA GeForce RTX 4070, Direct3D11 vs_5_0 ps_5_0, D3D11)",
297
- ),),
298
- },
299
- "win_gaming_rx6600": {
300
- "weight": 5,
301
- "platform": "Windows",
302
- "resolutions": ("1920x1080", "2560x1440"),
303
- "cores": (12, 16),
304
- "memory": (16.0, 32.0),
305
- "touch": (0,),
306
- "architecture": "x86",
307
- "platform_versions": ("15.0.0", "19.0.0"),
308
- "webgl": ((
309
- "Google Inc. (AMD)",
310
- "ANGLE (AMD, AMD Radeon RX 6600 XT, Direct3D11 vs_5_0 ps_5_0, D3D11)",
311
- ),),
312
- },
313
- "win_gaming_rx6700xt": {
314
- "weight": 3,
315
- "platform": "Windows",
316
- "resolutions": ("1920x1080", "2560x1440", "3440x1440"),
317
- "cores": (16, 20, 24),
318
- "memory": (16.0, 32.0),
319
- "touch": (0,),
320
- "architecture": "x86",
321
- "platform_versions": ("15.0.0", "19.0.0"),
322
- "webgl": ((
323
- "Google Inc. (AMD)",
324
- "ANGLE (AMD, AMD Radeon RX 6700 XT, Direct3D11 vs_5_0 ps_5_0, D3D11)",
325
- ),),
326
- },
327
- "win_workstation_a2000": {
328
- "weight": 1,
329
- "platform": "Windows",
330
- "resolutions": ("1920x1080", "2560x1440", "3840x2160"),
331
- "cores": (16, 24, 32),
332
- "memory": (32.0, 64.0),
333
- "touch": (0,),
334
- "architecture": "x86",
335
- "platform_versions": ("15.0.0", "19.0.0"),
336
- "webgl": ((
337
- "Google Inc. (NVIDIA)",
338
- "ANGLE (NVIDIA, NVIDIA RTX A2000, Direct3D11 vs_5_0 ps_5_0, D3D11)",
339
- ),),
340
- },
341
- "win_workstation_a4000": {
342
- "weight": 1,
343
- "platform": "Windows",
344
- "resolutions": ("2560x1440", "3840x2160"),
345
- "cores": (24, 32, 64),
346
- "memory": (32.0, 64.0),
347
- "touch": (0,),
348
- "architecture": "x86",
349
- "platform_versions": ("19.0.0",),
350
- "webgl": ((
351
- "Google Inc. (NVIDIA)",
352
- "ANGLE (NVIDIA, NVIDIA RTX A4000, Direct3D11 vs_5_0 ps_5_0, D3D11)",
353
- ),),
354
- },
355
- "win_low_power_uhd620": {
356
- "weight": 7,
357
- "platform": "Windows",
358
- "resolutions": ("1366x768", "1536x864", "1920x1080"),
359
- "cores": (4, 8),
360
- "memory": (4.0, 8.0),
361
- "touch": (0,),
362
- "architecture": "x86",
363
- "platform_versions": ("10.0.0", "15.0.0"),
364
- "webgl": ((
365
- "Google Inc. (Intel)",
366
- "ANGLE (Intel, Intel(R) UHD Graphics 620, Direct3D11 vs_5_0 ps_5_0, D3D11)",
367
- ),),
368
- },
369
- "win_ultrawide_rtx3080": {
370
- "weight": 1,
371
- "platform": "Windows",
372
- "resolutions": ("3440x1440", "3840x1600"),
373
- "cores": (20, 24, 32),
374
- "memory": (32.0, 64.0),
375
- "touch": (0,),
376
- "architecture": "x86",
377
- "platform_versions": ("15.0.0", "19.0.0"),
378
- "webgl": ((
379
- "Google Inc. (NVIDIA)",
380
- "ANGLE (NVIDIA, NVIDIA GeForce RTX 3080, Direct3D11 vs_5_0 ps_5_0, D3D11)",
381
- ),),
382
- },
383
- "win_touch_iris_xe": {
384
- "weight": 4,
385
- "platform": "Windows",
386
- "resolutions": ("1920x1080", "1920x1200", "2256x1504"),
387
- "cores": (8, 12, 16),
388
- "memory": (8.0, 16.0),
389
- "touch": (10,),
390
- "architecture": "x86",
391
- "platform_versions": ("15.0.0", "19.0.0"),
392
- "webgl": ((
393
- "Google Inc. (Intel)",
394
- "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics, Direct3D11 vs_5_0 ps_5_0, D3D11)",
395
- ),),
396
- },
397
- "mac_m1": {
398
- "weight": 8,
399
- "platform": "macOS",
400
- "resolutions": ("1440x900", "1680x1050", "2560x1600"),
401
- "cores": (8,),
402
- "memory": (8.0, 16.0),
403
- "touch": (0,),
404
- "architecture": "arm",
405
- "platform_versions": ("13.6.0", "14.5.0"),
406
- "webgl": ((
407
- "Google Inc. (Apple)",
408
- "ANGLE (Apple, ANGLE Metal Renderer: Apple M1, Unspecified Version)",
409
- ),),
410
- },
411
- "mac_m2": {
412
- "weight": 7,
413
- "platform": "macOS",
414
- "resolutions": ("1470x956", "1710x1112", "2560x1664", "3024x1964"),
415
- "cores": (8, 10, 12),
416
- "memory": (8.0, 16.0, 24.0),
417
- "touch": (0,),
418
- "architecture": "arm",
419
- "platform_versions": ("13.6.0", "14.5.0", "15.0.0"),
420
- "webgl": ((
421
- "Google Inc. (Apple)",
422
- "ANGLE (Apple, ANGLE Metal Renderer: Apple M2, Unspecified Version)",
423
- ),),
424
- },
425
- "mac_m3": {
426
- "weight": 5,
427
- "platform": "macOS",
428
- "resolutions": ("1470x956", "1710x1112", "2560x1664", "3024x1964"),
429
- "cores": (8, 10, 12),
430
- "memory": (8.0, 16.0, 24.0, 36.0),
431
- "touch": (0,),
432
- "architecture": "arm",
433
- "platform_versions": ("14.5.0", "15.0.0"),
434
- "webgl": ((
435
- "Google Inc. (Apple)",
436
- "ANGLE (Apple, ANGLE Metal Renderer: Apple M3, Unspecified Version)",
437
- ),),
438
- },
439
- "mac_m4": {
440
- "weight": 3,
441
- "platform": "macOS",
442
- "resolutions": ("1470x956", "1710x1112", "2560x1664", "3024x1964"),
443
- "cores": (10, 12, 14),
444
- "memory": (16.0, 24.0, 32.0),
445
- "touch": (0,),
446
- "architecture": "arm",
447
- "platform_versions": ("15.0.0",),
448
- "webgl": ((
449
- "Google Inc. (Apple)",
450
- "ANGLE (Apple, ANGLE Metal Renderer: Apple M4, Unspecified Version)",
451
- ),),
452
- },
453
- "mac_intel_iris_pro": {
454
- "weight": 2,
455
- "platform": "macOS",
456
- "resolutions": ("1920x1080", "2560x1440", "2560x1600"),
457
- "cores": (16,),
458
- "memory": (8.0,),
459
- "touch": (0,),
460
- "architecture": "x86",
461
- "platform_versions": ("13.6.0", "14.5.0"),
462
- "webgl": ((
463
- "Google Inc. (Intel Inc.)",
464
- "ANGLE (Intel, ANGLE Metal Renderer: Intel Iris Pro OpenGL Engine, Unspecified Version)",
465
- ),),
466
- },
467
- "win_amd_radeon_164e": {
468
- "weight": 2,
469
- "platform": "Windows",
470
- "resolutions": ("1920x1080", "1920x1200", "2560x1440"),
471
- "cores": (20,),
472
- "memory": (8.0,),
473
- "touch": (0,),
474
- "architecture": "x86",
475
- "platform_versions": ("15.0.0", "19.0.0"),
476
- "webgl": ((
477
- "Google Inc. (AMD)",
478
- "ANGLE (AMD, AMD Radeon(TM) Graphics (0x0000164E) Direct3D11 vs_5_0 ps_5_0, D3D11-27.20.11028.10001)",
479
- ),),
480
- },
481
- "win_amd_760g": {
482
- "weight": 1,
483
- "platform": "Windows",
484
- "resolutions": ("1366x768", "1600x900", "1920x1080"),
485
- "cores": (20,),
486
- "memory": (8.0,),
487
- "touch": (0,),
488
- "architecture": "x86",
489
- "platform_versions": ("10.0.0",),
490
- "webgl": ((
491
- "Google Inc. (AMD)",
492
- "ANGLE (AMD, AMD 760G (Microsoft Corporation WDDM 1.1) (0x00001636) Direct3D9Ex vs_3_0 ps_3_0, D3D9Ex)",
493
- ),),
494
- },
495
- "win_intel_uhd600": {
496
- "weight": 2,
497
- "platform": "Windows",
498
- "resolutions": ("1366x768", "1600x900", "1920x1080"),
499
- "cores": (20,),
500
- "memory": (8.0,),
501
- "touch": (0,),
502
- "architecture": "x86",
503
- "platform_versions": ("10.0.0", "15.0.0"),
504
- "webgl": ((
505
- "Google Inc. (Intel)",
506
- "ANGLE (Intel, Intel(R) UHD Graphics 600 (0x00003185) Direct3D11 vs_5_0 ps_5_0, D3D11)",
507
- ),),
508
- },
509
- }
510
-
511
- # (offset_min, label) — multiple options per region to avoid fixed fingerprint
512
- _TIMEZONES_BY_REGION: dict[str, tuple[tuple[int, str], ...]] = {
513
- "JP": ((540, "日本标准时间"),),
514
- "KR": ((540, "韩国标准时间"),),
515
- "SG": ((480, "新加坡标准时间"),),
516
- "HK": ((480, "香港标准时间"),),
517
- "TW": ((480, "台北标准时间"),),
518
- "MY": ((480, "马来西亚时间"),),
519
- "PH": ((480, "菲律宾标准时间"),),
520
- "CN": ((480, "中国标准时间"),),
521
- "TH": ((420, "印度支那时间"),),
522
- "VN": ((420, "印度支那时间"),),
523
- "ID": ((420, "印度尼西亚西部时间"), (480, "印度尼西亚中部时间"), (540, "印度尼西亚东部时间")),
524
- "IN": ((330, "印度标准时间"),),
525
- "AE": ((240, "海湾标准时间"),),
526
- "SA": ((180, "阿拉伯标准时间"),),
527
- "TR": ((180, "土耳其时间"),),
528
- "US": (
529
- (-480, "太平洋标准时间"),
530
- (-420, "太平洋夏令时间"),
531
- (-420, "山地标准时间"),
532
- (-360, "山地夏令时间"),
533
- (-360, "中部标准时间"),
534
- (-300, "中部夏令时间"),
535
- (-300, "东部标准时间"),
536
- (-240, "东部夏令时间"),
537
- ),
538
- "CA": (
539
- (-480, "太平洋标准时间"),
540
- (-420, "太平洋夏令时间"),
541
- (-300, "东部标准时间"),
542
- (-240, "东部夏令时间"),
543
- ),
544
- "GB": ((0, "格林尼治标准时间"), (60, "英国夏令时间")),
545
- "UK": ((0, "格林尼治标准时间"), (60, "英国夏令时间")),
546
- "IE": ((0, "格林尼治标准时间"), (60, "爱尔兰夏令时间")),
547
- "DE": ((60, "中欧标准时间"), (120, "中欧夏令时间")),
548
- "FR": ((60, "中欧标准时间"), (120, "中欧夏令时间")),
549
- "NL": ((60, "中欧标准时间"), (120, "中欧夏令时间")),
550
- "IT": ((60, "中欧标准时间"), (120, "中欧夏令时间")),
551
- "ES": ((60, "中欧标准时间"), (120, "中欧夏令时间")),
552
- "PT": ((0, "西欧标准时间"), (60, "西欧夏令时间")),
553
- "AU": ((600, "澳大利亚东部标准时间"), (660, "澳大利亚东部夏令时间"), (570, "澳大利亚中部标准时间")),
554
- "NZ": ((720, "新西兰标准时间"), (780, "新西兰夏令时间")),
555
- "BR": ((-180, "巴西利亚时间"), (-120, "亚马逊时间")),
556
- "MX": ((-360, "中部标准时间"), (-300, "中部夏令时间"), (-420, "太平洋标准时间")),
557
- "AR": ((-180, "阿根廷时间"),),
558
- "CL": ((-240, "智利标准时间"), (-180, "智利夏令时间")),
559
- "CO": ((-300, "哥伦比亚时间"),),
560
- }
561
-
562
- # default fallback pool
563
- _TIMEZONES_DEFAULT: tuple[tuple[int, str], ...] = (
564
- (540, "日本标准时间"),
565
- (480, "中国标准时间"),
566
- (-300, "东部标准时间"),
567
- (60, "中欧夏令时间"),
568
- (0, "格林尼治标准时间"),
569
- )
570
-
571
- # IANA names for logging / optional consumers
572
- _IANA_BY_REGION: dict[str, tuple[str, ...]] = {
573
- "JP": ("Asia/Tokyo",),
574
- "KR": ("Asia/Seoul",),
575
- "SG": ("Asia/Singapore",),
576
- "HK": ("Asia/Hong_Kong",),
577
- "TW": ("Asia/Taipei",),
578
- "MY": ("Asia/Kuala_Lumpur",),
579
- "PH": ("Asia/Manila",),
580
- "CN": ("Asia/Shanghai",),
581
- "TH": ("Asia/Bangkok",),
582
- "VN": ("Asia/Ho_Chi_Minh",),
583
- "ID": ("Asia/Jakarta", "Asia/Makassar", "Asia/Jayapura"),
584
- "IN": ("Asia/Kolkata",),
585
- "AE": ("Asia/Dubai",),
586
- "SA": ("Asia/Riyadh",),
587
- "TR": ("Europe/Istanbul",),
588
- "US": ("America/Los_Angeles", "America/Denver", "America/Chicago", "America/New_York"),
589
- "CA": ("America/Vancouver", "America/Toronto"),
590
- "GB": ("Europe/London",),
591
- "UK": ("Europe/London",),
592
- "IE": ("Europe/Dublin",),
593
- "DE": ("Europe/Berlin",),
594
- "FR": ("Europe/Paris",),
595
- "NL": ("Europe/Amsterdam",),
596
- "IT": ("Europe/Rome",),
597
- "ES": ("Europe/Madrid",),
598
- "PT": ("Europe/Lisbon",),
599
- "AU": ("Australia/Sydney", "Australia/Melbourne", "Australia/Adelaide"),
600
- "NZ": ("Pacific/Auckland",),
601
- "BR": ("America/Sao_Paulo",),
602
- "MX": ("America/Mexico_City", "America/Tijuana"),
603
- "AR": ("America/Argentina/Buenos_Aires",),
604
- "CL": ("America/Santiago",),
605
- "CO": ("America/Bogota",),
606
- }
607
-
608
-
609
- @dataclass(slots=True)
610
- class Profile:
611
- user_agent: str
612
- sec_ch_ua: str
613
- sec_ch_ua_platform: str
614
- locale: str
615
- language: str = "en-US"
616
- resolution: str = "1920x1080"
617
- cores: int = 8
618
- history_len: int = 4
619
- timezone_offset_min: int = 540
620
- timezone_label: str = "日本标准时间"
621
- # extra fingerprint fields (safe defaults keep old callers working)
622
- platform_os: str = "Windows"
623
- browser: str = "chrome"
624
- chrome_major: int = 146
625
- chrome_full_version: str = "146.0.7680.0"
626
- device_memory: float = 8.0
627
- max_touch_points: int = 0
628
- region: str = ""
629
- timezone_id: str = "Asia/Tokyo"
630
- tls_impersonate: str = "chrome146"
631
- tls_client_identifier: str = "chrome_146"
632
- # High-entropy UA-CH/runtime fields. Firefox deliberately leaves UA-CH
633
- # brand fields empty because native Firefox does not emit Chromium hints.
634
- platform_version: str = "15.0.0"
635
- architecture: str = "x86"
636
- bitness: str = "64"
637
- mobile: bool = False
638
- hardware_profile: str = "win_mainstream"
639
- webgl_vendor: str = ""
640
- webgl_renderer: str = ""
641
- webrtc_mode: str = "disabled"
642
- geolocation_mode: str = "ask"
643
- canvas_mode: str = "real"
644
- webgl_mode: str = "real"
645
- audio_mode: str = "real"
646
- audio_seed: str = ""
647
- media_devices_mode: str = "real"
648
- media_devices_seed: str = ""
649
- client_rects_mode: str = "real"
650
- client_rects_seed: str = ""
651
- speech_voices_mode: str = "real"
652
- speech_voices_seed: str = ""
653
- webgpu_mode: str = "native"
654
- interface_language_mode: str = "language"
655
- do_not_track_mode: str = "default"
656
- port_scan_protection: bool = False
657
- tls_features_disabled: bool = False
658
- device_name: str = ""
659
- mac_address: str = ""
660
- hardware_acceleration: str = "default"
661
-
662
- @property
663
- def browser_major(self) -> int:
664
- """Browser-neutral alias; ``chrome_major`` remains for compatibility."""
665
- return self.chrome_major
666
-
667
- @property
668
- def browser_full_version(self) -> str:
669
- """Browser-neutral alias; ``chrome_full_version`` remains compatible."""
670
- return self.chrome_full_version
671
-
672
- def request_headers(self, *, high_entropy: bool = False) -> dict[str, str]:
673
- """Return internally consistent UA/locale headers for this profile."""
674
- return profile_headers(self, high_entropy=high_entropy)
675
-
676
-
677
- def _rand_choice(seq):
678
- return seq[secrets.randbelow(len(seq))]
679
-
680
-
681
- def _rand_int(a: int, b: int) -> int:
682
- return a + secrets.randbelow(b - a + 1)
683
-
684
-
685
- def _derived_seed(seed: str, label: str) -> str:
686
- source = f"{str(seed or '0').upper()}:{label}".encode("utf-8")
687
- return hashlib.blake2s(source, digest_size=4).hexdigest().upper()
688
-
689
-
690
- def _device_identity(platform_os: str, seed: str) -> tuple[str, str]:
691
- digest = hashlib.blake2s(
692
- f"{platform_os}:{seed}".encode("utf-8"), digest_size=8
693
- ).digest()
694
- suffix = "".join("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[b % 36] for b in digest[:7])
695
- if platform_os == "macOS":
696
- device_name = f"iMac-{suffix[:5]}"
697
- else:
698
- prefix = ("DESKTOP", "LAPTOP", "USER-PC")[digest[7] % 3]
699
- device_name = f"{prefix}-{suffix}"
700
- mac = bytearray(digest[:6])
701
- mac[0] = (mac[0] | 0x02) & 0xFE # locally administered, unicast
702
- separator = ":" if platform_os == "macOS" else "-"
703
- return device_name, separator.join(f"{part:02X}" for part in mac)
704
-
705
-
706
- def _pick_hardware(platform_os: str, name: str | None = None) -> tuple[str, dict[str, object]]:
707
- requested = str(name or "").strip().lower()
708
- if requested:
709
- persona = _HARDWARE_PERSONAS.get(requested)
710
- if persona is None:
711
- raise ValueError(f"unknown hardware profile: {name}")
712
- if persona["platform"] != platform_os:
713
- raise ValueError(
714
- f"hardware profile {requested!r} is {persona['platform']}, not {platform_os}"
715
- )
716
- return requested, persona
717
- names = [
718
- key
719
- for key, value in _HARDWARE_PERSONAS.items()
720
- if value["platform"] == platform_os
721
- ]
722
- total = sum(max(1, int(_HARDWARE_PERSONAS[key].get("weight", 1))) for key in names)
723
- ticket = secrets.randbelow(total)
724
- selected = names[-1]
725
- for key in names:
726
- ticket -= max(1, int(_HARDWARE_PERSONAS[key].get("weight", 1)))
727
- if ticket < 0:
728
- selected = key
729
- break
730
- return selected, _HARDWARE_PERSONAS[selected]
731
-
732
-
733
- def hardware_profile_names(platform_os: str | None = None) -> tuple[str, ...]:
734
- """List stable hardware persona identifiers exposed by the library."""
735
- wanted = str(platform_os or "").strip()
736
- return tuple(
737
- key
738
- for key, value in _HARDWARE_PERSONAS.items()
739
- if not wanted or value["platform"] == wanted
740
- )
741
-
742
-
743
- def _hardware_values(persona: dict[str, object]) -> tuple[str, int, float, int, str, str, str, str]:
744
- resolution = _rand_choice(persona["resolutions"])
745
- cores = int(_rand_choice(persona["cores"]))
746
- memory = float(_rand_choice(persona["memory"]))
747
- touch = int(_rand_choice(persona["touch"]))
748
- platform_version = str(_rand_choice(persona["platform_versions"]))
749
- architecture = str(persona["architecture"])
750
- vendor, renderer = _rand_choice(persona["webgl"])
751
- return (
752
- str(resolution),
753
- cores,
754
- memory,
755
- touch,
756
- platform_version,
757
- architecture,
758
- str(vendor),
759
- str(renderer),
760
- )
761
-
762
-
763
- def _chrome_full_version(major: int) -> str:
764
- # Known Chromium branch bases; the reduced HTTP UA still uses x.0.0.0,
765
- # while UAData may expose this task-stable full version.
766
- branch = {
767
- 144: 7559,
768
- 145: 7632,
769
- 146: 7680,
770
- 148: 7778,
771
- 149: 7827,
772
- 150: 7871,
773
- }.get(major, 7680)
774
- build = branch
775
- patch = _rand_int(60, 220)
776
- return f"{major}.0.{build}.{patch}"
777
-
778
-
779
- def _build_ua_and_ch(major: int, browser: str, platform_os: str) -> tuple[str, str, str, str, str]:
780
- full = _chrome_full_version(major)
781
- if platform_os == "macOS":
782
- ua_plat = _rand_choice(_MAC_UA_PLATFORMS)
783
- ch_platform = '"macOS"'
784
- base = (
785
- f"Mozilla/5.0 ({ua_plat}) AppleWebKit/537.36 "
786
- f"(KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36"
787
- )
788
- else:
789
- ch_platform = '"Windows"'
790
- base = (
791
- f"Mozilla/5.0 ({_WINDOWS_UA_PLATFORM}) AppleWebKit/537.36 "
792
- f"(KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36"
793
- )
794
-
795
- if browser == "edge":
796
- # Edge mainly Windows; if mac selected, still emit Edge UA form
797
- user_agent = f"{base} Edg/{major}.0.0.0"
798
- sec_ch_ua = (
799
- f'"Not;A=Brand";v="8", "Chromium";v="{major}", '
800
- f'"Microsoft Edge";v="{major}"'
801
- )
802
- browser_name = "edge"
803
- else:
804
- user_agent = base
805
- sec_ch_ua = (
806
- f'"Not;A=Brand";v="8", "Chromium";v="{major}", '
807
- f'"Google Chrome";v="{major}"'
808
- )
809
- browser_name = "chrome"
810
- return user_agent, sec_ch_ua, ch_platform, full, browser_name
811
-
812
-
813
- def proxy_region_code(proxy: str | None) -> str:
814
- """Extract provider region code from URLs like ...-region-JP-sid-..."""
815
- if not proxy:
816
- return ""
817
- text = str(proxy)
818
- patterns = (
819
- r"(?:^|[-_./?&])region[-_=/]?([A-Za-z]{2})(?:[-_./?&]|$)",
820
- r"(?:^|[-_./?&])(?:country|cc|loc)[-_=/]?([A-Za-z]{2})(?:[-_./?&]|$)",
821
- )
822
- for pat in patterns:
823
- m = re.search(pat, text, flags=re.I)
824
- if m:
825
- return m.group(1).upper()
826
- return ""
827
-
828
-
829
- def _pick_locale(region: str) -> tuple[str, str]:
830
- region = (region or "").upper()
831
- pool = _LOCALES_BY_REGION.get(region) or _LOCALES_GENERIC
832
- return _rand_choice(pool)
833
-
834
-
835
- def _timezone_parts(timezone_id: str, region: str = "") -> tuple[int, str, str]:
836
- timezone_id = str(timezone_id or "UTC").strip() or "UTC"
837
- try:
838
- now = datetime.now(ZoneInfo(timezone_id))
839
- offset = int((now.utcoffset() or now.astimezone().utcoffset()).total_seconds() // 60)
840
- # Locale-neutral and DST-correct. The same label is injected into the
841
- # Sentinel JS context, so requirements p and enforcement t agree.
842
- label = str(now.tzname() or timezone_id)
843
- return offset, label, timezone_id
844
- except (ZoneInfoNotFoundError, OSError, ValueError):
845
- # Minimal compatibility fallback for environments missing tzdata.
846
- # Production requirements install tzdata, so this branch is mainly for
847
- # old embedded runtimes.
848
- tz_pool = _TIMEZONES_BY_REGION.get((region or "").upper()) or _TIMEZONES_DEFAULT
849
- offset, label = _rand_choice(tz_pool)
850
- return offset, label, timezone_id
851
-
852
-
853
- def _pick_timezone(region: str) -> tuple[int, str, str]:
854
- region = (region or "").upper()
855
- iana_pool = _IANA_BY_REGION.get(region) or ("UTC",)
856
- return _timezone_parts(_rand_choice(iana_pool), region)
857
-
858
-
859
-
860
- # curl_cffi 0.15 request-time-supported desktop Chrome targets.
861
- # Session construction is lazy, so unsupported values can appear valid until
862
- # the first request. chrome144 is deliberately absent: the bundled transport
863
- # raises "Impersonating chrome144 is not supported" at request time.
864
- _TLS_CHROME_AVAILABLE: tuple[int, ...] = (120, 123, 124, 131, 136, 142, 145, 146)
865
- _TLS_CHROME_SPECIAL: dict[int, str] = {
866
- # package uses chrome133a, not chrome133
867
- 133: "chrome133a",
868
- }
869
- _TLS_FIREFOX_AVAILABLE: tuple[int, ...] = (133, 135, 144, 147)
870
- _TLS_CLIENT_CHROME_AVAILABLE: tuple[int, ...] = (144, 146)
871
- _TLS_CLIENT_FIREFOX_AVAILABLE: tuple[int, ...] = (146,)
872
-
873
-
874
- def choose_tls_impersonate(
875
- *,
876
- browser: str,
877
- chrome_major: int,
878
- platform_os: str = "Windows",
879
- ) -> str:
880
- """Map UA browser/version to a real curl_cffi impersonate target.
881
-
882
- Prefer nearest lower-or-equal Chrome major so JA3 stays consistent with
883
- advertised Chromium version. Edge sometimes uses edge101 for diversity.
884
- Always return a target known-supported by curl_cffi 0.15.
885
- """
886
- browser = (browser or "chrome").lower()
887
- major = int(chrome_major or 146)
888
-
889
- if browser == "firefox":
890
- lower = [m for m in _TLS_FIREFOX_AVAILABLE if m <= major]
891
- pick = lower[-1] if lower else _TLS_FIREFOX_AVAILABLE[0]
892
- return f"firefox{pick}"
893
- if browser == "edge":
894
- # edge impersonate set is sparse; mix edge101 with chrome TLS
895
- if platform_os == "Windows" and (major % 5 == 0):
896
- return "edge101"
897
- if browser == "safari":
898
- return "safari18_0" if major >= 140 else "safari17_0"
899
-
900
- if major in _TLS_CHROME_SPECIAL:
901
- return _TLS_CHROME_SPECIAL[major]
902
-
903
- lower = [m for m in _TLS_CHROME_AVAILABLE if m <= major]
904
- if lower:
905
- pick = lower[-1]
906
- else:
907
- pick = min(_TLS_CHROME_AVAILABLE, key=lambda m: abs(m - major))
908
- return f"chrome{pick}"
909
-
910
-
911
- def choose_tls_client_identifier(*, browser: str, browser_major: int) -> str:
912
- """Map a browser UA to an installed tls-client-python identifier."""
913
- browser = str(browser or "chrome").lower()
914
- major = int(browser_major or 146)
915
- if browser == "firefox":
916
- lower = [m for m in _TLS_CLIENT_FIREFOX_AVAILABLE if m <= major]
917
- pick = lower[-1] if lower else _TLS_CLIENT_FIREFOX_AVAILABLE[0]
918
- # The installed transport exposes Firefox 146 as a PSK preset.
919
- return f"firefox_{pick}_PSK"
920
- lower = [m for m in _TLS_CLIENT_CHROME_AVAILABLE if m <= major]
921
- pick = lower[-1] if lower else _TLS_CLIENT_CHROME_AVAILABLE[0]
922
- return f"chrome_{pick}"
923
-
924
-
925
- # Region-localized given/family names for create_account payloads.
926
- _NAMES_EN: tuple[tuple[str, ...], tuple[str, ...]] = (
927
- (
928
- "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph",
929
- "Thomas", "Charles", "Daniel", "Matthew", "Anthony", "Mark", "Steven", "Paul",
930
- "Andrew", "Joshua", "Kevin", "Brian", "Emily", "Jessica", "Ashley", "Sarah",
931
- "Amanda", "Melissa", "Nicole", "Michelle", "Kimberly", "Amy", "Angela", "Stephanie",
932
- "Rebecca", "Laura", "Samantha", "Rachel", "Lauren", "Hannah", "Olivia", "Emma",
933
- ),
934
- (
935
- "Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis",
936
- "Rodriguez", "Martinez", "Hernandez", "Lopez", "Gonzalez", "Wilson", "Anderson",
937
- "Thomas", "Taylor", "Moore", "Jackson", "Martin", "Lee", "Perez", "Thompson",
938
- "White", "Harris", "Sanchez", "Clark", "Ramirez", "Lewis", "Robinson", "Walker",
939
- "Young", "Allen", "King", "Wright", "Scott", "Torres", "Nguyen", "Hill", "Flores",
940
- ),
941
- )
942
-
943
- _NAMES_BY_REGION: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {
944
- "US": _NAMES_EN,
945
- "CA": _NAMES_EN,
946
- "GB": (
947
- (
948
- "Oliver", "George", "Harry", "Jack", "Jacob", "Noah", "Charlie", "Thomas",
949
- "Oscar", "William", "James", "Amelia", "Olivia", "Isla", "Ava", "Emily",
950
- "Sophia", "Grace", "Mia", "Poppy", "Lily", "Ella",
951
- ),
952
- (
953
- "Smith", "Jones", "Taylor", "Brown", "Williams", "Wilson", "Johnson", "Davies",
954
- "Patel", "Wright", "Evans", "Thomas", "Roberts", "Walker", "Thompson", "White",
955
- "Hughes", "Edwards", "Green", "Hall", "Clarke", "Harris",
956
- ),
957
- ),
958
- "AU": _NAMES_EN,
959
- "NZ": _NAMES_EN,
960
- "DE": (
961
- (
962
- "Lukas", "Leon", "Luca", "Felix", "Maximilian", "Paul", "Elias", "Jonas",
963
- "Noah", "Ben", "Mia", "Emma", "Hannah", "Sophia", "Emilia", "Lina", "Marie",
964
- "Anna", "Lea", "Lena", "Clara", "Laura",
965
- ),
966
- (
967
- "Muller", "Schmidt", "Schneider", "Fischer", "Weber", "Meyer", "Wagner",
968
- "Becker", "Schulz", "Hoffmann", "Schafer", "Koch", "Bauer", "Richter",
969
- "Klein", "Wolf", "Schroder", "Neumann", "Schwarz", "Zimmermann", "Braun",
970
- "Kruger", "Hofmann", "Hartmann",
971
- ),
972
- ),
973
- "FR": (
974
- (
975
- "Lucas", "Louis", "Gabriel", "Arthur", "Hugo", "Jules", "Leo", "Adam",
976
- "Raphael", "Paul", "Emma", "Jade", "Louise", "Alice", "Chloe", "Lina",
977
- "Mila", "Lea", "Manon", "Camille", "Ines", "Rose",
978
- ),
979
- (
980
- "Martin", "Bernard", "Thomas", "Petit", "Robert", "Richard", "Durand",
981
- "Dubois", "Moreau", "Laurent", "Simon", "Michel", "Lefebvre", "Leroy",
982
- "Roux", "David", "Bertrand", "Morel", "Fournier", "Girard", "Bonnet",
983
- "Dupont", "Lambert", "Fontaine",
984
- ),
985
- ),
986
- "NL": (
987
- (
988
- "Daan", "Sem", "Lucas", "Levi", "Finn", "Luuk", "Bram", "Noah", "Milan",
989
- "Jesse", "Emma", "Tess", "Sophie", "Julia", "Zoe", "Sara", "Anna", "Liv",
990
- "Nora", "Lotte", "Eva", "Fleur",
991
- ),
992
- (
993
- "de Jong", "Jansen", "de Vries", "van den Berg", "van Dijk", "Bakker",
994
- "Janssen", "Visser", "Smit", "Meijer", "de Boer", "Mulder", "de Groot",
995
- "Bos", "Vos", "Peters", "Hendriks", "van Leeuwen", "Dekker", "Brouwer",
996
- ),
997
- ),
998
- "IT": (
999
- (
1000
- "Leonardo", "Francesco", "Alessandro", "Lorenzo", "Mattia", "Andrea",
1001
- "Gabriele", "Tommaso", "Riccardo", "Edoardo", "Sofia", "Giulia", "Aurora",
1002
- "Alice", "Ginevra", "Emma", "Giorgia", "Greta", "Beatrice", "Anna",
1003
- ),
1004
- (
1005
- "Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "Romano", "Colombo",
1006
- "Ricci", "Marino", "Greco", "Bruno", "Gallo", "Conti", "De Luca", "Mancini",
1007
- "Costa", "Giordano", "Rizzo", "Lombardi", "Moretti",
1008
- ),
1009
- ),
1010
- "ES": (
1011
- (
1012
- "Hugo", "Martin", "Lucas", "Mateo", "Leo", "Daniel", "Alejandro", "Pablo",
1013
- "Manuel", "Alvaro", "Lucia", "Sofia", "Martina", "Maria", "Julia", "Paula",
1014
- "Valeria", "Emma", "Daniela", "Carla",
1015
- ),
1016
- (
1017
- "Garcia", "Rodriguez", "Gonzalez", "Fernandez", "Lopez", "Martinez",
1018
- "Sanchez", "Perez", "Gomez", "Martin", "Jimenez", "Ruiz", "Hernandez",
1019
- "Diaz", "Moreno", "Alvarez", "Munoz", "Romero", "Alonso", "Gutierrez",
1020
- ),
1021
- ),
1022
- "PT": (
1023
- (
1024
- "Joao", "Francisco", "Santiago", "Afonso", "Duarte", "Tomas", "Martim",
1025
- "Miguel", "Rodrigo", "Gabriel", "Maria", "Leonor", "Matilde", "Beatriz",
1026
- "Carolina", "Alice", "Benedita", "Ines", "Lara", "Mariana",
1027
- ),
1028
- (
1029
- "Silva", "Santos", "Ferreira", "Pereira", "Oliveira", "Costa", "Rodrigues",
1030
- "Martins", "Jesus", "Sousa", "Fernandes", "Goncalves", "Gomes", "Lopes",
1031
- "Marques", "Alves", "Almeida", "Ribeiro", "Pinto", "Carvalho",
1032
- ),
1033
- ),
1034
- "BR": (
1035
- (
1036
- "Miguel", "Arthur", "Gael", "Heitor", "Theo", "Davi", "Gabriel", "Bernardo",
1037
- "Samuel", "Joao", "Helena", "Alice", "Laura", "Maria", "Sophia", "Valentina",
1038
- "Heloisa", "Julia", "Lorena", "Livia",
1039
- ),
1040
- (
1041
- "Silva", "Santos", "Oliveira", "Souza", "Rodrigues", "Ferreira", "Alves",
1042
- "Pereira", "Lima", "Gomes", "Costa", "Ribeiro", "Martins", "Carvalho",
1043
- "Almeida", "Lopes", "Soares", "Fernandes", "Vieira", "Barbosa",
1044
- ),
1045
- ),
1046
- "JP": (
1047
- (
1048
- "Haruto", "Yuto", "Sota", "Ren", "Hinata", "Asahi", "Minato", "Yamato",
1049
- "Aoi", "Itsuki", "Yui", "Hina", "Yuna", "Sakura", "Mio", "Riko",
1050
- "Mei", "Koharu", "Saki", "Nanami", "Ichika",
1051
- ),
1052
- (
1053
- "Sato", "Suzuki", "Takahashi", "Tanaka", "Watanabe", "Ito", "Yamamoto",
1054
- "Nakamura", "Kobayashi", "Kato", "Yoshida", "Yamada", "Sasaki", "Yamaguchi",
1055
- "Matsumoto", "Inoue", "Kimura", "Hayashi", "Shimizu", "Yamazaki", "Mori",
1056
- "Abe", "Ikeda", "Hashimoto",
1057
- ),
1058
- ),
1059
- "KR": (
1060
- (
1061
- "Minjun", "Seojoon", "Dojun", "Siwoo", "Jihun", "Yejun", "Hajun", "Juwon",
1062
- "Geonwoo", "Hyunwoo", "Seoah", "Jiwoo", "Haun", "Yuna", "Sua", "Jiyu",
1063
- "Seoyeon", "Hayoon", "Chaeon", "Yeeun",
1064
- ),
1065
- (
1066
- "Kim", "Lee", "Park", "Choi", "Jung", "Kang", "Cho", "Yoon", "Jang", "Lim",
1067
- "Han", "Oh", "Shin", "Seo", "Kwon", "Hwang", "Ahn", "Song", "Hong", "Yoo",
1068
- ),
1069
- ),
1070
- "CN": (
1071
- (
1072
- "Wei", "Fang", "Na", "Xiuying", "Min", "Jing", "Li", "Yang", "Yong", "Yan",
1073
- "Lei", "Jun", "Qiang", "Jie", "Juan", "Tao", "Ming", "Chao", "Ping", "Hui",
1074
- ),
1075
- (
1076
- "Wang", "Li", "Zhang", "Liu", "Chen", "Yang", "Huang", "Zhao", "Wu", "Zhou",
1077
- "Xu", "Sun", "Ma", "Zhu", "Hu", "Guo", "He", "Gao", "Lin", "Luo",
1078
- ),
1079
- ),
1080
- "TW": (
1081
- (
1082
- "Wei", "Ting", "Yu", "Jia", "An", "Cheng", "Hsuan", "Yi", "Chun", "Kai",
1083
- "Yun", "Han", "Ming", "Chen", "Hao", "En", "Zih", "Rui", "Xin", "Pei",
1084
- ),
1085
- (
1086
- "Chen", "Lin", "Huang", "Chang", "Lee", "Wang", "Wu", "Liu", "Tsai", "Yang",
1087
- "Hsu", "Cheng", "Kuo", "Chiu", "Tseng", "Liao", "Hsieh", "Sung", "Tang",
1088
- ),
1089
- ),
1090
- "HK": (
1091
- (
1092
- "Ka Ming", "Wai", "Chi", "Wing", "Ho", "Kin", "Yiu", "Man", "Siu", "Tsz",
1093
- "Hiu", "Chun", "Lok", "Yin", "Shing", "Long", "Kei", "Yan", "Pui", "Mei",
1094
- ),
1095
- (
1096
- "Chan", "Wong", "Cheung", "Lau", "Lee", "Ng", "Cheng", "Leung", "Ho", "Lam",
1097
- "Yeung", "Tang", "Chow", "Choi", "Yuen", "Mak", "Kwok", "Fung", "Tsang", "Siu",
1098
- ),
1099
- ),
1100
- "SG": _NAMES_EN,
1101
- "MY": (
1102
- (
1103
- "Ahmad", "Muhammad", "Adam", "Daniel", "Ryan", "Aiman", "Hafiz", "Irfan",
1104
- "Amir", "Azlan", "Siti", "Nur", "Aisha", "Aina", "Farah", "Hana", "Maya",
1105
- "Sofia", "Izzati", "Putri",
1106
- ),
1107
- (
1108
- "Abdullah", "Ahmad", "Ismail", "Hassan", "Ibrahim", "Yusof", "Rahman",
1109
- "Chong", "Tan", "Lim", "Ng", "Lee", "Wong", "Goh", "Chan", "Ong", "Teo",
1110
- "Kumar", "Singh", "Rajan",
1111
- ),
1112
- ),
1113
- "PH": (
1114
- (
1115
- "Juan", "Jose", "Miguel", "Carlo", "Mark", "John", "Gabriel", "Angelo",
1116
- "Paolo", "Rafael", "Maria", "Ana", "Sofia", "Andrea", "Angela", "Bianca",
1117
- "Camille", "Denise", "Isabel", "Patricia",
1118
- ),
1119
- (
1120
- "Santos", "Reyes", "Cruz", "Bautista", "Garcia", "Mendoza", "Torres",
1121
- "Flores", "Gonzales", "Ramos", "Lopez", "Aquino", "Diaz", "Rivera",
1122
- "Villanueva", "Castro", "Fernandez", "Navarro", "Domingo", "Santiago",
1123
- ),
1124
- ),
1125
- "TH": (
1126
- (
1127
- "Nattapong", "Somchai", "Anan", "Somsak", "Wichai", "Pichai", "Kittisak",
1128
- "Arthit", "Thanakorn", "Pattarapol", "Nattaya", "Siriporn", "Malee",
1129
- "Kanokwan", "Supaporn", "Pornthip", "Apinya", "Chutima", "Wanida", "Rattana",
1130
- ),
1131
- (
1132
- "Srisawat", "Chaiyaporn", "Saetang", "Wongchai", "Phanich", "Rattanakul",
1133
- "Suksamran", "Boonsri", "Jaidee", "Thongchai", "Kittipong", "Prasert",
1134
- "Siriwan", "Chanthara", "Phetchabun", "Wongsawat", "Anurak", "Kaewmanee",
1135
- ),
1136
- ),
1137
- "VN": (
1138
- (
1139
- "Minh", "Anh", "Hung", "Dung", "Khoa", "Long", "Nam", "Phong", "Quang",
1140
- "Tuan", "Linh", "Huong", "Trang", "Nga", "Thao", "Mai", "Lan", "Hoa",
1141
- "Yen", "My",
1142
- ),
1143
- (
1144
- "Nguyen", "Tran", "Le", "Pham", "Hoang", "Huynh", "Phan", "Vu", "Vo",
1145
- "Dang", "Bui", "Do", "Ho", "Ngo", "Duong", "Ly", "Dinh", "Truong", "Doan",
1146
- "Cao",
1147
- ),
1148
- ),
1149
- "ID": (
1150
- (
1151
- "Budi", "Agus", "Andi", "Ahmad", "Rizky", "Dimas", "Fajar", "Hendra",
1152
- "Yusuf", "Rian", "Siti", "Dewi", "Putri", "Ayu", "Rina", "Fitri", "Lestari",
1153
- "Anisa", "Maya", "Intan",
1154
- ),
1155
- (
1156
- "Santoso", "Wijaya", "Saputra", "Pratama", "Putra", "Hidayat", "Nugroho",
1157
- "Setiawan", "Kurniawan", "Wibowo", "Siregar", "Nasution", "Halim", "Gunawan",
1158
- "Tan", "Lim", "Suharto", "Rahman", "Maulana", "Firmansyah",
1159
- ),
1160
- ),
1161
- "IN": (
1162
- (
1163
- "Aarav", "Vivaan", "Aditya", "Vihaan", "Arjun", "Sai", "Reyansh", "Ayaan",
1164
- "Krishna", "Ishaan", "Aadhya", "Ananya", "Aaradhya", "Pari", "Anika",
1165
- "Navya", "Diya", "Myra", "Sara", "Ira",
1166
- ),
1167
- (
1168
- "Sharma", "Verma", "Patel", "Singh", "Kumar", "Gupta", "Reddy", "Nair",
1169
- "Iyer", "Chopra", "Mehta", "Joshi", "Malhotra", "Kapoor", "Rao", "Das",
1170
- "Banerjee", "Choudhury", "Pandey", "Yadav",
1171
- ),
1172
- ),
1173
- "TR": (
1174
- (
1175
- "Yusuf", "Eymen", "Mirac", "Omer", "Mustafa", "Kerem", "Emir", "Ahmet",
1176
- "Ali", "Huseyin", "Zeynep", "Elif", "Asel", "Defne", "Azra", "Ecrin",
1177
- "Miray", "Nehir", "Eylul", "Masal",
1178
- ),
1179
- (
1180
- "Yilmaz", "Kaya", "Demir", "Celik", "Sahin", "Yildiz", "Yildirim", "Ozturk",
1181
- "Aydin", "Ozdemir", "Arslan", "Dogan", "Kilic", "Aslan", "Cetin", "Kara",
1182
- "Koc", "Kurt", "Ozkan", "Simsek",
1183
- ),
1184
- ),
1185
- "AE": (
1186
- (
1187
- "Omar", "Youssef", "Khalid", "Hassan", "Ahmed", "Ali", "Mohammed", "Faisal",
1188
- "Sultan", "Rashid", "Fatima", "Aisha", "Mariam", "Noor", "Layla", "Sara",
1189
- "Huda", "Amira", "Salma", "Reem",
1190
- ),
1191
- (
1192
- "Al Hashimi", "Al Maktoum", "Al Nahyan", "Al Qasimi", "Al Nuaimi", "Hassan",
1193
- "Ahmed", "Ibrahim", "Ali", "Khan", "Rahman", "Hussein", "Abbas", "Farouk",
1194
- "Salem", "Mansour", "Nasser", "Hamid", "Jaber", "Saeed",
1195
- ),
1196
- ),
1197
- "SA": (
1198
- (
1199
- "Omar", "Youssef", "Khalid", "Hassan", "Ahmed", "Ali", "Mohammed", "Faisal",
1200
- "Sultan", "Abdullah", "Fatima", "Aisha", "Mariam", "Noor", "Layla", "Sara",
1201
- "Huda", "Noura", "Salma", "Reem",
1202
- ),
1203
- (
1204
- "Al Saud", "Al Rashid", "Al Harbi", "Al Ghamdi", "Al Qahtani", "Al Otaibi",
1205
- "Al Zahrani", "Al Shehri", "Al Dosari", "Al Mutairi", "Hassan", "Ahmed",
1206
- "Ibrahim", "Ali", "Khan", "Rahman", "Hussein", "Abbas", "Salem", "Nasser",
1207
- ),
1208
- ),
1209
- "MX": (
1210
- (
1211
- "Santiago", "Mateo", "Sebastian", "Leonardo", "Matias", "Emiliano", "Diego",
1212
- "Daniel", "Miguel", "Angel", "Sofia", "Valentina", "Regina", "Camila",
1213
- "Maria", "Ximena", "Victoria", "Renata", "Daniela", "Fernanda",
1214
- ),
1215
- (
1216
- "Hernandez", "Garcia", "Martinez", "Lopez", "Gonzalez", "Perez", "Rodriguez",
1217
- "Sanchez", "Ramirez", "Cruz", "Flores", "Gomez", "Morales", "Vazquez",
1218
- "Jimenez", "Reyes", "Torres", "Diaz", "Gutierrez", "Ruiz",
1219
- ),
1220
- ),
1221
- "AR": (
1222
- (
1223
- "Santiago", "Mateo", "Juan", "Benjamin", "Felipe", "Tomas", "Lucas", "Bruno",
1224
- "Thiago", "Joaquin", "Sofia", "Valentina", "Emma", "Martina", "Catalina",
1225
- "Olivia", "Isabella", "Mia", "Julieta",
1226
- ),
1227
- (
1228
- "Gonzalez", "Rodriguez", "Gomez", "Fernandez", "Lopez", "Diaz", "Martinez",
1229
- "Perez", "Garcia", "Sanchez", "Romero", "Sosa", "Alvarez", "Torres",
1230
- "Ruiz", "Ramirez", "Flores", "Acosta", "Benitez", "Aguirre",
1231
- ),
1232
- ),
1233
- }
1234
-
1235
- _NAMES_BY_REGION["UK"] = _NAMES_BY_REGION["GB"]
1236
- _NAMES_BY_REGION["IE"] = _NAMES_BY_REGION["GB"]
1237
- _NAMES_BY_REGION["CL"] = _NAMES_BY_REGION["AR"]
1238
- _NAMES_BY_REGION["CO"] = _NAMES_BY_REGION["MX"]
1239
-
1240
-
1241
- def random_person_name(region: str | None = None, language: str | None = None) -> tuple[str, str]:
1242
- """Return (first_name, last_name) localized by region/language."""
1243
- region_code = (region or "").strip().upper()
1244
- lang = (language or "").strip()
1245
-
1246
- pool = _NAMES_BY_REGION.get(region_code)
1247
- if not pool:
1248
- low = lang.lower()
1249
- if low.startswith("ja"):
1250
- pool = _NAMES_BY_REGION["JP"]
1251
- elif low.startswith("ko"):
1252
- pool = _NAMES_BY_REGION["KR"]
1253
- elif low.startswith("zh-tw"):
1254
- pool = _NAMES_BY_REGION["TW"]
1255
- elif low.startswith("zh-hk"):
1256
- pool = _NAMES_BY_REGION["HK"]
1257
- elif low.startswith("zh"):
1258
- pool = _NAMES_BY_REGION["CN"]
1259
- elif low.startswith("de"):
1260
- pool = _NAMES_BY_REGION["DE"]
1261
- elif low.startswith("fr"):
1262
- pool = _NAMES_BY_REGION["FR"]
1263
- elif low.startswith("tr"):
1264
- pool = _NAMES_BY_REGION["TR"]
1265
- elif low.startswith("es"):
1266
- pool = _NAMES_BY_REGION["ES"]
1267
- elif low.startswith("pt"):
1268
- pool = _NAMES_BY_REGION["BR"]
1269
- elif low.startswith("vi"):
1270
- pool = _NAMES_BY_REGION["VN"]
1271
- elif low.startswith("th"):
1272
- pool = _NAMES_BY_REGION["TH"]
1273
- elif low.startswith("id"):
1274
- pool = _NAMES_BY_REGION["ID"]
1275
- elif low.startswith("ar"):
1276
- pool = _NAMES_BY_REGION["AE"]
1277
- else:
1278
- pool = _NAMES_EN
1279
-
1280
- first_pool, last_pool = pool
1281
- return _rand_choice(first_pool), _rand_choice(last_pool)
1282
-
1283
-
1284
- def random_profile(
1285
- *,
1286
- region: str | None = None,
1287
- browser: str | None = None,
1288
- platform_os: str | None = None,
1289
- chrome_major: int | None = None,
1290
- hardware_profile: str | None = None,
1291
- ) -> Profile:
1292
- """Generate a randomized browser fingerprint.
1293
-
1294
- Args:
1295
- region: ISO country/region code (JP/US/TR...). Affects locale + timezone.
1296
- browser: "chrome" | "edge" | None(default Chrome)
1297
- platform_os: "Windows" | "macOS" | None(default Windows)
1298
- """
1299
- region_code = (region or "").strip().upper()
1300
- requested_major = int(chrome_major or 0)
1301
- major = (
1302
- requested_major
1303
- if 100 <= requested_major <= 999
1304
- else _rand_choice(_REALISTIC_MAJORS)
1305
- )
1306
-
1307
- # The bundled transport preset is desktop Chrome/Windows. Explicit
1308
- # overrides remain available for non-registration callers, but automatic
1309
- # generation never mixes a macOS/Edge JS profile into Chrome TLS.
1310
- if platform_os in {"Windows", "macOS"}:
1311
- os_name = platform_os
1312
- else:
1313
- os_name = "Windows"
1314
-
1315
- if browser in {"chrome", "edge"}:
1316
- browser_name = browser
1317
- else:
1318
- browser_name = "chrome"
1319
-
1320
- user_agent, sec_ch_ua, ch_platform, full_ver, browser_name = _build_ua_and_ch(
1321
- major, browser_name, os_name
1322
- )
1323
- locale, language = _pick_locale(region_code)
1324
- tz_offset, tz_label, tz_id = _pick_timezone(region_code)
1325
- hardware_name, hardware = _pick_hardware(os_name, hardware_profile)
1326
- (
1327
- resolution,
1328
- cores,
1329
- device_memory,
1330
- max_touch_points,
1331
- platform_version,
1332
- architecture,
1333
- webgl_vendor,
1334
- webgl_renderer,
1335
- ) = _hardware_values(hardware)
1336
-
1337
- return Profile(
1338
- user_agent=user_agent,
1339
- sec_ch_ua=sec_ch_ua,
1340
- sec_ch_ua_platform=ch_platform,
1341
- locale=locale,
1342
- language=language,
1343
- resolution=resolution,
1344
- cores=cores,
1345
- history_len=_rand_choice(_HISTORY_LENGTHS),
1346
- timezone_offset_min=tz_offset,
1347
- timezone_label=tz_label,
1348
- platform_os=os_name,
1349
- browser=browser_name,
1350
- chrome_major=major,
1351
- chrome_full_version=full_ver,
1352
- device_memory=device_memory,
1353
- max_touch_points=max_touch_points,
1354
- region=region_code,
1355
- timezone_id=tz_id,
1356
- tls_impersonate=choose_tls_impersonate(
1357
- browser=browser_name,
1358
- chrome_major=major,
1359
- platform_os=os_name,
1360
- ),
1361
- tls_client_identifier=choose_tls_client_identifier(
1362
- browser=browser_name,
1363
- browser_major=major,
1364
- ),
1365
- platform_version=platform_version,
1366
- architecture=architecture,
1367
- hardware_profile=hardware_name,
1368
- webgl_vendor=webgl_vendor,
1369
- webgl_renderer=webgl_renderer,
1370
- )
1371
-
1372
-
1373
- def apply_region_fingerprint(profile: Profile, region: str | None) -> Profile:
1374
- """Align locale/timezone to region while keeping UA/device stable within task."""
1375
- region_code = (region or "").strip().upper()
1376
- if not region_code:
1377
- return profile
1378
- # Idempotence matters: pipeline retries may call this helper several times
1379
- # for the same provider region. Re-rolling locale/timezone under the same
1380
- # device id is a fingerprint drift.
1381
- if profile.region == region_code and profile.locale and profile.timezone_id:
1382
- return profile
1383
- locale, language = _pick_locale(region_code)
1384
- tz_offset, tz_label, tz_id = _pick_timezone(region_code)
1385
- profile.locale = locale
1386
- profile.language = language
1387
- profile.timezone_offset_min = tz_offset
1388
- profile.timezone_label = tz_label
1389
- profile.timezone_id = tz_id
1390
- profile.region = region_code
1391
- return profile
1392
-
1393
-
1394
- def apply_proxy_timezone(
1395
- profile: Profile,
1396
- proxy: str | None,
1397
- *,
1398
- geo_country: str | None = None,
1399
- geo_timezone: str | None = None,
1400
- ) -> Profile:
1401
- """Mutate profile locale/timezone from proxy region or geo country.
1402
-
1403
- Priority:
1404
- 1) observed exit-IP country/timezone
1405
- 2) provider region in proxy URL (region-JP / country-US)
1406
- """
1407
- region = (geo_country or "").strip().upper() or proxy_region_code(proxy)
1408
- if not region:
1409
- return profile
1410
- apply_region_fingerprint(profile, region)
1411
- timezone_id = str(geo_timezone or "").strip()
1412
- if timezone_id and profile.timezone_id != timezone_id:
1413
- offset, label, timezone_id = _timezone_parts(timezone_id, region)
1414
- profile.timezone_offset_min = offset
1415
- profile.timezone_label = label
1416
- profile.timezone_id = timezone_id
1417
- return profile
1418
-
1419
-
1420
- def edge_windows_profile(major: int = 146, *, region: str | None = None) -> Profile:
1421
- """Profile matching local successful Edge/Windows packet capture style."""
1422
- region_code = (region or "").strip().upper()
1423
- locale, language = _pick_locale(region_code or "US")
1424
- tz_offset, tz_label, tz_id = _pick_timezone(region_code or "JP")
1425
- full = _chrome_full_version(major)
1426
- hardware_name, hardware = _pick_hardware("Windows")
1427
- (
1428
- resolution,
1429
- cores,
1430
- device_memory,
1431
- max_touch_points,
1432
- platform_version,
1433
- architecture,
1434
- webgl_vendor,
1435
- webgl_renderer,
1436
- ) = _hardware_values(hardware)
1437
- return Profile(
1438
- user_agent=(
1439
- f"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
1440
- f"AppleWebKit/537.36 (KHTML, like Gecko) "
1441
- f"Chrome/{major}.0.0.0 Safari/537.36 Edg/{major}.0.0.0"
1442
- ),
1443
- sec_ch_ua=(
1444
- f'"Not;A=Brand";v="8", "Chromium";v="{major}", '
1445
- f'"Microsoft Edge";v="{major}"'
1446
- ),
1447
- sec_ch_ua_platform='"Windows"',
1448
- locale=locale,
1449
- language=language,
1450
- resolution=resolution,
1451
- cores=cores,
1452
- history_len=_rand_choice(_HISTORY_LENGTHS),
1453
- timezone_offset_min=tz_offset,
1454
- timezone_label=tz_label,
1455
- platform_os="Windows",
1456
- browser="edge",
1457
- chrome_major=major,
1458
- chrome_full_version=full,
1459
- device_memory=device_memory,
1460
- max_touch_points=max_touch_points,
1461
- region=region_code,
1462
- timezone_id=tz_id,
1463
- tls_impersonate=choose_tls_impersonate(
1464
- browser="edge",
1465
- chrome_major=major,
1466
- platform_os="Windows",
1467
- ),
1468
- tls_client_identifier=choose_tls_client_identifier(
1469
- browser="edge",
1470
- browser_major=major,
1471
- ),
1472
- platform_version=platform_version,
1473
- architecture=architecture,
1474
- hardware_profile=hardware_name,
1475
- webgl_vendor=webgl_vendor,
1476
- webgl_renderer=webgl_renderer,
1477
- )
1478
-
1479
-
1480
- def chrome_windows_profile(major: int | None = None, *, region: str | None = None) -> Profile:
1481
- """Chrome/Windows profile using one exact bundled TLS preset per account."""
1482
- return random_profile(
1483
- region=region,
1484
- browser="chrome",
1485
- platform_os="Windows",
1486
- chrome_major=major,
1487
- )
1488
-
1489
-
1490
- def profile_from_user_agent(
1491
- user_agent: str,
1492
- *,
1493
- region: str | None = None,
1494
- hardware_profile: str | None = None,
1495
- audio_seed: str | None = None,
1496
- ) -> Profile:
1497
- """Create a complete runtime profile from an observed browser UA."""
1498
- ua = str(user_agent or "").strip()
1499
- # Chromium's headless launcher may expose this token even when every other
1500
- # runtime field is browser-shaped. A context UA must use the regular token.
1501
- ua = re.sub(r"\bHeadlessChrome/", "Chrome/", ua, flags=re.I)
1502
- firefox = re.search(r"Firefox/(\d+)(?:\.([\d.]+))?", ua, flags=re.I)
1503
- if firefox:
1504
- profile = firefox_windows_profile(
1505
- int(firefox.group(1)),
1506
- region=region,
1507
- hardware_profile=hardware_profile,
1508
- audio_seed=audio_seed,
1509
- )
1510
- profile.user_agent = ua
1511
- full_match = re.search(r"Firefox/([\d.]+)", ua, flags=re.I)
1512
- if full_match:
1513
- profile.chrome_full_version = full_match.group(1)
1514
- seed = profile.audio_seed or secrets.token_hex(4).upper()
1515
- profile.device_name, profile.mac_address = _device_identity(
1516
- profile.platform_os, seed
1517
- )
1518
- return profile
1519
-
1520
- chrome = re.search(r"(?:Chrome|Chromium)/(\d+)(?:\.([\d.]+))?", ua, flags=re.I)
1521
- edge = re.search(r"Edg/(\d+)(?:\.([\d.]+))?", ua, flags=re.I)
1522
- if chrome:
1523
- major = int(chrome.group(1))
1524
- platform_os = "macOS" if "Macintosh" in ua else "Windows"
1525
- browser = "edge" if edge else "chrome"
1526
- profile = random_profile(
1527
- region=region,
1528
- browser=browser,
1529
- platform_os=platform_os,
1530
- chrome_major=major,
1531
- hardware_profile=hardware_profile,
1532
- )
1533
- profile.user_agent = ua
1534
- full_match = re.search(r"(?:Chrome|Chromium)/([\d.]+)", ua, flags=re.I)
1535
- if full_match:
1536
- profile.chrome_full_version = full_match.group(1)
1537
- seed = (
1538
- str(audio_seed or "").strip().upper() or secrets.token_hex(4).upper()
1539
- )
1540
- profile.audio_seed = seed
1541
- profile.audio_mode = "noise"
1542
- profile.media_devices_mode = "noise"
1543
- profile.media_devices_seed = _derived_seed(seed, "media")
1544
- profile.client_rects_mode = "noise"
1545
- profile.client_rects_seed = _derived_seed(seed, "rects")
1546
- profile.speech_voices_mode = "noise"
1547
- profile.speech_voices_seed = _derived_seed(seed, "voices")
1548
- profile.webgpu_mode = "webgl"
1549
- profile.port_scan_protection = True
1550
- profile.device_name, profile.mac_address = _device_identity(
1551
- profile.platform_os, seed
1552
- )
1553
- return profile
1554
- raise ValueError("unsupported browser user agent")
1555
-
1556
-
1557
- def firefox_windows_profile(
1558
- major: int = 150,
1559
- *,
1560
- region: str | None = None,
1561
- hardware_profile: str | None = None,
1562
- audio_seed: str | None = None,
1563
- ) -> Profile:
1564
- """Build a Firefox/Windows profile without Chromium-only Client Hints.
1565
-
1566
- The default ``win_gtx1660`` persona mirrors the supplied 20-core/8-GB/GTX
1567
- 1660-style browser profile. Device name and MAC address are intentionally
1568
- absent: ordinary web content cannot read either value.
1569
- """
1570
- major = max(100, int(major or 150))
1571
- region_code = (region or "").strip().upper()
1572
- locale, language = _pick_locale(region_code)
1573
- tz_offset, tz_label, tz_id = _pick_timezone(region_code)
1574
- hardware_name, hardware = _pick_hardware(
1575
- "Windows", hardware_profile or "win_gtx1660"
1576
- )
1577
- (
1578
- resolution,
1579
- cores,
1580
- device_memory,
1581
- max_touch_points,
1582
- platform_version,
1583
- architecture,
1584
- webgl_vendor,
1585
- webgl_renderer,
1586
- ) = _hardware_values(hardware)
1587
- seed = str(audio_seed or "").strip().upper()
1588
- if not seed:
1589
- seed = secrets.token_hex(4).upper()
1590
- device_name, mac_address = _device_identity("Windows", seed)
1591
- full = f"{major}.0"
1592
- return Profile(
1593
- user_agent=(
1594
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64; "
1595
- f"rv:{full}) Gecko/20100101 Firefox/{full}"
1596
- ),
1597
- sec_ch_ua="",
1598
- sec_ch_ua_platform="",
1599
- locale=locale,
1600
- language=language,
1601
- resolution=resolution,
1602
- cores=cores,
1603
- history_len=_rand_choice(_HISTORY_LENGTHS),
1604
- timezone_offset_min=tz_offset,
1605
- timezone_label=tz_label,
1606
- platform_os="Windows",
1607
- browser="firefox",
1608
- chrome_major=major,
1609
- chrome_full_version=full,
1610
- device_memory=device_memory,
1611
- max_touch_points=max_touch_points,
1612
- region=region_code,
1613
- timezone_id=tz_id,
1614
- tls_impersonate=choose_tls_impersonate(
1615
- browser="firefox",
1616
- chrome_major=major,
1617
- platform_os="Windows",
1618
- ),
1619
- tls_client_identifier=choose_tls_client_identifier(
1620
- browser="firefox", browser_major=major
1621
- ),
1622
- platform_version=platform_version,
1623
- architecture=architecture,
1624
- hardware_profile=hardware_name,
1625
- webgl_vendor=webgl_vendor,
1626
- webgl_renderer=webgl_renderer,
1627
- webrtc_mode="disabled",
1628
- geolocation_mode="ask",
1629
- canvas_mode="real",
1630
- webgl_mode="real",
1631
- audio_mode="noise",
1632
- audio_seed=seed,
1633
- device_name=device_name,
1634
- mac_address=mac_address,
1635
- hardware_acceleration="default",
1636
- )
1637
-
1638
-
1639
- def _full_version_list(profile: Profile) -> str:
1640
- major = str(profile.browser_major)
1641
- full = profile.browser_full_version
1642
- return re.sub(
1643
- rf'v="{re.escape(major)}"',
1644
- f'v="{full}"',
1645
- profile.sec_ch_ua,
1646
- )
1647
-
1648
-
1649
- def profile_headers(profile: Profile, *, high_entropy: bool = False) -> dict[str, str]:
1650
- """Build UA headers while omitting browser-incompatible fields."""
1651
- headers = {
1652
- "user-agent": profile.user_agent,
1653
- "accept-language": profile.locale,
1654
- }
1655
- if profile.sec_ch_ua:
1656
- headers.update(
1657
- {
1658
- "sec-ch-ua": profile.sec_ch_ua,
1659
- "sec-ch-ua-mobile": "?1" if profile.mobile else "?0",
1660
- "sec-ch-ua-platform": profile.sec_ch_ua_platform,
1661
- }
1662
- )
1663
- if high_entropy:
1664
- headers.update(
1665
- {
1666
- "sec-ch-ua-arch": f'"{profile.architecture}"',
1667
- "sec-ch-ua-bitness": f'"{profile.bitness}"',
1668
- "sec-ch-ua-model": '""',
1669
- "sec-ch-ua-full-version": f'"{profile.browser_full_version}"',
1670
- "sec-ch-ua-full-version-list": _full_version_list(profile),
1671
- "sec-ch-ua-platform-version": f'"{profile.platform_version}"',
1672
- }
1673
- )
1674
- return headers
1675
-
1676
-
1677
- @dataclass(frozen=True, slots=True)
1678
- class ProfileValidation:
1679
- errors: tuple[str, ...] = ()
1680
- warnings: tuple[str, ...] = ()
1681
-
1682
- @property
1683
- def valid(self) -> bool:
1684
- return not self.errors
1685
-
1686
-
1687
- def validate_profile(profile: Profile) -> ProfileValidation:
1688
- """Detect UA/Client-Hint/TLS/hardware contradictions before launch."""
1689
- errors: list[str] = []
1690
- warnings: list[str] = []
1691
- browser = profile.browser.lower()
1692
- major = profile.browser_major
1693
-
1694
- if browser == "firefox":
1695
- if f"Firefox/{major}." not in profile.user_agent:
1696
- errors.append("Firefox UA major does not match browser_major")
1697
- if profile.sec_ch_ua or profile.sec_ch_ua_platform:
1698
- errors.append("Firefox profile must not emit Chromium sec-ch-ua headers")
1699
- if not profile.tls_impersonate.startswith("firefox"):
1700
- errors.append("Firefox UA is paired with a non-Firefox curl TLS preset")
1701
- if not profile.tls_client_identifier.startswith("firefox_"):
1702
- errors.append("Firefox UA is paired with a non-Firefox tls-client preset")
1703
- elif browser in {"chrome", "edge"}:
1704
- if f"Chrome/{major}." not in profile.user_agent:
1705
- errors.append("Chromium UA major does not match browser_major")
1706
- if f'"Chromium";v="{major}"' not in profile.sec_ch_ua:
1707
- errors.append("Chromium sec-ch-ua major does not match browser_major")
1708
- expected_platform = f'"{profile.platform_os}"'
1709
- if profile.sec_ch_ua_platform != expected_platform:
1710
- errors.append("sec-ch-ua-platform does not match platform_os")
1711
- if not profile.browser_full_version.startswith(f"{major}."):
1712
- errors.append("Chromium full version does not match browser_major")
1713
-
1714
- if not re.fullmatch(r"[1-9]\d{2,4}x[1-9]\d{2,4}", profile.resolution):
1715
- errors.append("resolution must be WIDTHxHEIGHT")
1716
- if profile.cores <= 0 or profile.device_memory <= 0:
1717
- errors.append("hardware concurrency and memory must be positive")
1718
- persona = _HARDWARE_PERSONAS.get(profile.hardware_profile)
1719
- if persona is None:
1720
- errors.append("unknown hardware persona")
1721
- elif persona["platform"] != profile.platform_os:
1722
- errors.append("hardware persona platform does not match UA platform")
1723
- if persona:
1724
- if profile.resolution not in persona["resolutions"]:
1725
- errors.append("resolution does not belong to hardware persona")
1726
- if profile.cores not in persona["cores"]:
1727
- errors.append("core count does not belong to hardware persona")
1728
- if profile.device_memory not in persona["memory"]:
1729
- errors.append("memory does not belong to hardware persona")
1730
- if profile.max_touch_points not in persona["touch"]:
1731
- errors.append("touch points do not belong to hardware persona")
1732
- if profile.platform_version not in persona["platform_versions"]:
1733
- errors.append("platform version does not belong to hardware persona")
1734
- if profile.architecture != persona["architecture"]:
1735
- errors.append("architecture does not belong to hardware persona")
1736
- if (profile.webgl_vendor, profile.webgl_renderer) not in persona["webgl"]:
1737
- errors.append("WebGL renderer does not belong to hardware persona")
1738
-
1739
- region = profile.region.upper()
1740
- allowed_locales = _LOCALES_BY_REGION.get(region)
1741
- if allowed_locales and (profile.locale, profile.language) not in allowed_locales:
1742
- errors.append("locale/language pair does not match region")
1743
- allowed_timezones = _IANA_BY_REGION.get(region)
1744
- if allowed_timezones and profile.timezone_id not in allowed_timezones:
1745
- errors.append("timezone does not match region")
1746
- expected_tls = choose_tls_impersonate(
1747
- browser=profile.browser,
1748
- chrome_major=profile.browser_major,
1749
- platform_os=profile.platform_os,
1750
- )
1751
- if profile.tls_impersonate != expected_tls:
1752
- errors.append("curl TLS preset does not match the supported browser mapping")
1753
-
1754
- tls_match = re.search(r"(\d+)", profile.tls_impersonate)
1755
- if tls_match and abs(int(tls_match.group(1)) - major) > 0:
1756
- warnings.append(
1757
- f"curl TLS preset {profile.tls_impersonate} is a nearest-version fallback "
1758
- f"for {browser}/{major}"
1759
- )
1760
- return ProfileValidation(tuple(errors), tuple(warnings))
1761
-
1762
-
1763
- FINGERPRINT_PROFILE_SCHEMA_VERSION = 2
1764
-
1765
-
1766
- def profile_to_json(profile: Profile) -> str:
1767
- """Serialize a complete, versioned account fingerprint snapshot."""
1768
- payload = {
1769
- "version": FINGERPRINT_PROFILE_SCHEMA_VERSION,
1770
- "profile": asdict(profile),
1771
- }
1772
- return json.dumps(
1773
- payload,
1774
- ensure_ascii=False,
1775
- separators=(",", ":"),
1776
- sort_keys=True,
1777
- )
1778
-
1779
-
1780
- def profile_from_json(value: object) -> Profile | None:
1781
- """Restore and validate a stored fingerprint snapshot.
1782
-
1783
- Unknown future fields are ignored so additive schema changes remain
1784
- backward compatible. Invalid or truncated snapshots raise ``ValueError``
1785
- and callers can generate a new legacy-account companion profile.
1786
- """
1787
- if value in (None, "", b""):
1788
- return None
1789
- try:
1790
- payload = json.loads(value) if isinstance(value, (str, bytes, bytearray)) else value
1791
- except (TypeError, ValueError, json.JSONDecodeError) as exc:
1792
- raise ValueError("invalid fingerprint profile JSON") from exc
1793
- if not isinstance(payload, dict):
1794
- raise ValueError("fingerprint profile snapshot must be an object")
1795
- raw = payload.get("profile", payload)
1796
- if not isinstance(raw, dict):
1797
- raise ValueError("fingerprint profile payload must be an object")
1798
- allowed = {item.name for item in fields(Profile)}
1799
- kwargs = {key: raw[key] for key in allowed if key in raw}
1800
- try:
1801
- profile = Profile(**kwargs)
1802
- except (TypeError, ValueError) as exc:
1803
- raise ValueError("fingerprint profile fields are incomplete") from exc
1804
- validation = validate_profile(profile)
1805
- if not validation.valid:
1806
- raise ValueError(
1807
- "stored fingerprint profile mismatch: " + "; ".join(validation.errors)
1808
- )
1809
- return profile
1810
-
1811
-
1812
- def profile_supports_protocol_transport(profile: Profile) -> bool:
1813
- """Return whether the stored UA has an exact installed TLS persona."""
1814
- identifier = str(profile.tls_client_identifier or "").lower()
1815
- browser = str(profile.browser or "").lower()
1816
- if browser == "chrome":
1817
- expected = "chrome_"
1818
- elif browser == "firefox":
1819
- expected = "firefox_"
1820
- else:
1821
- return False
1822
- match = re.search(r"(\d+)", identifier)
1823
- return bool(
1824
- identifier.startswith(expected)
1825
- and match
1826
- and int(match.group(1)) == int(profile.browser_major)
1827
- )
1828
-
1829
-
1830
- def profile_summary(profile: Profile) -> str:
1831
- """Short one-line fingerprint for logs."""
1832
- tls = (
1833
- getattr(profile, "tls_client_identifier", "")
1834
- or getattr(profile, "tls_impersonate", "")
1835
- or ""
1836
- )
1837
- return (
1838
- f"{profile.browser}/{profile.chrome_full_version} {profile.platform_os} · "
1839
- f"{profile.language} · tz={profile.timezone_offset_min}({profile.timezone_label}) · "
1840
- f"{profile.resolution} · {profile.cores}C/{profile.device_memory:g}GB · "
1841
- f"hist={profile.history_len} · touch={profile.max_touch_points} · "
1842
- f"hw={profile.hardware_profile}"
1843
- + (f" · tls={tls}" if tls else "")
1844
- + (f" · region={profile.region}" if profile.region else "")
1845
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
standalone_flow.py DELETED
@@ -1,529 +0,0 @@
1
- """Standalone HTTP flow used by the direct-bind service.
2
-
3
- No imports from the parent project, no project database, and no calls to port 5550.
4
- """
5
- from __future__ import annotations
6
-
7
- import base64
8
- import json
9
- import re
10
- import threading
11
- import time
12
- from pathlib import Path
13
- from typing import Any, Callable
14
- from urllib.request import Request, urlopen
15
-
16
- from standalone_core.card_payment import CardPaymentConfig, run_card_payment
17
- from standalone_core.fingerprint_store import (
18
- extractor_profile,
19
- get_account_fingerprint,
20
- get_account_fingerprints,
21
- )
22
- from standalone_core.ph_shortlink_extractor import (
23
- Mode8Config,
24
- Mode8Extractor,
25
- normalize_proxy,
26
- )
27
-
28
- ROOT = Path(__file__).resolve().parent
29
- CONFIG_PATH = ROOT / "standalone_config.json"
30
- _CONFIG_LOCK = threading.RLock()
31
- _CONFIG_CACHE: dict[str, Any] = {}
32
- _CONFIG_CACHE_MTIME_NS = -1
33
- _PREFLIGHT_LOCK = threading.RLock()
34
- _PREFLIGHT_CACHE: dict[str, tuple[float, str, dict[str, Any]]] = {}
35
-
36
-
37
- def _text(value: Any) -> str:
38
- return str(value or "").strip()
39
-
40
-
41
- def _load_config() -> dict[str, Any]:
42
- global _CONFIG_CACHE, _CONFIG_CACHE_MTIME_NS
43
- if not CONFIG_PATH.exists():
44
- return {}
45
- mtime_ns = CONFIG_PATH.stat().st_mtime_ns
46
- with _CONFIG_LOCK:
47
- if _CONFIG_CACHE and mtime_ns == _CONFIG_CACHE_MTIME_NS:
48
- return dict(_CONFIG_CACHE)
49
- data = json.loads(CONFIG_PATH.read_text(encoding="utf-8-sig") or "{}")
50
- if not isinstance(data, dict):
51
- raise ValueError("standalone_config.json must contain an object")
52
- _CONFIG_CACHE = data
53
- _CONFIG_CACHE_MTIME_NS = mtime_ns
54
- return dict(data)
55
-
56
-
57
- def _preflight_key(ctx: dict[str, Any]) -> str:
58
- return f"{ctx['account_id']}\n{ctx['promo_pool'][0]}"
59
-
60
-
61
- def _remember_preflight(
62
- ctx: dict[str, Any], result: dict[str, Any], config: dict[str, Any]
63
- ) -> None:
64
- ttl = max(30, min(900, int(config.get("preflight_cache_ttl") or 600)))
65
- key = _preflight_key(ctx)
66
- now = time.monotonic()
67
- with _PREFLIGHT_LOCK:
68
- _PREFLIGHT_CACHE[key] = (now + ttl, ctx["access_token"], dict(result))
69
- expired = [item for item, value in _PREFLIGHT_CACHE.items() if value[0] <= now]
70
- for item in expired:
71
- _PREFLIGHT_CACHE.pop(item, None)
72
-
73
-
74
- def _take_preflight(ctx: dict[str, Any]) -> dict[str, Any] | None:
75
- key = _preflight_key(ctx)
76
- with _PREFLIGHT_LOCK:
77
- cached = _PREFLIGHT_CACHE.pop(key, None)
78
- if not cached or cached[0] <= time.monotonic() or cached[1] != ctx["access_token"]:
79
- return None
80
- return dict(cached[2])
81
-
82
-
83
- def _decode_claims(token: str) -> dict[str, Any]:
84
- parts = _text(token).split(".")
85
- if len(parts) < 2:
86
- raise ValueError("AT format is invalid")
87
- raw = parts[1] + "=" * (-len(parts[1]) % 4)
88
- try:
89
- payload = json.loads(base64.urlsafe_b64decode(raw.encode("ascii")))
90
- except Exception as exc:
91
- raise ValueError("AT payload is invalid") from exc
92
- if not isinstance(payload, dict):
93
- raise ValueError("AT payload is invalid")
94
- return payload
95
-
96
-
97
- def _account_context(token: str) -> tuple[str, str]:
98
- claims = _decode_claims(token)
99
- auth = claims.get("https://api.openai.com/auth") or {}
100
- profile = claims.get("https://api.openai.com/profile") or {}
101
- account_id = ""
102
- if isinstance(auth, dict):
103
- account_id = _text(auth.get("chatgpt_account_id") or auth.get("account_id"))
104
- account_id = account_id or _text(claims.get("chatgpt_account_id") or claims.get("account_id"))
105
- email = _text(profile.get("email") if isinstance(profile, dict) else "") or _text(claims.get("email"))
106
- if not account_id:
107
- raise ValueError("AT does not contain an account id")
108
- return account_id, email
109
-
110
-
111
- def _pool(value: Any) -> list[str]:
112
- if isinstance(value, str):
113
- values = re.split(r"[\r\n,;]+", value)
114
- elif isinstance(value, list):
115
- values = value
116
- else:
117
- values = []
118
- result: list[str] = []
119
- for item in values:
120
- raw = _text(item)
121
- if not raw:
122
- continue
123
- proxy = normalize_proxy(raw)
124
- if not proxy:
125
- continue
126
- scheme, endpoint = proxy.split("://", 1)
127
- fallback_schemes = {
128
- "http": ("http", "https"),
129
- "https": ("https", "http"),
130
- "socks4": ("socks4", "socks4a"),
131
- "socks4a": ("socks4a", "socks4"),
132
- "socks5": ("socks5", "socks5h"),
133
- "socks5h": ("socks5h", "socks5"),
134
- }.get(scheme.lower(), (scheme.lower(),))
135
- for candidate_scheme in fallback_schemes:
136
- candidate = f"{candidate_scheme}://{endpoint}"
137
- if candidate not in result:
138
- result.append(candidate)
139
- return result[:500]
140
-
141
-
142
- def _is_proxy_transport_error(value: Any) -> bool:
143
- text = _text(value).lower()
144
- if any(marker in text for marker in ("card_declined", "incorrect_cvc", "expired_card")):
145
- return False
146
- return any(
147
- marker in text
148
- for marker in (
149
- "proxy", "curl: (5)", "curl: (6)", "curl: (7)", "curl: (28)",
150
- "curl: (35)", "curl: (56)", "connect", "connection", "timed out",
151
- "timeout", "tls", "ssl", "reset", "remote end closed", "failed to perform",
152
- )
153
- )
154
-
155
-
156
- def _billing_payload(value: Any, *, required: bool) -> dict[str, str]:
157
- source = value if isinstance(value, dict) else {}
158
- fields = {
159
- key: _text(source.get(key))[:200]
160
- for key in (
161
- "name", "email", "phone", "line1", "line2", "city",
162
- "state", "postal_code", "country",
163
- )
164
- }
165
- fields["country"] = fields["country"].upper()
166
- fields["state"] = fields["state"].upper()
167
- fields["postal_code"] = fields["postal_code"].upper()
168
- if not required:
169
- return {key: item for key, item in fields.items() if item}
170
- missing = [
171
- label
172
- for key, label in (
173
- ("name", "持卡人姓名"),
174
- ("line1", "账单地址"),
175
- ("city", "城市"),
176
- ("postal_code", "邮编"),
177
- ("country", "国家代码"),
178
- )
179
- if not fields[key]
180
- ]
181
- if missing:
182
- raise ValueError("账单地址缺少:" + "、".join(missing))
183
- if not re.fullmatch(r"[A-Z]{2}", fields["country"]):
184
- raise ValueError("账单国家必须填写两位国家代码")
185
- if fields["country"] == "US":
186
- if not fields["state"]:
187
- raise ValueError("美国账单地址缺少州代码")
188
- if not re.fullmatch(r"\d{5}(?:-\d{4})?", fields["postal_code"]):
189
- raise ValueError("美国账单地址 ZIP 格式错误")
190
- return {key: item for key, item in fields.items() if item}
191
-
192
-
193
- def validate_payload(payload: dict[str, Any], *, require_payment_method: bool = True) -> dict[str, Any]:
194
- token = _text(payload.get("access_token"))
195
- if not token:
196
- raise ValueError("missing AT")
197
- account_id, email = _account_context(token)
198
- bind_pool = _pool(payload.get("bind_proxy_pool"))
199
- promo_pool = _pool(payload.get("promo_proxy_pool"))
200
- mode = _text(payload.get("flow_mode") or "full").lower()
201
- if mode not in {"full", "bind_only", "link_pay", "link_only"}:
202
- raise ValueError("unsupported flow mode")
203
- if mode == "link_only":
204
- if not promo_pool:
205
- raise ValueError("promo proxy pool is required")
206
- elif not bind_pool or not promo_pool:
207
- raise ValueError("both proxy pools are required")
208
- needs_payment_method = require_payment_method and mode != "link_only"
209
- payment_method_id = _text(payload.get("payment_method_id"))
210
- if needs_payment_method and not re.fullmatch(r"pm_[A-Za-z0-9_-]+", payment_method_id):
211
- raise ValueError("missing or invalid PaymentMethod")
212
- return {
213
- "access_token": token,
214
- "account_id": account_id,
215
- "email": email,
216
- "bind_pool": bind_pool,
217
- "promo_pool": promo_pool,
218
- "flow_mode": mode,
219
- "payment_method_id": payment_method_id,
220
- "card_last4": re.sub(r"\D", "", _text(payload.get("card_last4")))[-4:],
221
- "billing": _billing_payload(
222
- payload.get("billing"), required=needs_payment_method
223
- ),
224
- }
225
-
226
-
227
- def _attach_fingerprint(
228
- ctx: dict[str, Any],
229
- config: dict[str, Any],
230
- logger: Callable[[str], None],
231
- ) -> None:
232
- if ctx.get("fingerprint_profile") and ctx.get("device_id"):
233
- return
234
- logger("FLOW_STEP:fingerprint:start:正在加载账号固定指纹")
235
- region = _text(config.get("fingerprint_region") or "US").upper()
236
- profile, device_id = get_account_fingerprint(
237
- ctx["account_id"],
238
- region=region,
239
- proxy=ctx["bind_pool"][0] if ctx["bind_pool"] else "",
240
- )
241
- adapted = extractor_profile(profile, device_id)
242
- ctx["fingerprint_profile"] = adapted
243
- ctx["device_id"] = device_id
244
- ctx["fingerprint_summary"] = (
245
- f"{adapted.get('summary', '')} · id={adapted.get('fingerprint_id', '')}"
246
- ).strip(" ·")
247
- logger(f"账号指纹已加载:{ctx['fingerprint_summary']}")
248
- logger(
249
- f"FLOW_STEP:fingerprint:done:指纹 {adapted.get('fingerprint_id', '')} / TLS {adapted.get('tls_impersonate', '')}"
250
- )
251
-
252
-
253
- def _fingerprint_result(
254
- account_id: str, email: str, profile: Any, device_id: str
255
- ) -> dict[str, Any]:
256
- adapted = extractor_profile(profile, device_id)
257
- summary = (
258
- f"{adapted.get('summary', '')} · id={adapted.get('fingerprint_id', '')}"
259
- ).strip(" ·")
260
- return {
261
- "ok": True,
262
- "email": email,
263
- "account_id": account_id,
264
- "fingerprint": summary,
265
- "fingerprint_id": adapted.get("fingerprint_id", ""),
266
- "browser": f"{profile.browser}/{profile.browser_full_version}",
267
- "platform": profile.platform_os,
268
- "tls": profile.tls_impersonate,
269
- "language": profile.language,
270
- "region": profile.region,
271
- "timezone": profile.timezone_id,
272
- }
273
-
274
-
275
- def allocate_fingerprint(payload: dict[str, Any]) -> dict[str, Any]:
276
- """Allocate the account's sticky profile without making an upstream call."""
277
- token = _text(payload.get("access_token"))
278
- if not token:
279
- raise ValueError("missing AT")
280
- account_id, email = _account_context(token)
281
- config = _load_config()
282
- region = _text(config.get("fingerprint_region") or "US").upper()
283
- profile, device_id = get_account_fingerprint(account_id, region=region)
284
- return _fingerprint_result(account_id, email, profile, device_id)
285
-
286
-
287
- def allocate_fingerprints(payload: dict[str, Any]) -> dict[str, Any]:
288
- """Allocate many account profiles with one JSON-store transaction."""
289
- source = payload.get("accounts")
290
- if not isinstance(source, list) or not source:
291
- raise ValueError("accounts must be a non-empty list")
292
- if len(source) > 500:
293
- raise ValueError("fingerprint batch cannot exceed 500 accounts")
294
- config = _load_config()
295
- region = _text(config.get("fingerprint_region") or "US").upper()
296
- prepared: list[dict[str, str]] = []
297
- metadata: list[tuple[str, str, str]] = []
298
- output: list[dict[str, Any] | None] = [None] * len(source)
299
- for index, item in enumerate(source):
300
- client_id = _text(item.get("client_id"))[:100] if isinstance(item, dict) else ""
301
- try:
302
- if not isinstance(item, dict):
303
- raise ValueError("account item must be an object")
304
- token = _text(item.get("access_token"))
305
- if not token:
306
- raise ValueError("missing AT")
307
- account_id, email = _account_context(token)
308
- prepared.append({"account_id": account_id, "region": region})
309
- metadata.append((client_id, account_id, email))
310
- except Exception as exc: # keep one malformed row from blocking the batch
311
- output[index] = {"ok": False, "client_id": client_id, "error": str(exc)}
312
- profiles = get_account_fingerprints(prepared) if prepared else []
313
- valid_cursor = 0
314
- for index, item in enumerate(output):
315
- if item is not None:
316
- continue
317
- client_id, account_id, email = metadata[valid_cursor]
318
- profile, device_id = profiles[valid_cursor]
319
- output[index] = {
320
- **_fingerprint_result(account_id, email, profile, device_id),
321
- "client_id": client_id,
322
- }
323
- valid_cursor += 1
324
- return {"ok": True, "count": len(output), "items": output}
325
-
326
-
327
- def fetch_billing_address(payload: dict[str, Any]) -> dict[str, Any]:
328
- """Fetch and normalize one billing address from the configured API."""
329
- config = _load_config()
330
- endpoint = _text(config.get("address_generator") or config.get("test_address_generator")) or (
331
- "https://addressgen.top/api/v1/address?country_code=us&area_code=DE"
332
- )
333
- if not endpoint.startswith("https://addressgen.top/api/v1/address?"):
334
- raise ValueError("地址接口配置错误")
335
- request = Request(
336
- endpoint,
337
- headers={"Accept": "application/json", "User-Agent": "direct-bind-address/1.0"},
338
- )
339
- with urlopen(request, timeout=15) as response: # noqa: S310 - fixed allowlisted host
340
- raw = json.loads(response.read().decode("utf-8"))
341
- data = raw.get("data") if isinstance(raw, dict) else None
342
- address = data.get("address") if isinstance(data, dict) else None
343
- if not isinstance(data, dict) or not isinstance(address, dict):
344
- raise RuntimeError("测试地址接口返回字段不完整")
345
- billing = {
346
- "name": f"{_text(data.get('firstname'))} {_text(data.get('lastname'))}".strip(),
347
- "line1": _text(address.get("street")),
348
- "line2": "",
349
- "city": _text(address.get("city")),
350
- "state": _text(address.get("area_code")).upper(),
351
- "postal_code": _text(address.get("zipcode")),
352
- "country": _text(address.get("country_code") or "US").upper(),
353
- }
354
- validated = _billing_payload(billing, required=True)
355
- return {"ok": True, "source": "address_api", "billing": validated}
356
-
357
-
358
- def _extract_checkout(ctx: dict[str, Any], config: dict[str, Any], logger: Callable[[str], None]) -> dict[str, Any]:
359
- country = _text(config.get("country") or "PH").upper()
360
- currency = _text(config.get("currency") or "PHP").upper()
361
- # Checkout-link extraction is isolated to proxy pool 2. Proxy pool 1 is
362
- # reserved for SetupIntent card binding and payment confirmation.
363
- candidates = list(ctx["promo_pool"][:8])
364
- last_error: Exception | None = None
365
- for index, proxy in enumerate(candidates, start=1):
366
- logger(f"提链代理尝试 {index}/{len(candidates)}")
367
- try:
368
- result = Mode8Extractor(
369
- Mode8Config(
370
- token=ctx["access_token"],
371
- country=country,
372
- currency=currency,
373
- promo_campaign=_text(config.get("promo_campaign") or "plus-1-month-free"),
374
- require_oaics=True,
375
- reject_nonzero=bool(config.get("reject_nonzero", True)),
376
- timeout=max(30, min(1800, int(config.get("timeout") or 900))),
377
- diagnose_coupon=bool(config.get("coupon_diagnostic", False)),
378
- fingerprint_profile=dict(ctx.get("fingerprint_profile") or {}),
379
- device_id=_text(ctx.get("device_id")),
380
- ),
381
- logger=logger,
382
- ).run(proxy, proxy)
383
- checkout_id = _text(result.get("checkout_id"))
384
- key = _text(result.get("_publishable_key"))
385
- if not result.get("ok") or not checkout_id.startswith("oaics_") or not key.startswith("pk_"):
386
- raise RuntimeError("checkout extraction did not return an oaics id and publishable key")
387
- return result
388
- except Exception as exc: # noqa: BLE001
389
- last_error = exc
390
- if index >= len(candidates) or not _is_proxy_transport_error(exc):
391
- raise
392
- logger(f"提链代理连接失败,自动切换下一个候选:{exc}")
393
- raise RuntimeError(f"提链代理池已耗尽:{last_error}")
394
-
395
-
396
- def preflight(payload: dict[str, Any], logger: Callable[[str], None] = lambda _message: None) -> dict[str, Any]:
397
- ctx = validate_payload(payload, require_payment_method=False)
398
- config = _load_config()
399
- _attach_fingerprint(ctx, config, logger)
400
- result = _extract_checkout(ctx, config, logger)
401
- _remember_preflight(ctx, result, config)
402
- fingerprint = dict(ctx.get("fingerprint_profile") or {})
403
- return {
404
- "ok": True,
405
- "publishable_key": _text(result.get("_publishable_key")),
406
- "checkout_id": _text(result.get("checkout_id")),
407
- "processor_entity": _text(result.get("processor_entity")),
408
- "country": _text(result.get("country") or config.get("country") or "PH"),
409
- "currency": _text(result.get("currency") or config.get("currency") or "PHP"),
410
- "amount": _text(result.get("amount") or "unknown"),
411
- "link": _text(result.get("url") or result.get("link")),
412
- "fingerprint": _text(ctx.get("fingerprint_summary")),
413
- "fingerprint_id": _text(fingerprint.get("fingerprint_id")),
414
- "fingerprint_tls": _text(fingerprint.get("tls_impersonate")),
415
- "fingerprint_region": _text(fingerprint.get("region")),
416
- "fingerprint_timezone": _text(fingerprint.get("timezone")),
417
- }
418
-
419
-
420
- def run_flow(payload: dict[str, Any], logger: Callable[[str], None] = lambda _message: None) -> dict[str, Any]:
421
- ctx = validate_payload(payload, require_payment_method=True)
422
- config = _load_config()
423
- _attach_fingerprint(ctx, config, logger)
424
- first = _take_preflight(ctx)
425
- if first is None:
426
- logger("FLOW_STEP:first_link:start:正在执行首次提链")
427
- first = _extract_checkout(ctx, config, logger)
428
- else:
429
- logger("FLOW_STEP:first_link:start:正在复用卡片预检已完成的首次提链")
430
- logger(
431
- f"FLOW_STEP:first_link:done:首次提链完成 {_text(first.get('checkout_id'))[:18]}"
432
- )
433
- if ctx["flow_mode"] == "link_only":
434
- return {
435
- "ok": True,
436
- "email": ctx["email"],
437
- "payment_flow": "standalone-http-link-only",
438
- "flow_complete": True,
439
- "flow_steps": ["checkout extraction"],
440
- "checkout_id": _text(first.get("checkout_id")),
441
- "processor_entity": _text(first.get("processor_entity")),
442
- "checkout_link": _text(first.get("url") or first.get("link")),
443
- "fingerprint": _text(ctx.get("fingerprint_summary")),
444
- }
445
- timeout = max(30, min(1800, int(config.get("timeout") or 900)))
446
- country = _text(config.get("country") or "PH").upper()
447
- currency = _text(config.get("currency") or "PHP").upper()
448
- billing = dict(config.get("billing") or {})
449
- billing.update(ctx.get("billing") or {})
450
- if ctx["email"] and not _text(billing.get("email")):
451
- billing["email"] = ctx["email"]
452
-
453
- def refresh_checkout() -> dict[str, Any]:
454
- logger("FLOW_STEP:second_link:start:绑卡后正在重新提链")
455
- refreshed = _extract_checkout(ctx, config, logger)
456
- logger(
457
- f"FLOW_STEP:second_link:done:二次提链完成 {_text(refreshed.get('checkout_id'))[:18]}"
458
- )
459
- return refreshed
460
-
461
- bind_only = ctx["flow_mode"] == "bind_only"
462
- bind_candidates = list(ctx["bind_pool"][:8])
463
- result: dict[str, Any] | None = None
464
- last_bind_error: Exception | None = None
465
- for index, bind_proxy in enumerate(bind_candidates, start=1):
466
- logger(f"绑卡/支付代理尝试 {index}/{len(bind_candidates)}")
467
- try:
468
- result = run_card_payment(
469
- CardPaymentConfig(
470
- token=ctx["access_token"],
471
- account_id=ctx["account_id"],
472
- country=country,
473
- currency=currency,
474
- promo_campaign="",
475
- billing=billing,
476
- payment_method_id=ctx["payment_method_id"],
477
- card_last4=ctx["card_last4"],
478
- flow_mode=ctx["flow_mode"],
479
- device_id=_text(ctx.get("device_id")),
480
- fingerprint_profile=dict(ctx.get("fingerprint_profile") or {}),
481
- locale=_text((ctx.get("fingerprint_profile") or {}).get("oai_language")) or "en-US",
482
- timezone=_text((ctx.get("fingerprint_profile") or {}).get("timezone")) or "Asia/Manila",
483
- timeout=timeout,
484
- checkout_id=_text(first.get("checkout_id")),
485
- processor_entity=_text(first.get("processor_entity")),
486
- publishable_key=_text(first.get("_publishable_key")),
487
- bind_country=_text(config.get("bind_country") or "US").upper(),
488
- bind_currency=_text(config.get("bind_currency") or "USD").upper(),
489
- strong_bind_direct=True,
490
- stop_after_bind=bind_only,
491
- fast_verify=bool(config.get("fast_verify", True)),
492
- ),
493
- proxy=bind_proxy,
494
- logger=logger,
495
- refresh_checkout=None if bind_only else refresh_checkout,
496
- )
497
- break
498
- except Exception as exc: # noqa: BLE001
499
- last_bind_error = exc
500
- if index >= len(bind_candidates) or not _is_proxy_transport_error(exc):
501
- raise
502
- logger(f"绑卡/支付代理连接失败,自动切换下一个候选:{exc}")
503
- if result is None:
504
- raise RuntimeError(f"绑卡/支付代理池已耗尽:{last_bind_error}")
505
- processor = _text(result.get("processor_entity"))
506
- checkout_id = _text(result.get("checkout_id"))
507
- link = _text(first.get("url") or first.get("link")) if bind_only else (
508
- f"https://chatgpt.com/checkout/{processor}/{checkout_id}" if processor and checkout_id else ""
509
- )
510
- return {
511
- "ok": bool(result.get("ok")),
512
- "email": ctx["email"],
513
- "payment_flow": "standalone-http-bind" if bind_only else "standalone-http-full",
514
- "flow_complete": not bind_only,
515
- "flow_steps": [
516
- "checkout extraction",
517
- "HTTP SetupIntent confirmation",
518
- *( [] if bind_only else ["checkout refresh", "HTTP payment confirmation"] ),
519
- ],
520
- "checkout_id": checkout_id,
521
- "processor_entity": processor,
522
- "checkout_link": link,
523
- "card_last4": _text(result.get("card_last4") or ctx["card_last4"]),
524
- "setup_status": _text(result.get("setup_status")),
525
- "verify_status": result.get("verify_status", 0),
526
- "subscription_status": result.get("subscription_status", 0),
527
- "subscription_plan": _text(result.get("subscription_plan")),
528
- "fingerprint": _text(ctx.get("fingerprint_summary")),
529
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
standalone_protocol_pay.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import base64
3
+ import importlib.util
4
+ import json
5
+ import sys
6
+ import uuid
7
+ from typing import Any
8
+
9
+
10
+ def protocol_runtime_missing() -> list[str]:
11
+ missing=[]
12
+ for name in ("stripe_checkout","provider_checkout","ph_short_extractor"):
13
+ if importlib.util.find_spec(name) is None:missing.append(name)
14
+ try:
15
+ import app as runtime_app
16
+ if not callable(getattr(runtime_app,"sentinel_headers",None)):missing.append("app.sentinel_headers")
17
+ except Exception:missing.append("app.sentinel_headers")
18
+ return missing
19
+
20
+ RUNTIME_MISSING=protocol_runtime_missing()
21
+ protocol=None
22
+ if not RUNTIME_MISSING:
23
+ import ph_checkout_protocol as protocol
24
+
25
+ UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"
26
+ def emit(message:str,level:str="info",phase:str="")->None:print(json.dumps({"type":"log","level":level,"message":message,"phase":phase},ensure_ascii=True),flush=True)
27
+ def saved_methods(snapshot:dict[str,Any])->list[str]:
28
+ proxy=protocol.normalize_proxy(str(snapshot.get("proxy") or snapshot.get("checkout_proxy") or ""));http=protocol.build_identity_http(proxy,str(snapshot.get("user_agent") or UA));did=str(snapshot.get("checkout_device_id") or uuid.uuid4());protocol.install_cookies(http,dict(snapshot.get("session_cookies") or {}),did);aid=str(snapshot.get("chatgpt_account_id") or "")
29
+ headers={"Authorization":f"Bearer {str(snapshot.get('access_token') or '')}","ChatGPT-Account-Id":aid,"OAI-Device-Id":did,"User-Agent":str(snapshot.get("user_agent") or UA),"Accept":"application/json","Origin":"https://chatgpt.com","Referer":"https://chatgpt.com/"}
30
+ r=http.get("https://chatgpt.com/backend-api/payments/payment_methods",params={"account_id":aid},headers=headers,timeout=45)
31
+ if r.status_code in {401,403}:raise RuntimeError(f"AT_INVALID_OR_EXPIRED: HTTP {r.status_code}")
32
+ if r.status_code!=200:raise RuntimeError(f"PAYMENT_METHOD_QUERY_FAILED: HTTP {r.status_code}")
33
+ try:b=r.json()
34
+ except Exception as exc:raise RuntimeError("PAYMENT_METHOD_QUERY_NON_JSON") from exc
35
+ items=b if isinstance(b,list) else ((b.get("data") or b.get("payment_methods") or []) if isinstance(b,dict) else [])
36
+ return [str(x.get("id") or "") for x in items if isinstance(x,dict) and str(x.get("id") or "").startswith("pm_")]
37
+ def prepare(snapshot:dict[str,Any],proxies:list[str])->dict[str,Any]:
38
+ last="";snapshot.setdefault("user_agent",UA)
39
+ requested_method=str(snapshot.get("saved_payment_method_id") or "").strip()
40
+ if requested_method and not requested_method.startswith("pm_"):raise ValueError("INVALID_PAYMENT_METHOD")
41
+ for index,candidate in enumerate(proxies[:3],1):
42
+ a=dict(snapshot);a["proxy"]=candidate;a["checkout_proxy"]=candidate
43
+ if not (bool(snapshot.get("preserve_checkout_identity")) and index==1):a["checkout_device_id"]=str(uuid.uuid4());a["checkout_chatgpt_session_id"]=""
44
+ else:emit(f"Reusing original Checkout identity: {str(snapshot.get('context_source') or 'context_store')}",phase="validate")
45
+ try:
46
+ emit(f"Preparing saved card route {index}/{min(3,len(proxies))}",phase="validate");methods=saved_methods(a)
47
+ if not methods:raise RuntimeError("NO_SAVED_PAYMENT_METHOD: bind a card first")
48
+ selected_method=requested_method or methods[0]
49
+ if selected_method not in methods:raise RuntimeError("SAVED_PAYMENT_METHOD_ACCOUNT_MISMATCH: selected card is not attached to this account")
50
+ proxy=protocol.normalize_proxy(candidate);http=protocol.build_identity_http(proxy,str(a.get("user_agent") or UA));did=str(a.get("checkout_device_id") or uuid.uuid4());protocol.install_cookies(http,dict(a.get("session_cookies") or {}),did)
51
+ processor=str(a.get("processor_entity") or "openai_llc");session_id=str(a.get("checkout_session_id") or "")
52
+ state=protocol.resolve_oaics_checkout(http,a,processor,session_id,did);pk=str(state.get("publishable_key") or "");amount,currency=protocol.oaics_total(state)
53
+ stripe=protocol.build_stripe_http(proxy,str(a.get("user_agent") or UA));ctx=protocol.fetch_deferred_elements(stripe,state,session_id,str(a.get("user_agent") or UA))
54
+ checkout_methods=list(ctx.get("customer_payment_method_ids") or [])
55
+ if selected_method not in checkout_methods:raise RuntimeError("SAVED_PAYMENT_METHOD_CONTEXT_MISMATCH: selected card is not attached to this Checkout customer")
56
+ billing=protocol.default_billing("PH",str(a.get("email") or ""),real_random=True)
57
+ tax_state=protocol.submit_checkout_taxes(http,a,processor,session_id,did,billing,currency)
58
+ if tax_state:state={**state,**tax_state};pk=str(state.get("publishable_key") or pk);amount,currency=protocol.oaics_total(state)
59
+ protocol.update_saved_payment_method_billing(stripe,pk,selected_method,billing,ctx,str(a.get("user_agent") or UA))
60
+ ctx=protocol.fetch_deferred_elements(stripe,state,session_id,str(a.get("user_agent") or UA))
61
+ if selected_method not in list(ctx.get("customer_payment_method_ids") or []):raise RuntimeError("SAVED_PAYMENT_METHOD_CONTEXT_CHANGED: selected card disappeared after billing refresh")
62
+ emit(f"Checkout customer/card context matched: customer={str(ctx.get('customer_id') or '')[-6:]} pm={selected_method[-6:]}",phase="validate")
63
+ ctoken=protocol.create_confirmation_token(stripe,pk,selected_method,str(state.get("confirm_return_url") or ""),setup_only=(amount==0),elements_context=ctx,user_agent=str(a.get("user_agent") or UA))
64
+ emit("Saved PaymentMethod, taxes, billing and ConfirmationToken are prepared",phase="prepared")
65
+ pp={"short_url":a.get("short_url"),"processor_entity":processor,"checkout_session_id":session_id,"access_token":a.get("access_token"),"chatgpt_account_id":a.get("chatgpt_account_id"),"session_cookies":a.get("session_cookies") or {},"user_agent":a.get("user_agent") or UA,"checkout_device_id":a.get("checkout_device_id"),"checkout_chatgpt_session_id":a.get("checkout_chatgpt_session_id"),"email":a.get("email"),"proxy":candidate,"proxies":[candidate],"saved_payment_method_id":selected_method,"confirmation_token":ctoken,"card_retry_count":0,"card_retry_delay":1,"prepared_checkout_state":state,"prepared_elements_context":ctx,"prepared_amount":amount,"prepared_currency":currency,"preserve_checkout_identity":True}
66
+ return {"status":"prepared","prepared":{"protocol_payload":pp},"safe":{"amount":amount,"currency":currency.upper(),"saved_payment_method_count":len(methods),"selected_payment_method":True,"route_attempt":index}}
67
+ except Exception as exc:last=f"{type(exc).__name__}: {exc}";emit(f"Preparation route {index} failed: {last}","warn","validate")
68
+ raise RuntimeError(last or "PREPARE_FAILED")
69
+ def confirm(prepared:dict[str,Any])->dict[str,Any]:
70
+ pp=dict(prepared.get("protocol_payload") or {})
71
+ if not pp or not str(pp.get("confirmation_token") or "").startswith("ctoken_"):raise ValueError("PREPARED_CONTEXT_INVALID")
72
+ emit("Barrier released; submitting subscription now",phase="protocol");result=dict(protocol.run(pp) or {});result.update({"flow":"batch_saved_card_protocol","account_email":str(pp.get("email") or ""),"checkout_url":str(pp.get("short_url") or "")});return result
73
+ def main()->int:
74
+ if RUNTIME_MISSING:raise RuntimeError("PROTOCOL_RUNTIME_DEPENDENCY_MISSING: "+", ".join(RUNTIME_MISSING))
75
+ payload=json.loads(sys.stdin.read() or "{}");mode=str(payload.get("mode") or "run").lower()
76
+ if mode=="prepare":result=prepare(dict(payload.get("snapshot") or {}),list(payload.get("proxies") or []))
77
+ elif mode=="confirm":result=confirm(dict(payload.get("prepared") or {}))
78
+ else:
79
+ pre=prepare(dict(payload.get("snapshot") or {}),list(payload.get("proxies") or []));result=confirm(dict(pre.get("prepared") or {}))
80
+ print(json.dumps({"type":"result","result":result},ensure_ascii=True),flush=True);return 0
81
+ if __name__=="__main__":
82
+ try:raise SystemExit(main())
83
+ except Exception as exc:print(json.dumps({"type":"error","error":f"{type(exc).__name__}: {exc}"},ensure_ascii=True),flush=True);raise SystemExit(1)
static/card-flow-logic.js ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function(root,factory){
2
+ const logic=factory();
3
+ root.CardFlowLogic=logic;
4
+ if(typeof module==='object'&&module.exports)module.exports=logic;
5
+ })(typeof globalThis!=='undefined'?globalThis:this,function(){
6
+ 'use strict';
7
+
8
+ function chunkPaymentWaves(items,limit){
9
+ const values=Array.from(items||[]);
10
+ const size=Math.max(1,Number(limit)||1);
11
+ const waves=[];
12
+ for(let offset=0;offset<values.length;offset+=size)waves.push(values.slice(offset,offset+size));
13
+ return waves;
14
+ }
15
+
16
+ function subscriptionFromTask(task){
17
+ const result=task&&typeof task.result==='object'&&task.result?task.result:{};
18
+ const subscription=result.subscription||(task&&typeof task.subscription==='object'?task.subscription:null);
19
+ return subscription&&typeof subscription==='object'?subscription:{};
20
+ }
21
+
22
+ function classifyPlus(task){
23
+ const subscription=subscriptionFromTask(task);
24
+ const taskStatus=String(task?.status||'').toLowerCase();
25
+ const state=String(subscription.verification_state||'').toLowerCase();
26
+ const httpStatus=Number(subscription.http_status||0);
27
+ const hasHttpStatus=Object.prototype.hasOwnProperty.call(subscription,'http_status');
28
+ if(taskStatus==='verification_required'){
29
+ return{verified:false,state:'verification_required',label:'\u9700\u8981\u989d\u5916\u9a8c\u8bc1',subscription};
30
+ }
31
+ if(subscription.verified===true){
32
+ return{verified:true,state:'plus',label:'Plus\u5230\u8d26',subscription};
33
+ }
34
+ if(state==='unknown'||Boolean(subscription.error)||(hasHttpStatus&&httpStatus===0)||(httpStatus>0&&httpStatus!==200)){
35
+ return{verified:false,state:'unknown',label:'Plus\u68c0\u6d4b\u5931\u8d25',subscription};
36
+ }
37
+ if(state==='not_plus'||(!state&&httpStatus===200&&Boolean(subscription.plan_type))){
38
+ return{verified:false,state:'not_plus',label:'Plus\u672a\u5230\u8d26',subscription};
39
+ }
40
+ return{verified:false,state:'pending',label:'Plus\u5f85\u9a8c\u8bc1',subscription};
41
+ }
42
+
43
+ return Object.freeze({chunkPaymentWaves,classifyPlus});
44
+ });
static/card-flow.css ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @charset "UTF-8";
2
+
3
+ :root{color-scheme:dark;--bg:#07111f;--panel:#0d1b2d;--panel2:#101f33;--line:#2b4059;--text:#f4f8ff;--muted:#9eb0c7;--accent:#58d9b2;--accent2:#7291ff;--danger:#ff7388;--ok:#71e6bd}*{box-sizing:border-box}body{margin:0;min-height:100vh;background:radial-gradient(circle at 88% 0,#19465a 0,transparent 36%),linear-gradient(145deg,#07111f,#0a1424);color:var(--text);font:16px/1.6 Inter,"Microsoft YaHei","PingFang SC","Noto Sans CJK SC","Segoe UI",system-ui,sans-serif}.shell{width:min(960px,calc(100% - 36px));margin:0 auto;padding:54px 0 82px}.hero{margin-bottom:28px}.eyebrow{color:var(--accent);font:800 12px ui-monospace,monospace;letter-spacing:.18em}.hero h1{margin:10px 0 8px;font-size:clamp(36px,6vw,62px);line-height:1.06;letter-spacing:-.04em}.hero p{max-width:760px;margin:0;color:var(--muted);font-size:17px}.card{padding:30px;border:1px solid var(--line);border-radius:26px;background:rgba(13,27,45,.94);box-shadow:0 30px 90px rgba(0,0,0,.3)}.steps{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:28px}.steps span{padding:12px;border:1px solid var(--line);border-radius:13px;color:var(--muted);text-align:center;font-size:14px}.steps .active{border-color:var(--accent);color:var(--accent);background:rgba(88,217,178,.08)}.steps .done{border-color:#355f58;color:var(--ok)}.account-panel{padding:20px;border:1px solid var(--line);border-radius:18px;background:var(--panel2);margin-bottom:22px}label{display:block;margin:18px 0 9px;font-weight:800}.account-panel label{margin-top:0}.account-row{display:grid;grid-template-columns:1fr 180px;gap:12px}input{width:100%;min-height:52px;padding:0 16px;border:1px solid var(--line);border-radius:13px;background:#091522;color:var(--text);font:600 16px/1.2 ui-monospace,monospace;outline:none}input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(88,217,178,.12)}button{min-height:52px;padding:14px 18px;border:0;border-radius:14px;background:linear-gradient(135deg,var(--accent),var(--accent2));color:#04101b;font-weight:900;font-size:16px;cursor:pointer}button.secondary{margin:0;background:#172a41;color:var(--text);border:1px solid #3c5571}button:disabled{opacity:.55;cursor:wait}.account-meta{margin-top:12px;color:var(--ok);font-weight:750}.stripe-box{padding:15px;border:1px solid var(--line);border-radius:15px;background:#fff}#submitButton{width:100%;margin-top:26px}.status{margin-top:20px;padding:15px 17px;border-radius:13px;background:#091522;color:var(--muted);white-space:pre-wrap}.status.error{color:var(--danger);border:1px solid rgba(255,115,136,.3)}.status.ok{color:var(--ok);border:1px solid rgba(113,230,189,.25)}.checkout-link{display:none;margin-top:15px;padding:14px;border:1px solid var(--accent);border-radius:13px;color:var(--accent);text-align:center;text-decoration:none;font-weight:850}@media(max-width:680px){.shell{width:min(100% - 22px,960px);padding-top:26px}.card{padding:18px}.steps{grid-template-columns:1fr 1fr}.account-row{grid-template-columns:1fr}.hero p{font-size:15px}}
4
+
5
+ .resume-button{width:100%;margin-top:12px}
6
+
7
+ .checkout-payment-panel{margin-top:22px;padding:20px;border:1px solid var(--line);border-radius:18px;background:var(--panel2)}
8
+ .checkout-payment-panel p{margin:0 0 14px;color:var(--muted)}
9
+ #authorizeButton{width:100%;margin-top:20px}
10
+
11
+
12
+ /* Batch direct-card flow */
13
+ .batch-shell{width:min(1120px,calc(100% - 36px))}
14
+ .batch-card{padding:32px}
15
+ .batch-steps{margin-bottom:24px}
16
+ .batch-section{margin-top:18px;padding:22px;border:1px solid var(--line);border-radius:18px;background:var(--panel2)}
17
+ .section-title{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:15px}
18
+ .section-title b{display:block;font-size:19px}
19
+ .section-title small{display:block;margin-top:2px;color:var(--muted);font-size:14px}
20
+ .tag{padding:5px 9px;border:1px solid #3d5874;border-radius:999px;color:var(--accent);font:800 11px ui-monospace,monospace}
21
+ textarea{width:100%;min-height:190px;padding:16px;border:1px solid var(--line);border-radius:14px;background:#091522;color:var(--text);font:600 14px/1.55 ui-monospace,monospace;resize:vertical;outline:none}
22
+ textarea:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(88,217,178,.12)}
23
+ .card-element-box{padding:18px}
24
+ .inline-state{margin-top:10px;color:var(--muted);font-size:14px}.inline-state.ok{color:var(--ok)}.inline-state.error{color:var(--danger)}
25
+ .action-row{display:grid;grid-template-columns:150px 1fr 150px;gap:12px;margin-top:22px;align-items:end}
26
+ .progress-wrap{margin-top:20px}.progress-meta{display:flex;justify-content:space-between;color:var(--muted);font-size:14px}
27
+ .progress-track{height:9px;margin-top:8px;overflow:hidden;border-radius:999px;background:#07101c}.progress-track i{display:block;width:0;height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2));transition:width .25s}
28
+ .result-section{margin-top:22px}.mini-actions{display:flex;gap:8px}.small{min-height:38px!important;padding:7px 12px!important;font-size:13px!important}
29
+ .result-output{min-height:150px;color:#8cf0cf}
30
+ .task-rows{display:grid;gap:8px;margin-top:14px}.task-row{display:grid;grid-template-columns:minmax(180px,1fr) 180px minmax(220px,2fr);gap:12px;padding:11px 13px;border:1px solid var(--line);border-radius:12px;background:#091522;font-size:13px}.task-row .row-account{overflow:hidden;text-overflow:ellipsis}.task-row .row-stage{color:var(--muted)}.task-row .row-result{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted)}.task-row.running{border-color:#5571a0}.task-row.success{border-color:#2f775f}.task-row.success .row-stage{color:var(--ok)}.task-row.failed{border-color:#79394a}.task-row.failed .row-stage,.task-row.failed .row-result{color:var(--danger)}
31
+ @media(max-width:700px){.batch-shell{width:min(100% - 18px,1120px)}.batch-card{padding:16px}.action-row{grid-template-columns:1fr}.task-row{grid-template-columns:1fr}.task-row .row-result{white-space:normal}.section-title{align-items:flex-start;flex-direction:column}.mini-actions{width:100%}.mini-actions button{flex:1}}
32
+
33
+
34
+ /* Isolated AT input cards */
35
+ .at-title-actions{display:flex;align-items:center;justify-content:flex-end;gap:9px;flex-wrap:wrap}
36
+ .add-at-button,.import-at-button{min-height:38px!important;padding:7px 13px!important}
37
+ .import-at-button{border-color:#355f58!important;color:var(--ok)!important}
38
+ .at-list{display:grid;gap:13px}
39
+ .at-entry{padding:14px;border:1px solid #304963;border-radius:15px;background:#0a1726;box-shadow:inset 3px 0 0 rgba(88,217,178,.42)}
40
+ .at-entry:focus-within{border-color:var(--accent);box-shadow:inset 3px 0 0 var(--accent),0 0 0 3px rgba(88,217,178,.08)}
41
+ .at-entry-head{display:flex;align-items:center;gap:10px;margin-bottom:10px}
42
+ .at-entry-index{color:var(--accent);font:900 13px ui-monospace,monospace;letter-spacing:.08em}
43
+ .at-entry-state{margin-left:auto;color:var(--muted);font-size:12px}
44
+ .remove-at-button{min-height:32px;padding:5px 10px;border:1px solid #4b3443;border-radius:9px;background:#241725;color:#ff9aae;font-size:12px}
45
+ .remove-at-button:disabled{opacity:.35}
46
+ .at-item-input{min-height:104px;resize:vertical;background:#07111e;font-size:13px}
47
+ @media(max-width:700px){.at-section-title{flex-direction:column}.at-title-actions{width:100%;justify-content:flex-start}.at-title-actions .tag{margin-right:auto}.add-at-button,.import-at-button{width:auto}}
48
+
49
+
50
+ /* Separated account and link results */
51
+ .task-rows{margin-top:0}
52
+ .task-row{grid-template-columns:minmax(190px,1fr) 150px minmax(300px,2fr) 112px;align-items:center}
53
+ .row-account-wrap,.row-link-wrap{min-width:0;display:grid;gap:3px}
54
+ .row-account-wrap small,.row-link-wrap small{color:#71859d;font:800 10px ui-monospace,monospace;letter-spacing:.12em}
55
+ .row-account,.row-link,.row-message{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
56
+ .row-account{color:var(--text);font-weight:750}
57
+ .row-link{color:var(--accent);text-decoration:none}.row-link:hover{text-decoration:underline}
58
+ .row-message{color:var(--muted)}
59
+ .copy-one-button{min-height:38px;padding:7px 10px;border:1px solid #3d5b76;border-radius:10px;background:#13273d;color:var(--text);font-size:12px}
60
+ .task-row.failed .row-message{color:var(--danger)}
61
+ @media(max-width:820px){.task-row{grid-template-columns:1fr}.row-account,.row-link,.row-message{white-space:normal;overflow-wrap:anywhere}.copy-one-button{width:100%}}
62
+
63
+
64
+ /* Split Stripe card fields */
65
+ .card-fields-grid{display:grid;grid-template-columns:minmax(0,2fr) minmax(150px,.7fr) minmax(120px,.55fr);gap:12px}
66
+ .card-field{display:block;margin:0}
67
+ .card-field>span{display:block;margin:0 0 7px;color:var(--muted);font-size:13px;font-weight:800}
68
+ .card-field-box{height:56px;padding:17px 15px;border:1px solid #304963;border-radius:13px;background:#091522;transition:border-color .18s,box-shadow .18s,background .18s}
69
+ .card-field-box:hover{border-color:#496681}
70
+ .card-field-box.StripeElement--focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(88,217,178,.12);background:#0b1929}
71
+ .card-field-box.field-complete{border-color:#377a68}
72
+ .card-field-box.field-invalid,.card-field-box.StripeElement--invalid{border-color:var(--danger);box-shadow:0 0 0 3px rgba(255,115,136,.09)}
73
+ @media(max-width:760px){.card-fields-grid{grid-template-columns:1fr 1fr}.card-number-field{grid-column:1/-1}}
74
+
75
+
76
+ /* Per-AT retry action */
77
+ .row-actions{display:grid;gap:7px}
78
+ .retry-one-button{min-height:38px;padding:7px 10px;border:1px solid #725b35;border-radius:10px;background:#2b2417;color:#ffd589;font-size:12px}
79
+ .retry-one-button:disabled{opacity:.48}
80
+ @media(max-width:820px){.row-actions{grid-template-columns:1fr 1fr}.row-actions button{width:100%}}
81
+
82
+
83
+ /* User supplied proxy pool */
84
+ .proxy-pool-input{min-height:150px;font-size:13px}
85
+ .proxy-pool-note{margin-top:9px;color:var(--muted);font-size:13px}
86
+
87
+
88
+ /* Explicit secure card loader */
89
+ .load-card-button{width:100%;margin-top:14px;background:#13273d;color:var(--text);border:1px solid #3d5b76}
90
+ .load-card-button:not(:disabled):hover{border-color:var(--accent);color:var(--accent);background:#10263a}
91
+ .load-card-button:disabled{opacity:.58}
92
+ .card-field-box:empty::after{content:"WAITING FOR SECURE INPUT";color:#63778f;font-size:13px}
93
+ .card-field-box.StripeElement::after{content:none}
94
+
95
+
96
+ /* Dual proxy pools: US binding/checkout + TR promotion */
97
+ .dual-proxy-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
98
+ .proxy-pool-card{padding:15px;border:1px solid #304963;border-radius:15px;background:#0a1726}
99
+ .proxy-pool-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:4px}
100
+ .proxy-pool-card>small{display:block;margin-bottom:10px;color:var(--muted)}
101
+ .proxy-pool-card .proxy-pool-input{min-height:170px}
102
+ @media(max-width:760px){.dual-proxy-grid{grid-template-columns:1fr}}
103
+
104
+ .concurrency-control{margin:0;display:grid;gap:6px;color:var(--muted);font-size:13px}.concurrency-control input{min-height:52px;text-align:center;font-size:18px}.concurrency-control span{font-weight:800;color:var(--text)}
105
+ /* Unified flow adds a final protocol-payment stage. */
106
+ .steps{grid-template-columns:repeat(5,1fr)}
107
+ @media(max-width:680px){.steps{grid-template-columns:repeat(2,1fr)}}
static/card-flow.js ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const apiBase=document.documentElement.dataset.apiBase||'';
2
+ const cardReady=document.getElementById('cardReady');
3
+ const loadCardButton=document.getElementById('loadCardButton');
4
+ const atList=document.getElementById('atList');
5
+ const addAtButton=document.getElementById('addAtButton');
6
+ const importAtButton=document.getElementById('importAtButton');
7
+ const atFileInput=document.getElementById('atFileInput');
8
+ const atCount=document.getElementById('atCount');
9
+ const startButton=document.getElementById('startButton');
10
+ const stopButton=document.getElementById('stopButton');
11
+ const copyButton=document.getElementById('copyButton');
12
+ const clearButton=document.getElementById('clearButton');
13
+ const taskRows=document.getElementById('taskRows');
14
+ const statusBox=document.getElementById('status');
15
+ const progressText=document.getElementById('progressText');
16
+ const progressPercent=document.getElementById('progressPercent');
17
+ const progressBar=document.getElementById('progressBar');
18
+ const bindProxyPoolInput=document.getElementById('bindProxyPool');
19
+ const promoProxyPoolInput=document.getElementById('promoProxyPool');
20
+ const bindProxyCount=document.getElementById('bindProxyCount');
21
+ const promoProxyCount=document.getElementById('promoProxyCount');
22
+ const batchConcurrencyInput=document.getElementById('batchConcurrency');
23
+ const steps=[document.getElementById('stepCard'),document.getElementById('stepAt'),document.getElementById('stepBind'),document.getElementById('stepLink'),document.getElementById('stepPay')].filter(Boolean);
24
+
25
+ let stripe=null;
26
+ let stripeKey='';
27
+ let cardFieldsMounted=false;
28
+ const prefetchedSessions=new Map();
29
+ let cardNumberElement=null,cardExpiryElement=null,cardCvcElement=null;
30
+ const cardComplete={number:false,expiry:false,cvc:false};
31
+ let cardIsReady=false;
32
+ let stopped=false;
33
+ let running=false;
34
+ let proxyCursor=0;
35
+ let cardSetupMutex=Promise.resolve();
36
+ let cardSetupPending=0;
37
+ const results=[];
38
+ const AT_IMPORT_LIMIT=500;
39
+ const MAX_BATCH_CONCURRENCY=200;
40
+ const CONCURRENCY_STORAGE_VERSION='200-v1';
41
+ const flowLogic=window.CardFlowLogic;
42
+ if(!flowLogic)throw new Error('Card flow logic failed to load');
43
+ const plusVerification=flowLogic.classifyPlus;
44
+ const chunkPaymentWaves=flowLogic.chunkPaymentWaves;
45
+ document.documentElement.dataset.cardFlowLogic='ready';
46
+ let paymentWaveLimit=MAX_BATCH_CONCURRENCY;
47
+ let runtimeConfigPromise=null;
48
+ const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
49
+
50
+ function status(text,kind=''){statusBox.textContent=text;statusBox.className=('status '+kind).trim()}
51
+ function stripeSetupFailure(value){
52
+ const stripeError=value||{};
53
+ const details=[];
54
+ if(stripeError.code)details.push('code='+String(stripeError.code));
55
+ if(stripeError.decline_code)details.push('decline_code='+String(stripeError.decline_code));
56
+ const error=new Error((stripeError.message||'Card binding failed')+(details.length?' ('+details.join(', ')+')':''));
57
+ error.stage='card_bind';
58
+ error.stripeCode=String(stripeError.code||'');
59
+ error.declineCode=String(stripeError.decline_code||'');
60
+ return error;
61
+ }
62
+ function setStep(index){steps.forEach((el,i)=>{el.classList.toggle('active',i===index);el.classList.toggle('done',i<index)})}
63
+ function setProgress(done,total,text){const percent=total?Math.round(done*100/total):0;progressText.textContent=text||'';progressPercent.textContent=percent+'%';progressBar.style.width=percent+'%'}
64
+ function tokenLabel(token,index){return 'AT '+(index+1)+' - '+token.slice(0,12)+'...'+token.slice(-8)}
65
+ function collectJsonAccessTokens(value,found=[]){
66
+ if(!value||typeof value!=='object')return found;
67
+ if(Array.isArray(value)){
68
+ for(const item of value)collectJsonAccessTokens(item,found);
69
+ return found;
70
+ }
71
+ const preferred=['accessToken','access_token','access-token','at'];
72
+ for(const key of preferred){
73
+ const token=value[key];
74
+ if(typeof token==='string'&&token.split('.').length===3&&token.length>300)found.push(token.trim());
75
+ }
76
+ for(const [key,item] of Object.entries(value)){
77
+ if(String(key).toLowerCase().includes('sessiontoken'))continue;
78
+ collectJsonAccessTokens(item,found);
79
+ }
80
+ return found;
81
+ }
82
+ function accessTokenRank(token){
83
+ try{
84
+ const segment=token.split('.')[1].replace(/-/g,'+').replace(/_/g,'/');
85
+ const claims=JSON.parse(atob(segment+'='.repeat((4-segment.length%4)%4)));
86
+ const exp=Number(claims.exp||0),iat=Number(claims.iat||0),now=Math.floor(Date.now()/1000);
87
+ return[(exp===0||exp>now)?1:0,iat,exp];
88
+ }catch{return[0,0,0]}
89
+ }
90
+ function chooseLatestAccessToken(values){
91
+ const unique=[...new Set(values.map(value=>String(value||'').trim()).filter(Boolean))];
92
+ unique.sort((left,right)=>{
93
+ const a=accessTokenRank(left),b=accessTokenRank(right);
94
+ return b[0]-a[0]||b[1]-a[1]||b[2]-a[2]||right.length-left.length;
95
+ });
96
+ return unique[0]||'';
97
+ }
98
+ function extractToken(raw){
99
+ const text=String(raw||'').trim();
100
+ if(!text)return'';
101
+ const candidates=[];
102
+ if(text.startsWith('{')||text.startsWith('[')){
103
+ try{
104
+ candidates.push(...collectJsonAccessTokens(JSON.parse(text)));
105
+ }catch{}
106
+ }
107
+ for(const match of text.matchAll(/["']access_?token["']\s*:\s*["']([^"']+)["']/ig))candidates.push(match[1]);
108
+ const jwtMatches=text.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g)||[];
109
+ candidates.push(...jwtMatches);
110
+ candidates.push(...text.split(/[\s|,;]+/).filter(value=>value.length>300&&value.split('.').length===3));
111
+ return chooseLatestAccessToken(candidates)||text;
112
+ }
113
+ function extractAllAccessTokens(raw){
114
+ const text=String(raw||'').trim();
115
+ if(!text)return[];
116
+ const candidates=[];
117
+ if(text.startsWith('{')||text.startsWith('[')){
118
+ try{candidates.push(...collectJsonAccessTokens(JSON.parse(text)))}catch{}
119
+ }
120
+ for(const match of text.matchAll(/["'](?:access_?token|access-token|at)["']\s*:\s*["']([^"']+)["']/ig))candidates.push(match[1]);
121
+ candidates.push(...(text.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g)||[]));
122
+ const seen=new Set(),tokens=[];
123
+ for(const candidate of candidates){
124
+ const token=String(candidate||'').trim();
125
+ if(token.length<300||token.split('.').length!==3||seen.has(token))continue;
126
+ seen.add(token);tokens.push(token);
127
+ if(tokens.length>=AT_IMPORT_LIMIT)break;
128
+ }
129
+ return tokens;
130
+ }
131
+ function renumberAtCards(){
132
+ const cards=[...atList.querySelectorAll('.at-entry')];
133
+ cards.forEach((card,index)=>{
134
+ card.querySelector('.at-entry-index').textContent='AT '+String(index+1).padStart(2,'0');
135
+ card.querySelector('.remove-at-button').disabled=cards.length===1||running;
136
+ });
137
+ atCount.textContent=cards.length+' AT';
138
+ }
139
+ function addAtField(value='',options={}){
140
+ const focus=options.focus!==false;
141
+ const refresh=options.refresh!==false;
142
+ const card=document.createElement('article');
143
+ card.className='at-entry';
144
+ card.innerHTML='<div class="at-entry-head"><span class="at-entry-index"></span><span class="at-entry-state">&#21333;&#29420;&#36755;&#20837;</span><button class="remove-at-button" type="button">&#21024;&#38500;</button></div><textarea class="at-item-input" spellcheck="false" autocomplete="off" placeholder="Paste a raw AT or JSON containing accessToken"></textarea>';
145
+ const input=card.querySelector('.at-item-input');
146
+ input.value=value;
147
+ input.addEventListener('input',updateCount);
148
+ card.querySelector('.remove-at-button').addEventListener('click',()=>{if(running)return;card.remove();if(!atList.children.length)addAtField();renumberAtCards();updateCount()});
149
+ atList.appendChild(card);
150
+ if(refresh){renumberAtCards();updateCount()}
151
+ if(focus)input.focus();
152
+ return input;
153
+ }
154
+ function parseTokens(){
155
+ const seen=new Set(),items=[];
156
+ for(const input of atList.querySelectorAll('.at-item-input')){
157
+ const token=extractToken(input.value);
158
+ if(token.length<300||!token.includes('.')||seen.has(token))continue;
159
+ seen.add(token);items.push(token);
160
+ }
161
+ return items;
162
+ }
163
+ function importAccessTokens(tokens,fileName=''){
164
+ const existing=new Set(parseTokens());
165
+ const blanks=[...atList.querySelectorAll('.at-item-input')].filter(input=>!String(input.value||'').trim());
166
+ let added=0,duplicates=0;
167
+ for(const token of tokens){
168
+ if(existing.has(token)){duplicates++;continue}
169
+ if(existing.size>=AT_IMPORT_LIMIT)break;
170
+ const input=blanks.shift()||addAtField('',{focus:false,refresh:false});
171
+ input.value=token;existing.add(token);added++;
172
+ }
173
+ renumberAtCards();updateCount();
174
+ const source=fileName||'AT \u6587\u4ef6';
175
+ if(added)status('\u5df2\u4ece '+source+' \u5bfc\u5165 '+added+' \u4e2a AT'+(duplicates?'\uff0c\u8df3\u8fc7 '+duplicates+' \u4e2a\u91cd\u590d\u9879':'')+'\u3002','ok');
176
+ else if(duplicates)status('\u6587\u4ef6\u4e2d\u7684 AT \u5df2\u5168\u90e8\u5b58\u5728\u4e8e\u5217\u8868\u4e2d\u3002','error');
177
+ else status('\u672a\u5728\u6587\u4ef6\u4e2d\u627e\u5230\u6709\u6548 AT\u3002','error');
178
+ return added;
179
+ }
180
+ function parseProxyInput(input){
181
+ const seen=new Set(),items=[];
182
+ for(const line of String(input?.value||'').replace(/\r/g,'').split('\n')){
183
+ const value=line.trim();if(!value||seen.has(value))continue;
184
+ seen.add(value);items.push(value);
185
+ if(items.length>=500)break;
186
+ }
187
+ return items;
188
+ }
189
+ function parseBindProxyPool(){return parseProxyInput(bindProxyPoolInput)}
190
+ function parsePromoProxyPool(){return parseProxyInput(promoProxyPoolInput)}
191
+ function nextProxy(){
192
+ const pool=parseBindProxyPool();
193
+ if(!pool.length)throw new Error('Please provide at least one US binding proxy');
194
+ const value=pool[proxyCursor%pool.length];proxyCursor=(proxyCursor+1)%Math.max(1,pool.length);return value;
195
+ }
196
+ function updateCount(){
197
+ const valid=parseTokens().length;
198
+ const total=atList.querySelectorAll('.at-entry').length;
199
+ const bindProxies=parseBindProxyPool().length;
200
+ const promoProxies=parsePromoProxyPool().length;
201
+ atCount.textContent=valid+' / '+total+' AT';
202
+ bindProxyCount.textContent=bindProxies+' PROXY';
203
+ promoProxyCount.textContent=promoProxies+' PROXY';
204
+ if(!running){
205
+ loadCardButton.disabled=cardFieldsMounted||!(valid&&bindProxies);
206
+ loadCardButton.textContent=cardFieldsMounted?'\u5361\u7247\u8f93\u5165\u6846\u5df2\u52a0\u8f7d':'\u52a0\u8f7d\u5b89\u5168\u5361\u7247\u8f93\u5165\u6846';
207
+ startButton.disabled=!(cardFieldsMounted&&cardIsReady&&valid&&bindProxies&&promoProxies);
208
+ startButton.textContent='\u5f00\u59cb\u7ed1\u5361\u3001\u63d0\u94fe\u5e76\u534f\u8bae\u652f\u4ed8';
209
+ }
210
+ }
211
+
212
+ async function api(url,options={}){
213
+ let response;
214
+ try{
215
+ response=await fetch(url,{credentials:'include',...options});
216
+ }catch(cause){
217
+ const error=new Error(cause?.message||'Network request failed');
218
+ error.httpStatus=0;error.networkError=true;throw error;
219
+ }
220
+ const data=await response.json().catch(()=>({}));
221
+ if(!response.ok||data.error||data.ok===false){
222
+ const code=data.error||('HTTP '+response.status);
223
+ const detail=String(data.detail||'').replace(/:\/\/[^/@\s]+@/g,'://***@').trim().slice(0,300);
224
+ const message=['AT_INVALID_OR_EXPIRED','AT_INVALIDATED_OR_EXPIRED'].includes(data.error)?'AT was invalidated by the server or rotated; use the latest AT and retry':(code+(detail?': '+detail:''));
225
+ const error=new Error(message);
226
+ error.httpStatus=response.status;
227
+ error.upstreamStatus=Number(data.status||0);
228
+ error.proxyPoolExhausted=Boolean(data.proxy_pool_exhausted);
229
+ throw error;
230
+ }
231
+ return data;
232
+ }
233
+ function ensureRuntimeConfig(){
234
+ if(runtimeConfigPromise)return runtimeConfigPromise;
235
+ runtimeConfigPromise=api(apiBase+'/api/card-bind/config').then(config=>{
236
+ const configured=Number(config.max_batch_concurrency||MAX_BATCH_CONCURRENCY)||MAX_BATCH_CONCURRENCY;
237
+ paymentWaveLimit=Math.max(1,Math.min(MAX_BATCH_CONCURRENCY,configured));
238
+ document.documentElement.dataset.paymentWaveLimit=String(paymentWaveLimit);
239
+ return paymentWaveLimit;
240
+ }).catch(()=>paymentWaveLimit);
241
+ return runtimeConfigPromise;
242
+ }
243
+ function retryableNetworkError(error){
244
+ if(error?.proxyPoolExhausted)return false;
245
+ const http=Number(error?.httpStatus||0);
246
+ const upstream=Number(error?.upstreamStatus||0);
247
+ const message=String(error?.message||'').toLowerCase();
248
+ if(error?.networkError)return true;
249
+ if([502,503,504].includes(http)&&(!upstream||upstream>=500||upstream===403))return true;
250
+ return /network|timeout|timed out|connection|transport|tls|ssl|empty reply|temporar|upstream/.test(message);
251
+ }
252
+ async function apiWithRetry(url,options={},attempts=3,onRetry=null){
253
+ let lastError=null;
254
+ for(let attempt=1;attempt<=attempts;attempt++){
255
+ try{return await api(url,options)}
256
+ catch(error){
257
+ lastError=error;
258
+ if(!retryableNetworkError(error)||attempt>=attempts)throw error;
259
+ if(onRetry)onRetry(attempt,attempts,error);
260
+ await sleep(1000*attempt);
261
+ }
262
+ }
263
+ throw lastError||new Error('Network request failed');
264
+ }
265
+ async function apiWithProxyRetry(url,baseBody,attempts=3,onRetry=null){
266
+ let lastError=null;
267
+ for(let attempt=1;attempt<=attempts;attempt++){
268
+ const proxy=nextProxy();
269
+ const body={...baseBody,proxy,proxy_pool:parseBindProxyPool()};
270
+ try{return await api(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)})}
271
+ catch(error){
272
+ lastError=error;
273
+ if(!retryableNetworkError(error)||attempt>=attempts)throw error;
274
+ if(onRetry)onRetry(attempt,attempts,error);
275
+ await sleep(1000*attempt);
276
+ }
277
+ }
278
+ throw lastError||new Error('Proxy request failed');
279
+ }
280
+ function findLink(value){
281
+ if(!value)return'';
282
+ if(typeof value==='string'&&/^https:\/\/(?:chatgpt\.com\/checkout|pay\.openai\.com\/)/.test(value))return value;
283
+ if(Array.isArray(value)){for(const item of value){const found=findLink(item);if(found)return found}}
284
+ else if(typeof value==='object'){for(const item of Object.values(value)){const found=findLink(item);if(found)return found}}
285
+ return'';
286
+ }
287
+ function updatePlusStatus(row,verification){
288
+ const target=row?.querySelector('.row-plus');
289
+ if(target)target.textContent=verification.label;
290
+ }
291
+ function finalTaskPresentation(verification){
292
+ if(verification.verified)return{stage:'Completed',kind:'success'};
293
+ if(verification.state==='verification_required')return{stage:'Payment verification required',kind:'running'};
294
+ if(verification.state==='not_plus')return{stage:'Payment completed / Plus not received',kind:'running'};
295
+ if(verification.state==='unknown')return{stage:'Payment completed / Plus check failed',kind:'running'};
296
+ return{stage:'Waiting for Plus verification',kind:'running'};
297
+ }
298
+ function addRow(id,label){
299
+ const row=document.createElement('div');row.className='task-row';row.id=id;
300
+ row.innerHTML='<div class="row-account-wrap"><small>&#36134;&#21495;</small><span class="row-account"></span><small class="row-plus">Plus&#24453;&#26816;&#27979;</small></div><div class="row-stage">Waiting</div><div class="row-link-wrap"><small>&#38142;&#25509;</small><a class="row-link" target="_blank" rel="noopener"></a><span class="row-message"></span></div><div class="row-actions"><button class="copy-one-button" type="button" hidden>&#22797;&#21046;&#38142;&#25509;</button><button class="retry-one-button" type="button" hidden disabled>&#37325;&#35797;&#35813; AT</button></div>';
301
+ row.querySelector('.row-account').textContent=label;
302
+ const copy=row.querySelector('.copy-one-button');
303
+ copy.addEventListener('click',async()=>{
304
+ const link=row.querySelector('.row-link').href;
305
+ if(!link)return;
306
+ await navigator.clipboard.writeText(link);
307
+ copy.textContent='Copied';
308
+ setTimeout(()=>copy.innerHTML='&#22797;&#21046;&#38142;&#25509;',1200);
309
+ });
310
+ const retry=row.querySelector('.retry-one-button');
311
+ retry.addEventListener('click',()=>retrySingleAt(row));
312
+ taskRows.appendChild(row);return row;
313
+ }
314
+ function updateRow(row,stage,kind='',result=''){
315
+ row.className=('task-row '+kind).trim();
316
+ row.querySelector('.row-stage').textContent=stage;
317
+ const link=row.querySelector('.row-link');
318
+ const message=row.querySelector('.row-message');
319
+ const copy=row.querySelector('.copy-one-button');
320
+ const retry=row.querySelector('.retry-one-button');
321
+ if(/^https:\/\//.test(result||'')){
322
+ link.href=result;link.textContent=result;link.hidden=false;
323
+ message.textContent='';copy.hidden=false;retry.hidden=true;
324
+ }else{
325
+ link.removeAttribute('href');link.textContent='';link.hidden=true;
326
+ message.textContent=result||'';copy.hidden=true;retry.hidden=kind!=='failed'||!row._token;retry.disabled=Boolean(row._retrying)||running||cardSetupPending>0;
327
+ }
328
+ }
329
+ function refreshRetryButtons(){
330
+ taskRows.querySelectorAll('.retry-one-button:not([hidden])').forEach(button=>{
331
+ const row=button.closest('.task-row');
332
+ button.disabled=Boolean(row?._retrying)||running||cardSetupPending>0;
333
+ });
334
+ }
335
+ function refreshOutput(){}
336
+
337
+ async function pollCheckout(taskId,onProgress=null){
338
+ for(let i=0;i<180;i++){
339
+ if(stopped)throw new Error('Task stopped');
340
+ const task=await apiWithRetry(apiBase+'/api/card-flow/task/'+taskId,{},3);
341
+ if(onProgress)onProgress(task);
342
+ if(task.status==='done'){
343
+ const link=findLink(task.result||task);
344
+ if(!link)throw new Error('Checkout task completed without a link');
345
+ return link;
346
+ }
347
+ if(['error','failed','cancelled'].includes(task.status))throw new Error(task.error||task.message||'Checkout extraction failed');
348
+ await sleep(2000);
349
+ }
350
+ throw new Error('Checkout extraction timed out');
351
+ }
352
+ async function cancelUnifiedTask(taskId){
353
+ if(!taskId)return;
354
+ try{await api(apiBase+'/api/unified-flow/jobs/'+taskId+'/cancel',{method:'POST'})}catch{}
355
+ }
356
+ async function releaseUnifiedPayments(taskIds){
357
+ return api(apiBase+'/api/unified-flow/batch-confirm',{
358
+ method:'POST',headers:{'Content-Type':'application/json'},
359
+ body:JSON.stringify({job_ids:taskIds})
360
+ });
361
+ }
362
+ async function pollUnifiedTask(taskId,onProgress=null,stopAtPrepared=false){
363
+ for(let i=0;i<900;i++){
364
+ if(stopped){await cancelUnifiedTask(taskId);throw new Error('Task stopped')}
365
+ const data=await apiWithRetry(apiBase+'/api/unified-flow/jobs/'+taskId,{},3);
366
+ const task=data.job||{};
367
+ if(onProgress)onProgress(task);
368
+ if(stopAtPrepared&&task.status==='prepared')return task;
369
+ if(['ready','verification_required','pending_verification'].includes(task.status))return task;
370
+ if(['error','failed','cancelled'].includes(task.status))throw new Error(task.error||task.message||'Unified flow failed');
371
+ await sleep(1500);
372
+ }
373
+ await cancelUnifiedTask(taskId);
374
+ throw new Error('Unified flow timed out');
375
+ }
376
+ async function mountCardFields(publishableKey){
377
+ if(typeof window.Stripe!=='function')throw new Error('Stripe \u5b89\u5168\u7ec4\u4ef6\u52a0\u8f7d\u5931\u8d25\uff0c\u8bf7\u5237\u65b0\u9875\u9762\u540e\u91cd\u8bd5');
378
+ if(cardNumberElement){try{cardNumberElement.destroy()}catch{}}
379
+ if(cardExpiryElement){try{cardExpiryElement.destroy()}catch{}}
380
+ if(cardCvcElement){try{cardCvcElement.destroy()}catch{}}
381
+ for(const key of Object.keys(cardComplete))cardComplete[key]=false;
382
+ cardIsReady=false;updateCount();
383
+ stripeKey=publishableKey;
384
+ cardFieldsMounted=true;
385
+ stripe=Stripe(publishableKey);
386
+ const elements=stripe.elements();
387
+ const style={
388
+ base:{fontSize:'17px',fontFamily:'"Microsoft YaHei","PingFang SC","Segoe UI",system-ui,sans-serif',color:'#f4f8ff',iconColor:'#58d9b2','::placeholder':{color:'#6f8299'}},
389
+ invalid:{color:'#ff7388',iconColor:'#ff7388'}
390
+ };
391
+ cardNumberElement=elements.create('cardNumber',{showIcon:true,style});
392
+ cardExpiryElement=elements.create('cardExpiry',{style});
393
+ cardCvcElement=elements.create('cardCvc',{style});
394
+ const entries=[['number',cardNumberElement,'#cardNumberElement'],['expiry',cardExpiryElement,'#cardExpiryElement'],['cvc',cardCvcElement,'#cardCvcElement']];
395
+ let readyCount=0;
396
+ const refreshCardState=()=>{
397
+ cardIsReady=cardComplete.number&&cardComplete.expiry&&cardComplete.cvc;
398
+ cardReady.textContent=cardIsReady?'Card information is complete':'Please complete card number, expiry and CVC';
399
+ cardReady.className='inline-state '+(cardIsReady?'ok':'');updateCount();
400
+ };
401
+ for(const [name,element,selector] of entries){
402
+ document.querySelector(selector).innerHTML='';
403
+ element.on('ready',()=>{readyCount++;if(readyCount===3){cardReady.textContent='Card fields are ready';cardReady.className='inline-state ok'}});
404
+ element.on('change',event=>{cardComplete[name]=Boolean(event.complete);const host=document.querySelector(selector);host.classList.toggle('field-complete',Boolean(event.complete));host.classList.toggle('field-invalid',Boolean(event.error));if(event.error){cardReady.textContent=event.error.message;cardReady.className='inline-state error'}else refreshCardState()});
405
+ element.mount(selector);
406
+ }
407
+ }
408
+ async function init(){
409
+ cardReady.textContent='\u8bf7\u5148\u586b\u5199 AT \u548c\u4ee3\u7406\u6c60\uff0c\u518d\u70b9\u51fb\u201c\u52a0\u8f7d\u5b89\u5168\u5361\u7247\u8f93\u5165\u6846\u201d';
410
+ cardReady.className='inline-state';
411
+ status('\u586b\u5199 AT \u4e0e\u4ee3\u7406\u6c60\u540e\uff0c\u5148\u52a0\u8f7d\u5361\u7247\u8f93\u5165\u6846\uff0c\u518d\u8f93\u5165\u5361\u53f7\u3001\u6709\u6548\u671f\u548c CVC\u3002');
412
+ updateCount();
413
+ }
414
+ async function resolvePendingKey(session){
415
+ if(!session||!session.pending)return session;
416
+ const probeId=String(session.key_probe_id||'');
417
+ if(!probeId)throw new Error('Stripe key probe ID is missing');
418
+ for(let i=0;i<360;i++){
419
+ const data=await apiWithRetry(apiBase+'/api/card-bind/key-probe/'+probeId,{},3);
420
+ const probe=data.probe||{};
421
+ status('Resolving Stripe key via temporary Checkout: '+Number(probe.progress||0)+'%');
422
+ if(probe.status==='done'){
423
+ const refreshed=(probe.session&&typeof probe.session==='object')?probe.session:{};
424
+ const key=String(refreshed.publishable_key||probe.publishable_key||'');
425
+ if(!key.startsWith('pk_'))throw new Error('Checkout initialization completed without a Stripe key');
426
+ if(!String(refreshed.client_secret||'').startsWith('seti_'))throw new Error('Checkout initialized, but the refreshed SetupIntent is missing');
427
+ return {...session,...refreshed,pending:false,publishable_key:key,publishable_key_source:'checkout_then_refetch'};
428
+ }
429
+ if(probe.status==='error')throw new Error(probe.error||probe.message||'Stripe key resolution failed');
430
+ await sleep(2000);
431
+ }
432
+ throw new Error('Stripe key resolution timed out');
433
+ }
434
+ async function loadCardFieldsFromAt(token){
435
+ status('Reading AT and resolving the Stripe account...');
436
+ let session=await apiWithProxyRetry(apiBase+'/api/card-bind/session',{access_token:token},3,(attempt,total)=>status('Resolving Stripe account, proxy retry '+attempt+' / '+total));
437
+ session=await resolvePendingKey(session);
438
+ const key=String(session.publishable_key||'');
439
+ if(!key.startsWith('pk_'))throw new Error('The AT/Checkout response did not contain a Stripe publishable key');
440
+ prefetchedSessions.set(token,session);
441
+ await mountCardFields(key);
442
+ status(session.publishable_key_source==='configured_protocol_fallback'?'SetupIntent and the local protocol Stripe key are ready.':session.publishable_key_source==='checkout_protocol_fallback'?'AT response had no key; one Checkout was created and the card fields are now ready.':'Stripe key was resolved directly from the AT response.','ok');
443
+ }
444
+ async function confirmCardSetupExclusive(row,session){
445
+ const queued=cardSetupPending>0;
446
+ cardSetupPending++;
447
+ refreshRetryButtons();
448
+ if(queued)updateRow(row,'Waiting for card binding slot','running');
449
+ const previous=cardSetupMutex;
450
+ let release;
451
+ cardSetupMutex=new Promise(resolve=>{release=resolve});
452
+ await previous;
453
+ try{
454
+ if(stopped)throw new Error('Task stopped');
455
+ updateRow(row,'Binding the card','running');
456
+ row.dataset.phase='card_bind';
457
+ return await stripe.confirmCardSetup(
458
+ session.client_secret,
459
+ {payment_method:{card:cardNumberElement,billing_details:session.billing_details,allow_redisplay:'always'}}
460
+ );
461
+ }finally{
462
+ cardSetupPending--;
463
+ release();
464
+ refreshRetryButtons();
465
+ }
466
+ }
467
+ async function prepareOne(token,index,total,existingRow=null){
468
+ const row=existingRow||addRow('task-'+Date.now()+'-'+index,tokenLabel(token,index));
469
+ row._token=token;row.dataset.atIndex=String(index);
470
+ row.dataset.phase='card_session';
471
+ row.querySelector('.row-account').textContent=tokenLabel(token,index);
472
+ updateRow(row,'Reading AT and creating SetupIntent','running');
473
+ let session=prefetchedSessions.get(token)||null;
474
+ if(session)prefetchedSessions.delete(token);
475
+ if(!session){
476
+ session=await apiWithProxyRetry(apiBase+'/api/card-bind/session',{access_token:token},3,(attempt,total)=>updateRow(row,'Proxy retry '+attempt+' / '+total,'running'));
477
+ session=await resolvePendingKey(session);
478
+ }
479
+ const sessionKey=String(session.publishable_key||'');
480
+ if(sessionKey&&sessionKey!==stripeKey){
481
+ prefetchedSessions.set(token,session);
482
+ await mountCardFields(sessionKey);
483
+ stopped=true;
484
+ const error=new Error('Stripe account changed. Card fields were refreshed with the Checkout key; re-enter the card and retry this AT.');
485
+ error.cardReentryRequired=true;
486
+ throw error;
487
+ }
488
+ const account=session.account_email||('account-'+(index+1));
489
+ row.querySelector('.row-account').textContent=account;
490
+ if(!session.billing_details)throw new Error('Automatic US billing details are missing');
491
+
492
+ const confirmation=await confirmCardSetupExclusive(row,session);
493
+ if(confirmation.error)throw stripeSetupFailure(confirmation.error);
494
+ if(!confirmation.setupIntent||confirmation.setupIntent.status!=='succeeded'){
495
+ const error=new Error('Card binding status: '+(confirmation.setupIntent?.status||'unknown'));
496
+ error.stage='card_bind';throw error;
497
+ }
498
+ const pm=typeof confirmation.setupIntent.payment_method==='string'?confirmation.setupIntent.payment_method:confirmation.setupIntent.payment_method?.id;
499
+ if(!pm){const error=new Error('Stripe did not return a PaymentMethod');error.stage='card_bind';throw error}
500
+
501
+ updateRow(row,'Starting unified card, link and payment task','running');
502
+ row.dataset.phase='task_create';
503
+ const created=await api(apiBase+'/api/unified-flow/jobs',{
504
+ method:'POST',headers:{'Content-Type':'application/json'},
505
+ body:JSON.stringify({access_token:token,payment_method_id:pm,entry_proxy_pool:parseBindProxyPool(),exit_proxy_pool:parsePromoProxyPool()})
506
+ });
507
+ const job=created.job||{};
508
+ row._unifiedTaskId=String(job.id||'');
509
+ return{account,row,jobId:row._unifiedTaskId,paymentMethodId:pm};
510
+ }
511
+ async function retrySingleAt(row){
512
+ if(!row?._token||row._retrying)return;
513
+ if(running||cardSetupPending>0){status('A card binding task is already running. Retry after it finishes.','error');return}
514
+ if(!cardIsReady){status('Please complete the card fields before retrying this AT.','error');return}
515
+ const batchWasRunning=running;
516
+ row._retrying=true;
517
+ const retry=row.querySelector('.retry-one-button');
518
+ retry.disabled=true;
519
+ if(!batchWasRunning){startButton.disabled=true;addAtButton.disabled=true;importAtButton.disabled=true}
520
+ try{
521
+ status('??????? AT??????????');
522
+ if(row._unifiedTaskId){await cancelUnifiedTask(row._unifiedTaskId);row._unifiedTaskId='';await sleep(300)}
523
+ const index=Number(row.dataset.atIndex||0);
524
+ const prepared=await prepareOne(row._token,index,1,row);
525
+ const onProgress=item=>updateRow(prepared.row,item.stage||item.message||'Running',item.status==='error'?'failed':'running',item.checkout_url||'');
526
+ await pollUnifiedTask(prepared.jobId,onProgress,true);
527
+ updateRow(row,'Ready for payment','running');
528
+ await releaseUnifiedPayments([prepared.jobId]);
529
+ const task=await pollUnifiedTask(prepared.jobId,onProgress);
530
+ const link=task.checkout_url||findLink(task.result||task);
531
+ const verification=plusVerification(task);
532
+ updatePlusStatus(row,verification);
533
+ const previous=results.findIndex(item=>item.account===prepared.account);
534
+ if(previous>=0)results.splice(previous,1);
535
+ results.push({account:prepared.account,link,status:task.status,subscription:verification.subscription,plusStatus:verification.state});
536
+ refreshOutput();
537
+ const presentation=finalTaskPresentation(verification);
538
+ updateRow(row,presentation.stage,presentation.kind,link||task.message);
539
+ status('? AT ????????','ok');
540
+ }catch(error){
541
+ updateRow(row,'Retry failed','failed',error.message);
542
+ status('? AT ?????'+error.message,'error');
543
+ }finally{
544
+ row._retrying=false;refreshRetryButtons();
545
+ if(!batchWasRunning){
546
+ startButton.disabled=!(cardFieldsMounted&&cardIsReady&&parseTokens().length&&parseBindProxyPool().length&&parsePromoProxyPool().length);
547
+ addAtButton.disabled=false;importAtButton.disabled=false;
548
+ }
549
+ }
550
+ }
551
+
552
+ loadCardButton.addEventListener('click',async()=>{
553
+ if(running||cardFieldsMounted)return;
554
+ const tokens=parseTokens();
555
+ if(!tokens.length){status('\u8bf7\u5148\u586b\u5199\u81f3\u5c11\u4e00\u4e2a\u6709\u6548 AT\u3002','error');return}
556
+ if(!parseBindProxyPool().length){status('\u8bf7\u5148\u5728\u4ee3\u7406\u6c60 1 \u586b\u5199 US \u7ed1\u5361\u8282\u70b9\u3002','error');return}
557
+ running=true;loadCardButton.disabled=true;startButton.disabled=true;addAtButton.disabled=true;importAtButton.disabled=true;
558
+ cardReady.textContent='\u6b63\u5728\u521b\u5efa\u5b89\u5168\u5361\u7247\u8f93\u5165\u4f1a\u8bdd\u2026';cardReady.className='inline-state';
559
+ try{
560
+ await loadCardFieldsFromAt(tokens[0]);
561
+ cardReady.textContent='\u5361\u7247\u8f93\u5165\u6846\u5df2\u5c31\u7eea\uff0c\u8bf7\u8f93\u5165\u5361\u53f7\u3001\u6709\u6548\u671f\u548c CVC';
562
+ cardReady.className='inline-state ok';
563
+ }catch(error){
564
+ cardFieldsMounted=false;
565
+ cardReady.textContent='\u5361\u7247\u8f93\u5165\u6846\u52a0\u8f7d\u5931\u8d25\uff1a'+error.message;
566
+ cardReady.className='inline-state error';
567
+ status('\u5361\u7247\u8f93\u5165\u6846\u52a0\u8f7d\u5931\u8d25\uff1a'+error.message,'error');
568
+ }finally{
569
+ running=false;addAtButton.disabled=false;importAtButton.disabled=false;renumberAtCards();updateCount();
570
+ }
571
+ });
572
+
573
+ startButton.addEventListener('click',async()=>{
574
+ if(running)return;
575
+ const tokens=parseTokens();
576
+ if(!tokens.length){status('?????????? AT?','error');return}
577
+ if(!parseBindProxyPool().length){status('?????? 1 ?? US ?????','error');return}
578
+ if(!parsePromoProxyPool().length){status('?????? 2 ?? TR ?????','error');return}
579
+ if(!cardFieldsMounted){status('????????????????','error');return}
580
+ if(!cardIsReady){status('???????????? CVC?','error');return}
581
+ await ensureRuntimeConfig();
582
+ const concurrency=Math.max(1,Math.min(MAX_BATCH_CONCURRENCY,tokens.length,Number(batchConcurrencyInput?.value||MAX_BATCH_CONCURRENCY)||MAX_BATCH_CONCURRENCY));
583
+ localStorage.setItem('cardLinkConcurrency',String(concurrency));
584
+ localStorage.setItem('cardLinkConcurrencyVersion',CONCURRENCY_STORAGE_VERSION);
585
+ running=true;stopped=false;results.length=0;refreshOutput();taskRows.innerHTML='';
586
+ startButton.disabled=true;stopButton.disabled=false;addAtButton.disabled=true;importAtButton.disabled=true;atList.querySelectorAll('textarea,button').forEach(el=>el.disabled=true);
587
+ setStep(2);setProgress(0,tokens.length,'\u7edf\u4e00\u4efb\u52a1\u5df2\u542f\u52a8 '+concurrency);
588
+ let success=0,pending=0,failed=0,preparedUnits=0,nextIndex=0;
589
+ const preparedTasks=[];
590
+ const progressUpdate=text=>setProgress(Math.min(preparedUnits,tokens.length),tokens.length,text);
591
+ const worker=async workerId=>{
592
+ await sleep(workerId*120);
593
+ while(!stopped){
594
+ const i=nextIndex++;
595
+ if(i>=tokens.length)return;
596
+ status('??????'+Math.min(nextIndex,tokens.length)+' / '+tokens.length+'??? '+concurrency);
597
+ let prepared=null;
598
+ try{
599
+ prepared=await prepareOne(tokens[i],i,tokens.length);
600
+ progressUpdate('\u7ed1\u5361\u5b8c\u6210\uff0c\u7b49\u5f85\u7edf\u4e00\u4efb\u52a1 '+(i+1)+' / '+tokens.length);
601
+ }catch(error){
602
+ failed++;preparedUnits++;
603
+ const row=document.querySelector('[data-at-index="'+i+'"]')||taskRows.querySelectorAll('.task-row')[i];
604
+ if(row){
605
+ const phase=String(error.stage||row.dataset.phase||'');
606
+ const title=phase==='card_bind'?'Card binding failed':phase==='card_session'?'Card session failed':'Unified task creation failed';
607
+ updateRow(row,title,'failed',error.message);
608
+ }
609
+ progressUpdate('\u5931\u8d25 '+(success+failed)+' / '+tokens.length);
610
+ continue;
611
+ }
612
+ if(stopped)return;
613
+ setStep(3);
614
+ try{
615
+ const task=await pollUnifiedTask(prepared.jobId,item=>{
616
+ const kind=item.status==='error'?'failed':'running';
617
+ updateRow(prepared.row,item.stage||item.message||'Unified flow running',kind,item.checkout_url||'');
618
+ if(item.stage==='协议支付')setStep(4);
619
+ },true);
620
+ const link=task.checkout_url||findLink(task.result||task);
621
+ preparedTasks.push({prepared,link});
622
+ updateRow(prepared.row,'Ready for concurrent payment','running',link||task.message);
623
+ }catch(error){
624
+ if(!prepared.row._retrying){
625
+ failed++;updateRow(prepared.row,'Unified flow failed','failed',error.message);
626
+ }
627
+ }finally{
628
+ preparedUnits++;progressUpdate('Pre-payment ready '+preparedUnits+' / '+tokens.length);
629
+ }
630
+ }
631
+ };
632
+ await Promise.all(Array.from({length:concurrency},(_,index)=>worker(index)));
633
+ if(!stopped&&preparedTasks.length){
634
+ setStep(4);
635
+ let paymentFinished=failed;
636
+ const paymentWaves=chunkPaymentWaves(preparedTasks,paymentWaveLimit);
637
+ const waveTotal=paymentWaves.length;
638
+ for(let waveIndex=0;waveIndex<paymentWaves.length&&!stopped;waveIndex++){
639
+ const wave=paymentWaves[waveIndex];
640
+ const waveNumber=waveIndex+1;
641
+ status('Pre-payment tasks are ready. Releasing payment wave '+waveNumber+' / '+waveTotal+' ('+wave.length+' accounts) concurrently.');
642
+ try{
643
+ await releaseUnifiedPayments(wave.map(item=>item.prepared.jobId));
644
+ await Promise.all(wave.map(async item=>{
645
+ const {prepared,link:preparedLink}=item;
646
+ try{
647
+ const task=await pollUnifiedTask(prepared.jobId,progress=>updateRow(prepared.row,progress.stage||progress.message||'Concurrent payment running',progress.status==='error'?'failed':'running',progress.checkout_url||preparedLink||''));
648
+ const link=task.checkout_url||preparedLink||findLink(task.result||task);
649
+ const verification=plusVerification(task);
650
+ updatePlusStatus(prepared.row,verification);
651
+ results.push({account:prepared.account,link,status:task.status,subscription:verification.subscription,plusStatus:verification.state});refreshOutput();
652
+ if(verification.verified){updateRow(prepared.row,'Completed','success',link);success++}
653
+ else{
654
+ const presentation=finalTaskPresentation(verification);
655
+ updateRow(prepared.row,presentation.stage,presentation.kind,link||task.message);pending++;
656
+ }
657
+ }catch(error){
658
+ failed++;updatePlusStatus(prepared.row,{label:'Plus\u68c0\u6d4b\u5931\u8d25'});updateRow(prepared.row,'Unified flow failed','failed',error.message);
659
+ }finally{
660
+ paymentFinished++;setProgress(Math.min(paymentFinished,tokens.length),tokens.length,'Concurrent payment '+paymentFinished+' / '+tokens.length);
661
+ }
662
+ }));
663
+ }catch(error){
664
+ failed+=wave.length;paymentFinished+=wave.length;
665
+ await Promise.all(wave.map(item=>cancelUnifiedTask(item.prepared.jobId)));
666
+ wave.forEach(item=>{updatePlusStatus(item.prepared.row,{label:'Plus\u68c0\u6d4b\u5931\u8d25'});updateRow(item.prepared.row,'Concurrent payment release failed','failed',error.message)});
667
+ setProgress(Math.min(paymentFinished,tokens.length),tokens.length,'Concurrent payment '+paymentFinished+' / '+tokens.length);
668
+ }
669
+ }
670
+ }
671
+ setStep(4);setProgress(tokens.length,tokens.length,'\u7edf\u4e00\u4efb\u52a1\u5df2\u7ed3\u675f');
672
+ status('\u672c\u6279\u5b8c\u6210\uff1a'+success+' \u6210\u529f,'+pending+' \u5f85\u9a8c\u8bc1,'+failed+' \u5931\u8d25'+(stopped?'\uff08\u5df2\u505c\u6b62\uff09':''),failed?'error':'ok');
673
+ running=false;stopButton.disabled=true;addAtButton.disabled=false;importAtButton.disabled=false;atList.querySelectorAll('textarea,button').forEach(el=>el.disabled=false);refreshRetryButtons();renumberAtCards();updateCount();
674
+ });
675
+ stopButton.addEventListener('click',async()=>{stopped=true;stopButton.disabled=true;status('\u6b63\u5728\u505c\u6b62\u7edf\u4e00\u4efb\u52a1...');await Promise.all([...taskRows.querySelectorAll('.task-row')].map(row=>cancelUnifiedTask(row._unifiedTaskId)))});
676
+ copyButton.addEventListener('click',async()=>{const links=results.map(item=>item.link).filter(Boolean);if(!links.length)return;await navigator.clipboard.writeText(links.join('\n'));status('All links copied.','ok')});
677
+ clearButton.addEventListener('click',()=>{results.length=0;refreshOutput();taskRows.innerHTML='';setProgress(0,0,'Waiting to start');status('Results cleared.')});
678
+ addAtButton.addEventListener('click',()=>addAtField());
679
+ importAtButton.addEventListener('click',()=>{if(!running)atFileInput.click()});
680
+ atFileInput.addEventListener('change',async()=>{
681
+ const file=atFileInput.files?.[0];atFileInput.value='';
682
+ if(!file||running)return;
683
+ if(file.size>5*1024*1024){status('\u6587\u4ef6\u8d85\u8fc7 5 MB\uff0c\u8bf7\u62c6\u5206\u540e\u91cd\u8bd5\u3002','error');return}
684
+ importAtButton.disabled=true;
685
+ try{importAccessTokens(extractAllAccessTokens(await file.text()),file.name)}
686
+ catch(error){status('\u8bfb\u53d6 AT \u6587\u4ef6\u5931\u8d25\uff1a'+String(error?.message||error),'error')}
687
+ finally{importAtButton.disabled=running}
688
+ });
689
+ bindProxyPoolInput.value=localStorage.getItem('cardLinkBindProxyPool')||localStorage.getItem('cardLinkProxyPool')||'';
690
+ promoProxyPoolInput.value=localStorage.getItem('cardLinkPromoProxyPool')||'';
691
+ if(batchConcurrencyInput){
692
+ const isCurrent=localStorage.getItem('cardLinkConcurrencyVersion')===CONCURRENCY_STORAGE_VERSION;
693
+ const stored=Number(isCurrent?localStorage.getItem('cardLinkConcurrency'):MAX_BATCH_CONCURRENCY)||MAX_BATCH_CONCURRENCY;
694
+ batchConcurrencyInput.value=String(Math.max(1,Math.min(MAX_BATCH_CONCURRENCY,stored)));
695
+ localStorage.setItem('cardLinkConcurrency',batchConcurrencyInput.value);
696
+ localStorage.setItem('cardLinkConcurrencyVersion',CONCURRENCY_STORAGE_VERSION);
697
+ }
698
+ bindProxyPoolInput.addEventListener('input',()=>{localStorage.setItem('cardLinkBindProxyPool',bindProxyPoolInput.value);updateCount()});
699
+ promoProxyPoolInput.addEventListener('input',()=>{localStorage.setItem('cardLinkPromoProxyPool',promoProxyPoolInput.value);updateCount()});
700
+ batchConcurrencyInput?.addEventListener('change',()=>{const value=Math.max(1,Math.min(MAX_BATCH_CONCURRENCY,Number(batchConcurrencyInput.value||MAX_BATCH_CONCURRENCY)||MAX_BATCH_CONCURRENCY));batchConcurrencyInput.value=String(value);localStorage.setItem('cardLinkConcurrency',String(value));localStorage.setItem('cardLinkConcurrencyVersion',CONCURRENCY_STORAGE_VERSION)});
701
+ addAtField();
702
+ ensureRuntimeConfig();
703
+ init();
static/card-long-flow.js ADDED
@@ -0,0 +1 @@
 
 
1
+ const statusBox=document.getElementById('status'),form=document.getElementById('flowForm'),button=document.getElementById('submitButton'),checkoutLink=document.getElementById('checkoutLink');let stripe,elements,recordId;const requestedRecordId=new URLSearchParams(location.search).get('record_id')||'';const sleep=ms=>new Promise(r=>setTimeout(r,ms));function status(text,kind=''){statusBox.textContent=text;statusBox.className=`status ${kind}`.trim()}function findLink(v){if(!v)return'';if(typeof v==='string'&&/^https:\/\/(?:checkout\.stripe\.com|pay\.openai\.com)\//.test(v))return v;if(Array.isArray(v)){for(const x of v){const r=findLink(x);if(r)return r}}else if(typeof v==='object'){for(const x of Object.values(v)){const r=findLink(x);if(r)return r}}return''}async function api(url,options={}){const r=await fetch(url,{credentials:'include',...options});const d=await r.json().catch(()=>({}));if(!r.ok||d.error)throw new Error(d.error||`HTTP ${r.status}`);return d}async function init(){try{const d=await api('../api/card-bind/session',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({record_id:requestedRecordId})});recordId=d.record_id;stripe=Stripe(d.publishable_key);elements=stripe.elements({clientSecret:d.client_secret,appearance:{theme:'stripe',variables:{borderRadius:'10px'}}});elements.create('payment',{layout:'tabs'}).mount('#paymentElement');elements.create('address',{mode:'billing'}).mount('#addressElement');status('Secure payment form is ready.','ok')}catch(e){status(`Initialization failed: ${e.message}`,'error');button.disabled=true}}async function poll(id){for(let i=0;i<180;i++){const t=await api(`/api/tasks/${id}`);status(`Long checkout task: ${t.message||t.status} - ${Number(t.progress||0)}%`);if(t.status==='done'){const link=findLink(t.result||t);if(!link)throw new Error('Task completed without a hosted link');return link}if(['error','failed','cancelled'].includes(t.status))throw new Error(t.error||t.message||'Long checkout task failed');await sleep(2000)}throw new Error('Long checkout task timed out')}form.addEventListener('submit',async e=>{e.preventDefault();if(!stripe||!elements)return;button.disabled=true;checkoutLink.style.display='none';try{status('Saving card with hosted redisplay enabled...');const r=await stripe.confirmSetup({elements,redirect:'if_required',confirmParams:{return_url:location.href,payment_method_data:{allow_redisplay:'always'}}});if(r.error)throw new Error(r.error.message);if(r.setupIntent?.status!=='succeeded')throw new Error(`Card binding status: ${r.setupIntent?.status||'unknown'}`);const pm=typeof r.setupIntent.payment_method==='string'?r.setupIntent.payment_method:r.setupIntent.payment_method?.id;if(!pm)throw new Error('Stripe did not return a payment method ID');status('Card saved. Setting it as the default payment method...','ok');await api('../api/card-bind/default',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({payment_method_id:pm,record_id:recordId})});status('Default card updated. Creating hosted long link...','ok');const c=await api(`/api/accounts/${recordId}/quick-checkout`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({link_type:'hosted',promo_country:'US',billing_country:'US',use_promo:false,use_sentinel:true,proxy_provider:'1024proxy'})});const link=await poll(c.task_id);checkoutLink.href=link;checkoutLink.style.display='block';status('Long checkout created. Opening hosted checkout...','ok');setTimeout(()=>location.href=link,900)}catch(err){status(`Flow failed: ${err.message}`,'error');button.disabled=false}});init();
static/direct-bind.css DELETED
@@ -1,102 +0,0 @@
1
- :root { color-scheme: dark; --bg:#07111f; --panel:#101e31; --panel2:#0b192b; --line:#29415c; --text:#e7f0fb; --muted:#8da6c0; --accent:#62dfbd; --blue:#70b7ff; --danger:#ff7186; }
2
- * { box-sizing:border-box; }
3
- body { margin:0; min-height:100vh; background:radial-gradient(circle at 85% 0,#12384e 0,transparent 32rem),linear-gradient(135deg,#06101d,#0b1728 58%,#081321); color:var(--text); font:15px/1.55 "Microsoft YaHei","PingFang SC",system-ui,sans-serif; }
4
- .shell { width:min(1180px,calc(100% - 32px)); margin:0 auto; padding:58px 0 70px; }
5
- .hero { margin:0 0 22px; }
6
- .eyebrow { color:var(--accent); font-size:12px; font-weight:800; letter-spacing:.16em; }
7
- h1 { margin:8px 0 6px; font-size:clamp(30px,5vw,50px); line-height:1.08; }
8
- .hero p { max-width:900px; margin:0; color:var(--muted); }
9
- .card { border:1px solid var(--line); border-radius:22px; background:rgba(16,30,49,.94); box-shadow:0 22px 70px #0005; }
10
- .batch-card { padding:22px; }
11
- .steps { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; margin-bottom:18px; }
12
- .steps span { padding:11px 12px; text-align:center; border:1px solid var(--line); border-radius:13px; color:var(--muted); background:#0b192b; font-weight:800; }
13
- .steps span.active { border-color:var(--accent); color:var(--accent); background:#10283a; }
14
- .steps span.done { border-color:#2e7769; color:var(--accent); }
15
- .setup-grid { display:grid; grid-template-columns:1fr 1.08fr; gap:14px; }
16
- .batch-section { padding:18px; border:1px solid #223a55; border-radius:16px; background:rgba(12,27,45,.72); }
17
- .section-title { display:flex; justify-content:space-between; align-items:flex-start; gap:12px; margin-bottom:15px; }
18
- .section-title b { font-size:17px; }
19
- .section-title small { display:block; margin-top:4px; color:var(--muted); }
20
- .tag { display:inline-flex; align-items:center; border:1px solid #2c796d; border-radius:999px; padding:4px 10px; color:var(--accent); font-size:11px; white-space:nowrap; }
21
- .card-fields-grid { display:grid; grid-template-columns:2fr 1fr 1fr; gap:10px; }
22
- .card-field span { display:block; margin-bottom:6px; color:var(--muted); }
23
- .card-field-box { min-height:48px; padding:14px; border:1px solid #2e806f; border-radius:11px; background:#091728; }
24
- .billing-head { display:flex; justify-content:space-between; align-items:baseline; gap:10px; margin:16px 0 8px; padding-top:13px; border-top:1px solid #223a55; }
25
- .billing-head small { color:var(--muted); font-size:11px; text-align:right; }
26
- .billing-auto-status { padding:10px 12px; border:1px dashed #35516d; border-radius:10px; color:var(--muted); background:#091728; font-size:12px; }
27
- .billing-auto-status.is-test { border-color:#2c796d; color:var(--accent); }
28
- .billing-auto-status.is-live { border-color:#9b7440; color:#f4ca72; }
29
- .billing-auto-status.error { border-color:#8f3f52; color:var(--danger); }
30
- .billing-grid[hidden] { display:none; }
31
- .billing-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:9px; }
32
- .billing-field { display:block; min-width:0; }
33
- .billing-field span { display:block; margin-bottom:5px; color:var(--muted); font-size:12px; }
34
- .billing-field input { width:100%; min-width:0; }
35
- .billing-field.billing-wide { grid-column:span 2; }
36
- .inline-state { min-height:25px; margin:11px 0 8px; color:var(--muted); }
37
- .inline-state.ok { color:var(--accent); }
38
- .inline-state.error { color:var(--danger); }
39
- .inline-state.warn { color:#f4ca72; }
40
- .at-title-actions { display:flex; align-items:center; gap:7px; flex-wrap:wrap; justify-content:flex-end; }
41
- .at-list { display:grid; gap:8px; max-height:240px; overflow:auto; }
42
- .at-row { display:grid; grid-template-columns:54px 1fr auto; gap:9px; align-items:center; padding:9px 10px; border:1px solid #2b806f; border-radius:10px; background:#0a192a; }
43
- .at-row__label { color:var(--accent); font:12px ui-monospace,Consolas,monospace; }
44
- .at-entry { width:100%; min-width:0; border:1px solid #263f5b; border-radius:8px; padding:9px 10px; background:#071321; color:var(--text); font:12px ui-monospace,Consolas,monospace; }
45
- .at-entry:focus, .proxy-pool-input:focus, input:focus { outline:none; border-color:var(--blue); box-shadow:0 0 0 3px #70b7ff22; }
46
- .at-row__remove { border:0; border-radius:8px; padding:7px 9px; color:#ff9aaa; background:#3a1e2c; cursor:pointer; }
47
- .proxy-pool-section { margin-top:14px; }
48
- .dual-proxy-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
49
- .proxy-pool-card { padding:13px; border:1px solid #263f5b; border-radius:13px; background:#091728; }
50
- .proxy-pool-head { display:flex; justify-content:space-between; align-items:center; gap:8px; }
51
- .proxy-pool-card small, .proxy-pool-note { color:var(--muted); }
52
- .proxy-pool-card small { display:block; margin:5px 0 9px; }
53
- .proxy-pool-input { width:100%; min-height:120px; resize:vertical; border:1px solid #223b58; border-radius:11px; padding:12px; background:#071321; color:var(--text); font:12px/1.5 ui-monospace,Consolas,monospace; }
54
- .proxy-pool-note { margin-top:9px; font-size:12px; }
55
- .action-row { display:flex; align-items:center; gap:10px; margin-top:16px; padding:12px; border:1px solid #253d59; border-radius:15px; background:#0c1b2d; }
56
- .concurrency-control { display:flex; align-items:center; gap:8px; margin-right:auto; color:var(--muted); }
57
- input { border:1px solid #2a4665; border-radius:9px; padding:9px 10px; background:#081626; color:var(--text); }
58
- .concurrency-control input { width:66px; }
59
- button { border:0; border-radius:10px; padding:11px 16px; color:#04101b; background:linear-gradient(100deg,#5bdcbb,#65b1ff); cursor:pointer; font-weight:900; white-space:nowrap; }
60
- button.secondary { color:var(--text); background:#233a57; }
61
- button.small { padding:7px 10px; font-size:12px; }
62
- button:disabled { opacity:.42; cursor:not-allowed; }
63
- .progress-wrap { margin:15px 0 16px; }
64
- .progress-meta { display:flex; justify-content:space-between; color:var(--muted); font-size:13px; margin-bottom:6px; }
65
- .progress-track { height:8px; overflow:hidden; border-radius:99px; background:#0a1422; }
66
- .progress-track i { display:block; width:0; height:100%; border-radius:inherit; background:linear-gradient(90deg,#61dfbd,#70b7ff); transition:width .25s ease; }
67
- .result-section { min-height:190px; }
68
- .mini-actions { display:flex; gap:7px; flex-wrap:wrap; justify-content:flex-end; }
69
- .task-rows { display:grid; gap:8px; }
70
- .task-row { display:grid; grid-template-columns:1fr auto; gap:10px; align-items:center; padding:12px 13px; border:1px solid #29435f; border-radius:11px; background:#091728; }
71
- .task-row.is-error { border-color:#814055; }
72
- .task-row__account { font-weight:800; }
73
- .task-row__stage { margin-top:4px; color:var(--muted); font-size:13px; }
74
- .task-row__link { margin-top:5px; color:var(--accent); word-break:break-all; font:12px ui-monospace,Consolas,monospace; }
75
- .batch-summary { margin-top:14px; padding:14px 16px; border:1px solid #814055; border-radius:12px; background:#091728; color:#ff7186; font-weight:800; }
76
- .batch-summary.is-success { border-color:#2b806f; color:#61dfbd; }
77
- .batch-summary.is-stopped { border-color:#806b2b; color:#ffc966; }
78
- @media(max-width:820px){ .setup-grid,.dual-proxy-grid { grid-template-columns:1fr; } .action-row { flex-wrap:wrap; } .concurrency-control { width:100%; margin-right:0; } }
79
- @media(max-width:560px){ .shell { width:min(100% - 16px,1180px); padding-top:25px; } .batch-card { padding:12px; } .steps { grid-template-columns:repeat(2,1fr); } .card-fields-grid,.billing-grid { grid-template-columns:1fr; } .billing-field.billing-wide { grid-column:span 1; } .at-row { grid-template-columns:45px 1fr auto; } }
80
-
81
- /* account import/list workflow */
82
- .account-import-input { width:100%; min-height:158px; resize:vertical; border:1px solid #2b806f; border-radius:12px; padding:13px; background:#071321; color:var(--text); font:12px/1.55 ui-monospace,Consolas,monospace; }
83
- .account-import-input:focus { outline:none; border-color:var(--blue); box-shadow:0 0 0 3px #70b7ff22; }
84
- .import-actions { display:flex; gap:9px; margin-top:11px; flex-wrap:wrap; }
85
- .account-list-actions { align-items:center; }
86
- .export-csv-button { border:1px solid #d7dcd5; border-radius:12px; background:#f7f8f4; color:#52605a; box-shadow:none; }
87
- .export-csv-button:hover { background:#fff; }
88
- .select-all-control { display:inline-flex; align-items:center; gap:7px; color:var(--muted); font-weight:700; }
89
- .select-all-control input,.account-select { width:17px; height:17px; accent-color:var(--accent); }
90
- .account-empty { padding:32px 14px; text-align:center; color:var(--muted); border:1px dashed #29435f; border-radius:12px; }
91
- .account-row { grid-template-columns:auto minmax(0,1fr) auto; align-items:center; }
92
- .account-row__summary { display:grid; grid-template-columns:minmax(360px,32%) minmax(300px,1fr) auto; gap:14px; align-items:center; min-width:0; }
93
- .task-row__account { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
94
- .account-row__current-step { min-width:0; margin:0; overflow:hidden; color:#91abc5; text-overflow:ellipsis; white-space:nowrap; }
95
- .account-row__current-step.is-error { color:var(--danger); }
96
- button.task-row__link { display:inline; margin:0; padding:0; border:0; border-radius:0; background:none; color:var(--accent); font:12px ui-monospace,Consolas,monospace; white-space:nowrap; }
97
- button.task-row__link:hover { text-decoration:underline; }
98
- .account-row-actions { display:flex; align-items:center; gap:9px; }
99
- .account-row-actions .at-row__remove { padding:8px 11px; }
100
- @media(max-width:680px){ .account-row { grid-template-columns:auto 1fr; } .account-row__summary { grid-template-columns:1fr; gap:3px; } .account-row-actions { grid-column:2; justify-content:flex-start; } }
101
- .task-row__proxy { margin-top:5px; color:#7fa4c5; font:11px ui-monospace,Consolas,monospace; word-break:break-all; }
102
- .task-row__billing { margin-top:6px; color:#f4ca72; font:11px ui-monospace,Consolas,monospace; word-break:break-word; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/direct-bind.js DELETED
@@ -1,1218 +0,0 @@
1
- (function () {
2
- 'use strict';
3
-
4
- const $ = (id) => document.getElementById(id);
5
- const PROXY_DRAFT_KEY = 'direct-bind:proxy-draft:v5';
6
- const ACCOUNT_LIST_KEY = 'direct-bind:account-list:v2';
7
- const CARD_DECLINE_MESSAGE = '绑卡未完成:发卡行拒绝了卡片,账号没有新增支付方式。';
8
- const TASK_POLL_MS = 400;
9
- const MAX_BATCH_CONCURRENCY = 50;
10
- const MAX_PROXY_FALLBACKS = 4;
11
- const ACCOUNT_SAVE_DEBOUNCE_MS = 120;
12
- let stripeJsPromise = null;
13
- let accountSaveTimer = 0;
14
- let accountRenderFrame = 0;
15
- const billingFetchPromises = new Map();
16
- const state = {
17
- stripe: null,
18
- publishableKey: '',
19
- elements: {},
20
- complete: { number: false, expiry: false, cvc: false },
21
- mounted: false,
22
- running: false,
23
- stop: false,
24
- accounts: [],
25
- nextId: 1,
26
- bindProxyCursor: 0,
27
- promoProxyCursor: 0,
28
- };
29
-
30
- // Open-source cleanup migration: discard drafts created by earlier private
31
- // builds, which may contain access tokens, proxy credentials and task state.
32
- try {
33
- for (let index = localStorage.length - 1; index >= 0; index -= 1) {
34
- const key = localStorage.key(index) || '';
35
- if (key.startsWith('direct-bind:') && ![PROXY_DRAFT_KEY, ACCOUNT_LIST_KEY].includes(key)) {
36
- localStorage.removeItem(key);
37
- }
38
- }
39
- } catch (_) {}
40
-
41
- function splitValues(value) {
42
- return [...new Set(String(value || '').split(/[\r\n,;]+/).map((item) => item.trim()).filter(Boolean))];
43
- }
44
-
45
- function parseProxyPool(value) {
46
- const source = String(value || '').trim();
47
- if (!source) return [];
48
- let values = [];
49
- if (source.startsWith('[')) {
50
- try {
51
- const parsed = JSON.parse(source);
52
- if (Array.isArray(parsed)) values = parsed;
53
- } catch (_) {}
54
- }
55
- if (!values.length) values = source.split(/[\s,;,;]+/);
56
- return [...new Set(values
57
- .map((item) => String(item || '').trim().replace(/^["']|["']$/g, ''))
58
- .filter(Boolean))].slice(0, 500);
59
- }
60
-
61
- function extractTokens(text) {
62
- const source = String(text || '');
63
- const namedAccessTokens = [...source.matchAll(
64
- /["']access_token["']\s*:\s*["'](eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*)["']/gi,
65
- )].map((match) => match[1]);
66
- if (namedAccessTokens.length) return [...new Set(namedAccessTokens.filter((token) => decodeAccount(token).accountId))];
67
- const jwtMatches = source.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g);
68
- const candidates = jwtMatches?.length
69
- ? [...new Set(jwtMatches)]
70
- : splitValues(source).map((item) => item.replace(/^["']|["']$/g, '')).filter(Boolean);
71
- return candidates.filter((token) => Boolean(decodeAccount(token).accountId));
72
- }
73
-
74
- function decodeAccount(token) {
75
- try {
76
- const part = String(token).split('.')[1];
77
- if (!part) return {};
78
- const raw = part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '=');
79
- const claims = JSON.parse(decodeURIComponent(Array.from(atob(raw), (ch) => `%${ch.charCodeAt(0).toString(16).padStart(2, '0')}`).join('')));
80
- const profile = claims['https://api.openai.com/profile'] || {};
81
- const auth = claims['https://api.openai.com/auth'] || {};
82
- return {
83
- email: String(profile.email || claims.email || ''),
84
- accountId: String(auth.chatgpt_account_id || auth.account_id || claims.chatgpt_account_id || claims.account_id || ''),
85
- };
86
- } catch (_) {
87
- return {};
88
- }
89
- }
90
-
91
- function maskToken(value) {
92
- const text = String(value || '');
93
- return text.length > 24 ? `${text.slice(0, 12)}…${text.slice(-8)}` : text;
94
- }
95
-
96
- async function copyText(value) {
97
- const text = String(value || '').trim();
98
- if (!text) return false;
99
- try {
100
- await navigator.clipboard.writeText(text);
101
- return true;
102
- } catch (_) {
103
- const field = document.createElement('textarea');
104
- field.value = text;
105
- field.setAttribute('readonly', '');
106
- field.style.position = 'fixed';
107
- field.style.opacity = '0';
108
- document.body.appendChild(field);
109
- field.select();
110
- const copied = document.execCommand('copy');
111
- field.remove();
112
- return copied;
113
- }
114
- }
115
-
116
- function csvCell(value) {
117
- return `"${String(value ?? '').replace(/"/g, '""')}"`;
118
- }
119
-
120
- function exportAccountsCsv() {
121
- if (!state.accounts.length) return false;
122
- const rows = [
123
- ['账号', '账号ID', '状态', '当前步骤', 'Checkout链接', '错误'],
124
- ...state.accounts.map((account) => [
125
- account.email || '',
126
- account.accountId || '',
127
- accountStatusLabel(account),
128
- account.stage || '',
129
- account.link || '',
130
- account.error || '',
131
- ]),
132
- ];
133
- const csv = `\uFEFF${rows.map((row) => row.map(csvCell).join(',')).join('\r\n')}`;
134
- const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }));
135
- const download = document.createElement('a');
136
- const stamp = new Date().toISOString().replace(/[:.]/g, '-');
137
- download.href = url;
138
- download.download = `账号任务-${stamp}.csv`;
139
- document.body.appendChild(download);
140
- download.click();
141
- download.remove();
142
- window.setTimeout(() => URL.revokeObjectURL(url), 1000);
143
- return true;
144
- }
145
-
146
- function translateError(value) {
147
- const text = String(value || '').replace(/\s+/g, ' ').trim();
148
- const lower = text.toLowerCase();
149
- if (!text) return '任务执行失败。';
150
- if (lower.includes('curl: (35)') || lower.includes('tls connect error') || lower.includes('openssl_internal:invalid library')) {
151
- return '代理 TLS 握手失败,请检查代理协议、地址、端口和有效期。';
152
- }
153
- if (lower.includes('impersonating') && lower.includes('is not supported')) {
154
- return '当前浏览器 TLS 指纹版本不受运行库支持,系统已自动切换兼容版本,请重试。';
155
- }
156
- if (lower.includes('card_declined') || lower.includes('your card was declined')) {
157
- return CARD_DECLINE_MESSAGE;
158
- }
159
- if (lower.includes('secret_key_required')) {
160
- return '支付接口权限不匹配,当前步骤没有获得所需的服务端权限。';
161
- }
162
- if (lower.includes('invalidated') || lower.includes('token expired') || lower.includes('at invalid') || lower.includes('http 401')) {
163
- return '账号凭证已失效,请删除后重新导入。';
164
- }
165
- if (lower.includes('at does not contain an account id') || lower.includes('at 缺少账号 id')) {
166
- return '该条不是可用的 AT(缺少账号 ID),请导入 access_token。';
167
- }
168
- if (lower.includes('missing or invalid paymentmethod') || lower.includes('paymentmethod 创建失败')) {
169
- return '卡片支付方式创建失败,请重新填写卡片。';
170
- }
171
- if (lower.includes('proxy') && (lower.includes('connect') || lower.includes('failed') || lower.includes('error'))) {
172
- return '代理连接失败,请检查代理格式、节点状态和网络。';
173
- }
174
- if (lower.includes('timeout') || lower.includes('timed out') || lower.includes('任务超时')) {
175
- return '请求超时,请检查代理速度后重试。';
176
- }
177
- if (lower.includes('http 403')) return '请求被拒绝(HTTP 403),请检查账号状态和接口权限。';
178
- if (lower.includes('http 402')) return '支付请求被拒绝(HTTP 402),请检查卡片状态。';
179
- if (lower.includes('failed to perform, curl')) return '网络请求失败,请检查代理和本机网络。';
180
- if (/[\u4e00-\u9fff]/.test(text)) return text;
181
- return `任务失败:${text.slice(0, 220)}`;
182
- }
183
-
184
- function normalizedBilling(value = {}, email = '') {
185
- return {
186
- name: String(value.name || '').trim(),
187
- line1: String(value.line1 || '').trim(),
188
- line2: String(value.line2 || '').trim(),
189
- city: String(value.city || '').trim(),
190
- state: String(value.state || '').trim().toUpperCase(),
191
- postal_code: String(value.postal_code || '').trim().toUpperCase(),
192
- country: String(value.country || 'US').trim().toUpperCase(),
193
- email: String(email || value.email || '').trim(),
194
- };
195
- }
196
-
197
- function billingIssues(billing) {
198
- const issues = [];
199
- if (!billing.name) issues.push('持卡人姓名');
200
- if (!billing.line1) issues.push('账单地址');
201
- if (!billing.city) issues.push('城市');
202
- if (!/^[A-Z]{2}$/.test(billing.country)) issues.push('两位国家代码');
203
- if (!billing.postal_code) issues.push('邮编');
204
- if (billing.country === 'US') {
205
- if (!billing.state) issues.push('州代码');
206
- if (!/^\d{5}(?:-\d{4})?$/.test(billing.postal_code)) issues.push('美国 ZIP 格式');
207
- }
208
- return issues;
209
- }
210
-
211
- function ensureStripeJs() {
212
- if (typeof window.Stripe === 'function') return Promise.resolve(window.Stripe);
213
- if (stripeJsPromise) return stripeJsPromise;
214
- stripeJsPromise = new Promise((resolve, reject) => {
215
- document.querySelectorAll('script[data-direct-stripe-loader]').forEach((node) => node.remove());
216
- const script = document.createElement('script');
217
- script.src = 'https://js.stripe.com/v3/';
218
- script.async = true;
219
- script.dataset.directStripeLoader = '1';
220
- const timer = window.setTimeout(() => {
221
- script.remove();
222
- reject(new Error('Stripe 安全组件加载超时,请检查浏览器网络或拦截扩展后重试'));
223
- }, 20000);
224
- script.addEventListener('load', () => {
225
- window.clearTimeout(timer);
226
- if (typeof window.Stripe === 'function') resolve(window.Stripe);
227
- else reject(new Error('Stripe 安全组件脚本已返回,但组件没有初始化'));
228
- }, { once: true });
229
- script.addEventListener('error', () => {
230
- window.clearTimeout(timer);
231
- reject(new Error('Stripe 安全组件加载失败,请检查浏览器网络或拦截扩展后重试'));
232
- }, { once: true });
233
- document.head.appendChild(script);
234
- }).catch((error) => {
235
- stripeJsPromise = null;
236
- throw error;
237
- });
238
- return stripeJsPromise;
239
- }
240
-
241
- function isStoredCardDecline(value) {
242
- const text = String(value || '').toLowerCase();
243
- return text.includes('card_declined')
244
- || text.includes('your card was declined')
245
- || text.includes('银行卡被拒绝')
246
- || text.includes('发卡行拒绝');
247
- }
248
-
249
- async function fetchBillingForAccount(account) {
250
- const key = account.id || account.token;
251
- if (billingFetchPromises.has(key)) return billingFetchPromises.get(key);
252
- const request = (async () => {
253
- const response = await fetch('/api/address', {
254
- method: 'POST',
255
- headers: { 'Content-Type': 'application/json' },
256
- body: '{}',
257
- });
258
- const payload = await response.json().catch(() => ({}));
259
- if (!response.ok || payload.ok === false || !payload.billing) {
260
- throw new Error(payload.error || `地址获取失败:HTTP ${response.status}`);
261
- }
262
- account.billing = normalizedBilling(payload.billing, account.email);
263
- account.billingMode = 'auto';
264
- return true;
265
- })().finally(() => billingFetchPromises.delete(key));
266
- billingFetchPromises.set(key, request);
267
- return request;
268
- }
269
-
270
- async function assignBillingAddresses(accounts) {
271
- if (!accounts.length) return;
272
- $('billingAutoStatus').className = 'billing-auto-status is-test';
273
- $('billingAutoStatus').textContent = `正在为 ${accounts.length} 个账号分别获取 DE 账单地址…`;
274
- let cursor = 0;
275
- async function worker() {
276
- while (cursor < accounts.length) {
277
- const account = accounts[cursor++];
278
- await fetchBillingForAccount(account);
279
- }
280
- }
281
- await Promise.all(Array.from({ length: Math.min(8, accounts.length) }, worker));
282
- renderAccounts();
283
- refresh();
284
- $('billingAutoStatus').textContent = `已为 ${accounts.length} 个账号分别分配接口账单地址。`;
285
- appendLog(`${accounts.length} 个账号的独立 DE 接口地址已就绪。`);
286
- }
287
-
288
- function setStep(id, status) {
289
- const node = $(id);
290
- if (node) node.className = status || '';
291
- }
292
-
293
- function log(message) {
294
- void message;
295
- }
296
-
297
- function appendLog(message) {
298
- void message;
299
- }
300
-
301
- function hideBatchSummary() {
302
- const node = $('batchSummary');
303
- node.hidden = true;
304
- node.className = 'batch-summary';
305
- node.textContent = '';
306
- }
307
-
308
- function showBatchSummary(label, success, failed, stopped = false) {
309
- const node = $('batchSummary');
310
- node.hidden = false;
311
- node.className = `batch-summary ${stopped ? 'is-stopped' : failed ? '' : 'is-success'}`;
312
- node.textContent = stopped
313
- ? `${label}已停止:${success} 个成功,${failed} 个失败或未执行。`
314
- : `${label}完成:${success} 个成功,${failed} 个失败。`;
315
- }
316
-
317
- function saveProxyDraft() {
318
- try {
319
- localStorage.setItem(PROXY_DRAFT_KEY, JSON.stringify({
320
- bind: $('bindProxyPool').value,
321
- promo: $('promoProxyPool').value,
322
- concurrency: $('batchConcurrency').value,
323
- }));
324
- } catch (_) {}
325
- }
326
-
327
- function loadProxyDraft() {
328
- try {
329
- const draft = JSON.parse(localStorage.getItem(PROXY_DRAFT_KEY) || '{}');
330
- if (typeof draft.bind === 'string') $('bindProxyPool').value = draft.bind;
331
- if (typeof draft.promo === 'string') $('promoProxyPool').value = draft.promo;
332
- if (draft.concurrency != null) $('batchConcurrency').value = draft.concurrency;
333
- } catch (_) {}
334
- }
335
-
336
- function saveAccountsNow() {
337
- if (accountSaveTimer) {
338
- window.clearTimeout(accountSaveTimer);
339
- accountSaveTimer = 0;
340
- }
341
- try {
342
- localStorage.setItem(ACCOUNT_LIST_KEY, JSON.stringify({
343
- nextId: state.nextId,
344
- items: state.accounts.map((account) => ({
345
- id: account.id,
346
- token: account.token,
347
- email: account.email || '',
348
- accountId: account.accountId || '',
349
- selected: Boolean(account.selected),
350
- status: account.status || 'idle',
351
- stage: account.stage || '待执行',
352
- error: account.error || '',
353
- link: account.link || '',
354
- taskId: account.taskId || '',
355
- bindProxyLabel: account.bindProxyLabel || '',
356
- promoProxyLabel: account.promoProxyLabel || '',
357
- fingerprint: account.fingerprint || '',
358
- fingerprintId: account.fingerprintId || '',
359
- fingerprintTls: account.fingerprintTls || '',
360
- fingerprintRegion: account.fingerprintRegion || '',
361
- fingerprintTimezone: account.fingerprintTimezone || '',
362
- steps: Array.isArray(account.steps) ? account.steps : [],
363
- billingMode: account.billingMode || '',
364
- billing: account.billing ? normalizedBilling(account.billing, account.email) : null,
365
- })),
366
- }));
367
- } catch (_) {}
368
- }
369
-
370
- function saveAccounts() {
371
- if (accountSaveTimer) window.clearTimeout(accountSaveTimer);
372
- accountSaveTimer = window.setTimeout(saveAccountsNow, ACCOUNT_SAVE_DEBOUNCE_MS);
373
- }
374
-
375
- function scheduleRenderAccounts() {
376
- if (accountRenderFrame) return;
377
- accountRenderFrame = window.requestAnimationFrame(() => {
378
- accountRenderFrame = 0;
379
- renderAccounts();
380
- });
381
- }
382
-
383
- function loadAccounts() {
384
- try {
385
- const saved = JSON.parse(localStorage.getItem(ACCOUNT_LIST_KEY) || '{}');
386
- const items = Array.isArray(saved.items) ? saved.items : [];
387
- state.accounts = items
388
- .filter((item) => item && typeof item.token === 'string' && item.token.trim())
389
- .map((item) => ({ item, decoded: decodeAccount(item.token.trim()) }))
390
- .filter(({ decoded }) => Boolean(decoded.accountId))
391
- .map(({ item, decoded }, index) => ({
392
- id: String(item.id || `account-${index + 1}`),
393
- token: item.token.trim(),
394
- email: String(decoded.email || item.email || ''),
395
- accountId: String(decoded.accountId || item.accountId || ''),
396
- selected: item.selected !== false,
397
- status: ['idle', 'running', 'success', 'error'].includes(item.status) ? item.status : 'idle',
398
- stage: isStoredCardDecline(item.error)
399
- ? '绑卡失败'
400
- : String(item.stage || '待执行').replace(/^注册指纹已就绪$/, '环境已就绪'),
401
- error: isStoredCardDecline(item.error)
402
- ? CARD_DECLINE_MESSAGE
403
- : item.error ? translateError(item.error) : '',
404
- link: String(item.link || ''),
405
- taskId: String(item.taskId || ''),
406
- bindProxyLabel: String(item.bindProxyLabel || ''),
407
- promoProxyLabel: String(item.promoProxyLabel || ''),
408
- fingerprint: String(item.fingerprint || ''),
409
- fingerprintId: String(item.fingerprintId || ''),
410
- fingerprintTls: String(item.fingerprintTls || ''),
411
- fingerprintRegion: String(item.fingerprintRegion || ''),
412
- fingerprintTimezone: String(item.fingerprintTimezone || ''),
413
- steps: Array.isArray(item.steps) ? item.steps.map((step) => ({
414
- key: String(step?.key || ''),
415
- label: String(step?.label || ''),
416
- status: ['pending', 'running', 'done', 'error'].includes(step?.status) ? step.status : 'pending',
417
- detail: step?.status === 'error' && step?.detail
418
- ? translateError(step.detail)
419
- : String(step?.detail || ''),
420
- })) : [],
421
- billingMode: String(item.billingMode || ''),
422
- billing: item.billing && typeof item.billing === 'object'
423
- ? normalizedBilling(item.billing, item.email)
424
- : null,
425
- }));
426
- state.nextId = Math.max(Number(saved.nextId) || 1, state.accounts.length + 1);
427
- if (state.accounts.length !== items.length) saveAccountsNow();
428
- } catch (_) {
429
- state.accounts = [];
430
- state.nextId = 1;
431
- }
432
- }
433
-
434
- function selectedAccounts() {
435
- return state.accounts.filter((account) => account.selected);
436
- }
437
-
438
- function maskProxy(value) {
439
- const text = String(value || '').trim();
440
- if (!text) return '';
441
- try {
442
- const normalized = text.includes('://') ? text : `http://${text}`;
443
- const url = new URL(normalized);
444
- return `${url.protocol}//${url.username ? '***@' : ''}${url.hostname}${url.port ? `:${url.port}` : ''}`;
445
- } catch (_) {
446
- const parts = text.split(':');
447
- return parts.length >= 2 ? `${parts[0]}:${parts[1]}` : '代理节点';
448
- }
449
- }
450
-
451
- function initialAccountSteps(mode) {
452
- const definitions = [
453
- ['proxy', '分配代理'],
454
- ];
455
- if (mode !== 'link_only') definitions.push(['card_method', '生成支付方式']);
456
- definitions.push(['fingerprint', '加载指纹'], ['first_link', '首次提链']);
457
- if (mode === 'bind_only') definitions.push(['bind', '绑卡']);
458
- else if (mode === 'link_pay') definitions.push(
459
- ['payment_prepare', '验证支付方式'],
460
- ['second_link', '刷新支付链接'],
461
- ['payment', '提交支付'],
462
- ['verify', '结果校验'],
463
- );
464
- else if (mode !== 'link_only') definitions.push(
465
- ['bind', '绑卡'],
466
- ['second_link', '二次提链'],
467
- ['payment', '提交支付'],
468
- ['verify', '结果校验'],
469
- );
470
- return definitions.map(([key, label]) => ({
471
- key,
472
- label,
473
- status: key === 'proxy' ? 'done' : 'pending',
474
- detail: key === 'proxy' ? (mode === 'link_only' ? '提链代理已分配' : '双代理已分配') : '等待执行',
475
- }));
476
- }
477
-
478
- function setAccountStep(account, key, status, detail) {
479
- const steps = Array.isArray(account.steps) ? account.steps : [];
480
- let step = steps.find((item) => item.key === key);
481
- if (!step) {
482
- step = { key, label: key, status: 'pending', detail: '等待执行' };
483
- steps.push(step);
484
- }
485
- step.status = status;
486
- step.detail = detail || step.detail;
487
- account.steps = steps;
488
- }
489
-
490
- function failRunningAccountStep(account, detail) {
491
- const steps = Array.isArray(account.steps) ? account.steps : [];
492
- const running = [...steps].reverse().find((step) => step.status === 'running');
493
- if (running) {
494
- running.status = 'error';
495
- running.detail = detail;
496
- }
497
- }
498
-
499
- function assignProxies(accounts, bindPool, promoPool, mode) {
500
- const bindStart = bindPool.length ? state.bindProxyCursor % bindPool.length : 0;
501
- const promoStart = state.promoProxyCursor % promoPool.length;
502
- accounts.forEach((account, index) => {
503
- account.bindProxy = bindPool.length ? bindPool[(bindStart + index) % bindPool.length] : '';
504
- account.promoProxy = promoPool[(promoStart + index) % promoPool.length];
505
- account.bindProxyPool = bindPool.length
506
- ? bindPool.map((_, offset) => bindPool[(bindStart + index + offset) % bindPool.length]).slice(0, MAX_PROXY_FALLBACKS)
507
- : [];
508
- account.promoProxyPool = promoPool
509
- .map((_, offset) => promoPool[(promoStart + index + offset) % promoPool.length])
510
- .slice(0, MAX_PROXY_FALLBACKS);
511
- account.bindProxyLabel = maskProxy(account.bindProxy);
512
- account.promoProxyLabel = maskProxy(account.promoProxy);
513
- account.status = 'running';
514
- account.stage = mode === 'link_only' ? '提链代理分配完成,等待并发启动' : '代理分配完成,等待并发启动';
515
- account.error = '';
516
- account.steps = initialAccountSteps(mode);
517
- });
518
- if (bindPool.length) state.bindProxyCursor = (bindStart + accounts.length) % bindPool.length;
519
- state.promoProxyCursor = (promoStart + accounts.length) % promoPool.length;
520
- renderAccounts();
521
- saveAccounts();
522
- }
523
-
524
- function accountStatusLabel(account) {
525
- if (account.status === 'success') return '完成';
526
- if (account.status === 'error') return '失败';
527
- if (account.status === 'running') return '运行中';
528
- return '待执行';
529
- }
530
-
531
- function renderAccounts() {
532
- if (accountRenderFrame) {
533
- window.cancelAnimationFrame(accountRenderFrame);
534
- accountRenderFrame = 0;
535
- }
536
- const root = $('taskRows');
537
- root.innerHTML = '';
538
- $('accountEmpty').hidden = state.accounts.length > 0;
539
-
540
- state.accounts.forEach((account, index) => {
541
- const row = document.createElement('div');
542
- row.className = `task-row account-row ${account.status === 'error' ? 'is-error' : ''}`;
543
- row.dataset.accountId = account.id;
544
-
545
- const checkbox = document.createElement('input');
546
- checkbox.type = 'checkbox';
547
- checkbox.className = 'account-select';
548
- checkbox.checked = account.selected;
549
- checkbox.disabled = state.running;
550
- checkbox.addEventListener('change', () => {
551
- account.selected = checkbox.checked;
552
- refresh();
553
- renderAccounts();
554
- });
555
-
556
- const meta = document.createElement('div');
557
- meta.className = 'task-row__meta account-row__summary';
558
- const accountName = document.createElement('div');
559
- accountName.className = 'task-row__account';
560
- accountName.textContent = account.email || `账号 ${String(index + 1).padStart(2, '0')}`;
561
- accountName.title = maskToken(account.token);
562
- const stage = document.createElement('div');
563
- stage.className = `task-row__stage account-row__current-step ${account.error ? 'is-error' : ''}`;
564
- const stageLabel = account.stage || '任务失败';
565
- const errorText = String(account.error || '');
566
- stage.textContent = errorText
567
- ? errorText.startsWith(stageLabel) ? errorText : `${stageLabel}:${errorText}`
568
- : account.stage || '待执行';
569
- const diagnostics = [
570
- `AT:${maskToken(account.token)}`,
571
- account.bindProxyLabel ? `绑卡/支付代理:${account.bindProxyLabel}` : '',
572
- account.promoProxyLabel ? `提链代理:${account.promoProxyLabel}` : '',
573
- account.fingerprint ? `指纹:${account.fingerprint}` : '',
574
- account.billing ? `账单:${account.billing.city || ''}, ${account.billing.state || ''} ${account.billing.postal_code || ''}` : '',
575
- ].filter(Boolean);
576
- stage.title = diagnostics.join('\n');
577
- meta.append(accountName, stage);
578
- if (account.link) {
579
- const link = document.createElement('button');
580
- link.type = 'button';
581
- link.className = 'task-row__link';
582
- link.textContent = '复制链接';
583
- link.title = account.link;
584
- link.addEventListener('click', async () => {
585
- const copied = await copyText(account.link);
586
- link.textContent = copied ? '已复制' : '复制失败';
587
- window.setTimeout(() => {
588
- if (link.isConnected) link.textContent = '复制链接';
589
- }, 1200);
590
- });
591
- meta.appendChild(link);
592
- }
593
-
594
- const actions = document.createElement('div');
595
- actions.className = 'account-row-actions';
596
- const tag = document.createElement('span');
597
- tag.className = 'tag';
598
- tag.textContent = accountStatusLabel(account);
599
- const remove = document.createElement('button');
600
- remove.type = 'button';
601
- remove.className = 'at-row__remove';
602
- remove.textContent = '删除';
603
- remove.disabled = state.running;
604
- remove.addEventListener('click', () => {
605
- state.accounts = state.accounts.filter((item) => item.id !== account.id);
606
- renderAccounts();
607
- refresh();
608
- appendLog('账号已从列表删除。');
609
- });
610
- actions.append(tag, remove);
611
- row.append(checkbox, meta, actions);
612
- root.appendChild(row);
613
- });
614
-
615
- const selected = selectedAccounts().length;
616
- $('selectAllAccounts').checked = Boolean(state.accounts.length) && selected === state.accounts.length;
617
- $('selectAllAccounts').indeterminate = selected > 0 && selected < state.accounts.length;
618
- saveAccounts();
619
- }
620
-
621
- async function allocateAccountFingerprint(account, { quiet = false, deferRender = false } = {}) {
622
- const previousStage = account.stage;
623
- if (account.status === 'idle') account.stage = '正在分配注册指纹';
624
- if (!deferRender) scheduleRenderAccounts();
625
- try {
626
- const bind = parseProxyPool($('bindProxyPool').value);
627
- const accountIndex = Math.max(0, state.accounts.indexOf(account));
628
- const response = await fetch('/api/fingerprint/allocate', {
629
- method: 'POST',
630
- headers: { 'Content-Type': 'application/json' },
631
- body: JSON.stringify({
632
- access_token: account.token,
633
- bind_proxy_pool: bind.length ? [bind[accountIndex % bind.length]] : [],
634
- }),
635
- });
636
- const payload = await response.json().catch(() => ({}));
637
- if (!response.ok || payload.ok === false) {
638
- throw new Error(payload.error || `指纹分配失败:HTTP ${response.status}`);
639
- }
640
- account.email = payload.email || account.email;
641
- account.accountId = payload.account_id || account.accountId;
642
- account.fingerprint = String(payload.fingerprint || '');
643
- account.fingerprintId = String(payload.fingerprint_id || '');
644
- account.fingerprintTls = String(payload.tls || '');
645
- account.fingerprintRegion = String(payload.region || '');
646
- account.fingerprintTimezone = String(payload.timezone || '');
647
- if (account.status === 'idle') account.stage = '环境已就绪';
648
- account.error = '';
649
- if (!quiet) appendLog(`${account.email || account.id}:注册指纹 ${account.fingerprintId} 已分配。`);
650
- } catch (error) {
651
- if (account.status === 'idle') account.stage = previousStage || '待执行';
652
- account.error = translateError(error?.message || error);
653
- }
654
- saveAccounts();
655
- if (!deferRender) scheduleRenderAccounts();
656
- }
657
-
658
- async function allocateFingerprints(accounts, { quiet = false } = {}) {
659
- if (!accounts.length) return;
660
- const previousStages = new Map();
661
- accounts.forEach((account) => {
662
- previousStages.set(account.id, account.stage);
663
- if (account.status === 'idle') account.stage = '正在批量分配注册指纹';
664
- });
665
- scheduleRenderAccounts();
666
- const bind = parseProxyPool($('bindProxyPool').value);
667
- for (let offset = 0; offset < accounts.length; offset += 500) {
668
- const chunk = accounts.slice(offset, offset + 500);
669
- try {
670
- const response = await fetch('/api/fingerprint/allocate-batch', {
671
- method: 'POST',
672
- headers: { 'Content-Type': 'application/json' },
673
- body: JSON.stringify({
674
- accounts: chunk.map((account) => {
675
- const accountIndex = Math.max(0, state.accounts.indexOf(account));
676
- return {
677
- client_id: account.id,
678
- access_token: account.token,
679
- bind_proxy_pool: bind.length ? [bind[accountIndex % bind.length]] : [],
680
- };
681
- }),
682
- }),
683
- });
684
- const payload = await response.json().catch(() => ({}));
685
- if (!response.ok || payload.ok === false || !Array.isArray(payload.items)) {
686
- throw new Error(payload.error || `批量指纹分配失败:HTTP ${response.status}`);
687
- }
688
- const byId = new Map(payload.items.map((item) => [String(item?.client_id || ''), item]));
689
- chunk.forEach((account) => {
690
- const item = byId.get(account.id) || {};
691
- if (item.ok === false || !item.fingerprint_id) {
692
- account.stage = previousStages.get(account.id) || '待执行';
693
- account.error = translateError(item.error || '批量指纹分配结果缺失');
694
- return;
695
- }
696
- account.email = item.email || account.email;
697
- account.accountId = item.account_id || account.accountId;
698
- account.fingerprint = String(item.fingerprint || '');
699
- account.fingerprintId = String(item.fingerprint_id || '');
700
- account.fingerprintTls = String(item.tls || '');
701
- account.fingerprintRegion = String(item.region || '');
702
- account.fingerprintTimezone = String(item.timezone || '');
703
- if (account.status === 'idle') account.stage = '环境已就绪';
704
- account.error = '';
705
- });
706
- } catch (error) {
707
- const message = translateError(error?.message || error);
708
- chunk.forEach((account) => {
709
- account.stage = previousStages.get(account.id) || '待执行';
710
- account.error = message;
711
- });
712
- }
713
- }
714
- saveAccounts();
715
- renderAccounts();
716
- refresh();
717
- if (!quiet) appendLog(`${accounts.length} 个账号的固定指纹已批量分配。`);
718
- }
719
-
720
- async function hydrateMissingFingerprints() {
721
- // 已落盘且为 US 的兼容指纹直接复用;只修复缺失或旧 TR/chrome144 数据。
722
- const pending = state.accounts.filter((account) => (
723
- !account.fingerprintId
724
- || !account.fingerprintTls
725
- || String(account.fingerprintRegion || '').toUpperCase() !== 'US'
726
- || String(account.fingerprintTls || '').toLowerCase() === 'chrome144'
727
- || /chrome\/144/i.test(String(account.fingerprint || ''))
728
- ));
729
- if (!pending.length) return;
730
- await allocateFingerprints(pending, { quiet: true });
731
- if (pending.length) appendLog(`已同步 ${pending.length} 个账号的注册指纹与 TLS 兼容版本。`);
732
- }
733
-
734
- async function hydrateMissingBillingAddresses() {
735
- const pending = state.accounts.filter((account) => (
736
- account.billingMode !== 'auto'
737
- || billingIssues(normalizedBilling(account.billing || {}, account.email)).length > 0
738
- ));
739
- if (pending.length) await assignBillingAddresses(pending);
740
- }
741
-
742
- async function importAccounts(text) {
743
- const values = extractTokens(text);
744
- const existing = new Set(state.accounts.map((account) => account.token));
745
- const imported = [];
746
- let added = 0;
747
- values.forEach((token) => {
748
- if (!token || existing.has(token)) return;
749
- const decoded = decodeAccount(token);
750
- state.accounts.push({
751
- id: `account-${state.nextId++}`,
752
- token,
753
- email: decoded.email || '',
754
- accountId: decoded.accountId || '',
755
- selected: true,
756
- status: 'idle',
757
- stage: '待执行',
758
- error: '',
759
- link: '',
760
- taskId: '',
761
- bindProxyLabel: '',
762
- promoProxyLabel: '',
763
- fingerprint: '',
764
- fingerprintId: '',
765
- fingerprintTls: '',
766
- fingerprintRegion: '',
767
- fingerprintTimezone: '',
768
- steps: [],
769
- billingMode: '',
770
- billing: null,
771
- });
772
- imported.push(state.accounts[state.accounts.length - 1]);
773
- existing.add(token);
774
- added += 1;
775
- });
776
- $('accountImportInput').value = '';
777
- updateImportCount();
778
- renderAccounts();
779
- refresh();
780
- log(added ? `已导入 ${added} 个账号,导入框已清空。` : '没有发现新的账号。');
781
- if (imported.length) {
782
- await Promise.all([
783
- allocateFingerprints(imported),
784
- assignBillingAddresses(imported),
785
- ]);
786
- }
787
- }
788
-
789
- function updateImportCount() {
790
- $('atCount').textContent = `${extractTokens($('accountImportInput').value).length} 条待导入`;
791
- }
792
-
793
- function updateAccount(account, values) {
794
- Object.assign(account, values);
795
- saveAccounts();
796
- scheduleRenderAccounts();
797
- }
798
-
799
- function refresh() {
800
- const bind = parseProxyPool($('bindProxyPool').value);
801
- const promo = parseProxyPool($('promoProxyPool').value);
802
- const selected = selectedAccounts();
803
- const billingMissingAccounts = state.publishableKey
804
- ? selected.filter((account) => billingIssues(normalizedBilling(account.billing || {}, account.email)).length > 0)
805
- : [];
806
- $('bindProxyCount').textContent = `${bind.length} PROXY`;
807
- $('promoProxyCount').textContent = `${promo.length} PROXY`;
808
- const basicReady = Boolean(selected.length && bind.length && promo.length);
809
- const linkOnlyReady = Boolean(selected.length && promo.length);
810
- const cardInputReady = state.mounted && Object.values(state.complete).every(Boolean);
811
- const billingReady = !state.publishableKey || billingMissingAccounts.length === 0;
812
- const ready = basicReady && cardInputReady && billingReady;
813
- $('loadCardButton').disabled = state.mounted || state.running;
814
- ['batchBindLinkButton', 'fullFlowButton', 'linkPayButton'].forEach((id) => {
815
- $(id).disabled = !ready || state.running;
816
- });
817
- $('linkOnlyButton').disabled = !linkOnlyReady || state.running;
818
- $('deleteSelectedButton').disabled = state.running || !selected.length;
819
- $('exportCsvButton').disabled = !state.accounts.length;
820
- $('clearButton').disabled = state.running || !state.accounts.length;
821
- $('selectAllAccounts').disabled = state.running || !state.accounts.length;
822
- $('cardReady').className = `inline-state ${ready ? 'ok' : ''}`;
823
- if (ready) $('cardReady').textContent = `卡片输入已就绪;已选择 ${selected.length} 个账号。`;
824
- else if (!basicReady) $('cardReady').textContent = '请先导入并选择账号,填写双代理池后再加载卡片。';
825
- else if (!billingReady) $('cardReady').textContent = `还有 ${billingMissingAccounts.length} 个账号的账单地址未就绪。`;
826
- return { accounts: selected, bind, promo, basicReady, linkOnlyReady, cardInputReady, billingReady, billingMissingAccounts, ready };
827
- }
828
-
829
- async function mountCard() {
830
- const data = refresh();
831
- if (state.mounted) return;
832
- if (!data.basicReady) {
833
- const missing = [];
834
- if (!data.accounts.length) missing.push('已选择账号');
835
- if (!data.bind.length) missing.push('绑卡代理池');
836
- if (!data.promo.length) missing.push('提链代理池');
837
- $('cardReady').className = 'inline-state error';
838
- $('cardReady').textContent = `加载卡片前还缺少:${missing.join('、')}`;
839
- appendLog($('cardReady').textContent);
840
- return;
841
- }
842
- $('loadCardButton').disabled = true;
843
- $('cardReady').textContent = '正在并行加载 Stripe、安全地址与 Checkout…';
844
- try {
845
- const missingBilling = state.accounts.filter((account) => (
846
- billingIssues(normalizedBilling(account.billing || {}, account.email)).length > 0
847
- ));
848
- const previewBind = data.bind[state.bindProxyCursor % data.bind.length];
849
- const previewPromo = data.promo[state.promoProxyCursor % data.promo.length];
850
- const checkoutPromise = fetch('/api/card-bind/session', {
851
- method: 'POST',
852
- headers: { 'Content-Type': 'application/json' },
853
- body: JSON.stringify({
854
- access_token: data.accounts[0].token,
855
- bind_proxy_pool: [previewBind],
856
- promo_proxy_pool: [previewPromo],
857
- }),
858
- });
859
- const billingPromise = assignBillingAddresses(missingBilling).catch((error) => {
860
- const message = translateError(error.message);
861
- $('billingAutoStatus').className = 'billing-auto-status error';
862
- $('billingAutoStatus').textContent = `自动账单地址获取失败:${message}`;
863
- appendLog(message);
864
- return false;
865
- });
866
- const [, response] = await Promise.all([
867
- ensureStripeJs(),
868
- checkoutPromise,
869
- ]);
870
- void billingPromise;
871
- const payload = await response.json().catch(() => ({}));
872
- if (!response.ok || payload.ok === false) throw new Error(payload.error || `预检失败:HTTP ${response.status}`);
873
- data.accounts[0].fingerprint = String(payload.fingerprint || data.accounts[0].fingerprint || '');
874
- data.accounts[0].fingerprintId = String(payload.fingerprint_id || data.accounts[0].fingerprintId || '');
875
- data.accounts[0].fingerprintTls = String(payload.fingerprint_tls || data.accounts[0].fingerprintTls || '');
876
- data.accounts[0].fingerprintRegion = String(payload.fingerprint_region || data.accounts[0].fingerprintRegion || '');
877
- data.accounts[0].fingerprintTimezone = String(payload.fingerprint_timezone || data.accounts[0].fingerprintTimezone || '');
878
- saveAccounts();
879
- renderAccounts();
880
- const key = String(payload.publishable_key || '');
881
- if (!key.startsWith('pk_')) throw new Error('Checkout 没有返回有效的 Stripe 公钥');
882
- state.publishableKey = key;
883
- state.stripe = window.Stripe(key);
884
- const elements = state.stripe.elements();
885
- const style = {
886
- base: { fontSize: '15px', color: '#e7f0fb', '::placeholder': { color: '#70869e' } },
887
- invalid: { color: '#ff7186' },
888
- };
889
- state.elements.number = elements.create('cardNumber', { showIcon: true, style });
890
- state.elements.expiry = elements.create('cardExpiry', { style });
891
- state.elements.cvc = elements.create('cardCvc', { style });
892
- [['number', 'cardNumberElement'], ['expiry', 'cardExpiryElement'], ['cvc', 'cardCvcElement']].forEach(([name, id]) => {
893
- state.elements[name].mount(`#${id}`);
894
- state.elements[name].on('change', (event) => {
895
- state.complete[name] = Boolean(event.complete);
896
- if (event.error) $('cardReady').textContent = translateError(event.error.message);
897
- refresh();
898
- });
899
- });
900
- state.mounted = true;
901
- setStep('stepCard', 'done');
902
- setStep('stepAt', 'active');
903
- $('cardReady').textContent = `安全卡片输入框已加载:${payload.country || 'PH'}/${payload.currency || 'PHP'}`;
904
- appendLog('卡片输入框已加载,后续任务由独立 HTTP 服务处理。');
905
- refresh();
906
- } catch (error) {
907
- const message = translateError(error.message);
908
- $('loadCardButton').disabled = false;
909
- $('cardReady').className = 'inline-state error';
910
- $('cardReady').textContent = message;
911
- appendLog(message);
912
- }
913
- }
914
-
915
- async function createPaymentMethod(account) {
916
- if (!state.stripe || !state.elements.number) throw new Error('卡片输入框尚未加载');
917
- const billing = normalizedBilling(account?.billing || {}, account?.email || '');
918
- const issues = billingIssues(billing);
919
- if (issues.length) throw new Error(`${account?.email || account?.id || '当前账号'} 的账单地址缺少:${issues.join('、')}`);
920
- const result = await state.stripe.createPaymentMethod({
921
- type: 'card',
922
- card: state.elements.number,
923
- billing_details: {
924
- name: billing.name,
925
- email: billing.email || undefined,
926
- address: {
927
- line1: billing.line1,
928
- line2: billing.line2 || undefined,
929
- city: billing.city,
930
- state: billing.state || undefined,
931
- postal_code: billing.postal_code,
932
- country: billing.country,
933
- },
934
- },
935
- });
936
- if (result.error) throw new Error(result.error.message || 'PaymentMethod 创建失败');
937
- const paymentMethod = result.paymentMethod || {};
938
- if (!paymentMethod.id) throw new Error('PaymentMethod 创建失败');
939
- return { id: paymentMethod.id, last4: paymentMethod.card?.last4 || '', billing };
940
- }
941
-
942
- async function prepareAccountCard(account) {
943
- updateAccount(account, { status: 'running', stage: '正在准备同批同步起跑', error: '' });
944
- setAccountStep(account, 'card_method', 'running', '正在通过安全卡片输入框生成支付方式');
945
- renderAccounts();
946
- const browserCard = await createPaymentMethod(account);
947
- setAccountStep(account, 'card_method', 'done', `支付方式已生成 ····${browserCard.last4 || ''}`);
948
- updateAccount(account, { stage: '支付方式已生成,等待同批账号同步起跑' });
949
- return browserCard;
950
- }
951
-
952
- function accountFlowPayload(account, mode, browserCard) {
953
- const payload = {
954
- access_token: account.token,
955
- flow_mode: mode,
956
- promo_proxy_pool: account.promoProxyPool?.length ? account.promoProxyPool : [account.promoProxy],
957
- };
958
- if (mode !== 'link_only') Object.assign(payload, {
959
- payment_method_id: browserCard.id,
960
- card_last4: browserCard.last4,
961
- billing: browserCard.billing,
962
- bind_proxy_pool: account.bindProxyPool?.length ? account.bindProxyPool : [account.bindProxy],
963
- });
964
- return payload;
965
- }
966
-
967
- async function pollAccountTask(account, taskId) {
968
- updateAccount(account, { stage: '同批任务已放行,正在同步执行', taskId });
969
- for (let i = 0; i < Math.ceil(1800000 / TASK_POLL_MS); i += 1) {
970
- await new Promise((resolve) => setTimeout(resolve, TASK_POLL_MS));
971
- if (state.stop) throw new Error('任务已停止');
972
- const poll = await fetch(`/api/standalone-flow/task/${taskId}?t=${Date.now()}`, { cache: 'no-store' });
973
- const data = await poll.json().catch(() => ({}));
974
- const task = data.task || {};
975
- const result = task.result || {};
976
- if (Array.isArray(task.steps)) account.steps = task.steps;
977
- if (task.status === 'done') {
978
- updateAccount(account, {
979
- email: result.email || account.email,
980
- status: 'success',
981
- stage: task.stage || '任务完成',
982
- link: result.checkout_link || '',
983
- error: '',
984
- taskId: '',
985
- fingerprint: result.fingerprint || account.fingerprint || '',
986
- steps: Array.isArray(task.steps) ? task.steps : account.steps,
987
- });
988
- return result;
989
- }
990
- if (task.status === 'error') {
991
- account.taskId = '';
992
- account.stage = task.stage || '任务执行失败';
993
- account.steps = Array.isArray(task.steps) ? task.steps : account.steps;
994
- saveAccounts();
995
- throw new Error(task.error || '任务执行失败');
996
- }
997
- const nextStage = task.stage || '任务处理中';
998
- if (nextStage !== account.stage) {
999
- updateAccount(account, {
1000
- stage: nextStage,
1001
- steps: Array.isArray(task.steps) ? task.steps : account.steps,
1002
- });
1003
- }
1004
- }
1005
- throw new Error('任务轮询超时');
1006
- }
1007
-
1008
- async function submitAlignedWave(entries, mode) {
1009
- entries.forEach(({ account }) => updateAccount(account, {
1010
- stage: `本批 ${entries.length} 个账号已就绪,等待统一放行`,
1011
- }));
1012
- const response = await fetch('/api/standalone-flow/quick-checkout-batch', {
1013
- method: 'POST',
1014
- headers: { 'Content-Type': 'application/json' },
1015
- body: JSON.stringify({
1016
- start_delay_ms: 250,
1017
- tasks: entries.map(({ account, browserCard }) => ({
1018
- client_id: account.id,
1019
- payload: accountFlowPayload(account, mode, browserCard),
1020
- })),
1021
- }),
1022
- });
1023
- const payload = await response.json().catch(() => ({}));
1024
- if (!response.ok || payload.ok === false || !Array.isArray(payload.items)) {
1025
- throw new Error(payload.error || `同步批次创建失败:HTTP ${response.status}`);
1026
- }
1027
- const byId = new Map(payload.items.map((item) => [String(item.client_id || ''), item.task_id]));
1028
- entries.forEach(({ account }) => {
1029
- const taskId = String(byId.get(account.id) || '');
1030
- if (!taskId) throw new Error(`${account.email || account.id} 缺少同步任务 ID`);
1031
- account.taskId = taskId;
1032
- account.stage = `同步批次 ${String(payload.start_group || '').slice(0, 8)} 已排队`;
1033
- });
1034
- renderAccounts();
1035
- return Promise.allSettled(entries.map(({ account }) => pollAccountTask(account, account.taskId)));
1036
- }
1037
-
1038
- function setModeSteps(mode, status) {
1039
- ['stepCard', 'stepAt', 'stepBind', 'stepLink'].forEach((id) => setStep(id, ''));
1040
- if (mode !== 'link_only') setStep('stepCard', 'done');
1041
- setStep('stepAt', 'done');
1042
- if (mode === 'bind_only') setStep('stepBind', status);
1043
- else if (mode === 'link_pay' || mode === 'link_only') setStep('stepLink', status);
1044
- else {
1045
- setStep('stepBind', status);
1046
- setStep('stepLink', status);
1047
- }
1048
- }
1049
-
1050
- function updateProgress(done, total, label) {
1051
- const percent = total ? Math.round((done * 100) / total) : 0;
1052
- $('progressText').textContent = `${label} ${done}/${total}`;
1053
- $('progressPercent').textContent = `${percent}%`;
1054
- $('progressBar').style.width = `${percent}%`;
1055
- }
1056
-
1057
- async function runBatch(mode, label) {
1058
- const data = refresh();
1059
- if ((mode === 'link_only' ? !data.linkOnlyReady : !data.ready) || state.running) return;
1060
- const accounts = [...data.accounts];
1061
- state.running = true;
1062
- state.stop = false;
1063
- hideBatchSummary();
1064
- $('stopButton').disabled = false;
1065
- renderAccounts();
1066
- refresh();
1067
- setModeSteps(mode, 'active');
1068
- const limit = Math.max(1, Math.min(MAX_BATCH_CONCURRENCY, Number($('batchConcurrency').value) || 1));
1069
- updateProgress(0, accounts.length, '正在分配代理');
1070
- assignProxies(accounts, data.bind, data.promo, mode);
1071
- appendLog(`已为 ${accounts.length} 个账号分配${mode === 'link_only' ? '提链代理' : '双代理'},每批 ${Math.min(limit, accounts.length)} 个账号同步起跑。`);
1072
- updateProgress(0, accounts.length, `${label}同步并发`);
1073
- let done = 0;
1074
- let success = 0;
1075
-
1076
- function recordFailure(account, error) {
1077
- const message = translateError(error?.message || error);
1078
- failRunningAccountStep(account, message);
1079
- const preciseStage = String(account.stage || '');
1080
- const failedStep = [...(account.steps || [])].reverse().find((step) => step.status === 'error');
1081
- updateAccount(account, {
1082
- status: 'error',
1083
- stage: failedStep?.label
1084
- ? `${failedStep.label}失败`
1085
- : preciseStage.includes('失败') ? preciseStage : `${label}失败`,
1086
- error: message,
1087
- });
1088
- appendLog(`${account.email || account.id}:${message}`);
1089
- }
1090
-
1091
- for (let offset = 0; offset < accounts.length && !state.stop; offset += limit) {
1092
- const wave = accounts.slice(offset, offset + limit);
1093
- const prepared = [];
1094
- updateProgress(done, accounts.length, `正在准备同步批次 ${Math.floor(offset / limit) + 1}`);
1095
- for (const account of wave) {
1096
- if (state.stop) break;
1097
- try {
1098
- if (mode === 'link_only') {
1099
- updateAccount(account, { status: 'running', stage: '提链代理已就绪,等待同批同步起跑', error: '' });
1100
- prepared.push({ account, browserCard: null });
1101
- } else {
1102
- const browserCard = await prepareAccountCard(account);
1103
- prepared.push({ account, browserCard });
1104
- }
1105
- } catch (error) {
1106
- recordFailure(account, error);
1107
- done += 1;
1108
- updateProgress(done, accounts.length, label);
1109
- }
1110
- }
1111
- if (!prepared.length || state.stop) continue;
1112
- appendLog(`同步批次 ${Math.floor(offset / limit) + 1}:${prepared.length} 个账号已就绪,统一放行。`);
1113
- try {
1114
- const settled = await submitAlignedWave(prepared, mode);
1115
- settled.forEach((result, index) => {
1116
- const account = prepared[index].account;
1117
- if (result.status === 'fulfilled') success += 1;
1118
- else recordFailure(account, result.reason);
1119
- done += 1;
1120
- updateProgress(done, accounts.length, label);
1121
- });
1122
- } catch (error) {
1123
- prepared.forEach(({ account }) => {
1124
- recordFailure(account, error);
1125
- done += 1;
1126
- updateProgress(done, accounts.length, label);
1127
- });
1128
- }
1129
- }
1130
- if (state.stop) {
1131
- accounts.filter((account) => account.status === 'running' && !account.taskId).forEach((account) => {
1132
- account.status = 'idle';
1133
- account.stage = '已停止,尚未执行';
1134
- });
1135
- }
1136
- state.running = false;
1137
- $('stopButton').disabled = true;
1138
- if (success === accounts.length && !state.stop) setModeSteps(mode, 'done');
1139
- $('progressText').textContent = state.stop ? `${label}已停止` : `${label}完成`;
1140
- showBatchSummary(
1141
- mode === 'bind_only' ? '批量绑卡' : mode === 'link_only' ? '批量提链' : '批量支付',
1142
- success,
1143
- Math.max(0, accounts.length - success),
1144
- state.stop,
1145
- );
1146
- renderAccounts();
1147
- refresh();
1148
- }
1149
-
1150
- $('accountImportInput').addEventListener('input', updateImportCount);
1151
- $('importAtButton').addEventListener('click', () => { void importAccounts($('accountImportInput').value); });
1152
- $('importAtFileButton').addEventListener('click', () => $('atFileInput').click());
1153
- $('atFileInput').addEventListener('change', async (event) => {
1154
- const file = event.target.files?.[0];
1155
- if (file) await importAccounts(await file.text());
1156
- event.target.value = '';
1157
- });
1158
- $('selectAllAccounts').addEventListener('change', (event) => {
1159
- state.accounts.forEach((account) => { account.selected = event.target.checked; });
1160
- renderAccounts();
1161
- refresh();
1162
- });
1163
- $('deleteSelectedButton').addEventListener('click', () => {
1164
- const count = selectedAccounts().length;
1165
- state.accounts = state.accounts.filter((account) => !account.selected);
1166
- renderAccounts();
1167
- refresh();
1168
- appendLog(`已删除 ${count} 个账号。`);
1169
- });
1170
- $('clearButton').addEventListener('click', () => {
1171
- const count = state.accounts.length;
1172
- state.accounts = [];
1173
- renderAccounts();
1174
- refresh();
1175
- $('progressBar').style.width = '0%';
1176
- $('progressPercent').textContent = '0%';
1177
- hideBatchSummary();
1178
- appendLog(`账号列表已清空,共移除 ${count} 个账号。`);
1179
- });
1180
- $('exportCsvButton').addEventListener('click', () => {
1181
- appendLog(exportAccountsCsv() ? 'CSV 已导出。' : '当前没有可导出的账号。');
1182
- });
1183
- $('loadCardButton').addEventListener('click', mountCard);
1184
- $('bindProxyPool').addEventListener('input', () => { saveProxyDraft(); refresh(); });
1185
- $('promoProxyPool').addEventListener('input', () => { saveProxyDraft(); refresh(); });
1186
- $('batchConcurrency').addEventListener('input', saveProxyDraft);
1187
- $('validateButton').addEventListener('click', () => {
1188
- const data = refresh();
1189
- const issues = [];
1190
- if (!state.accounts.length) issues.push('尚未导入账号');
1191
- else if (!data.accounts.length) issues.push('尚未选择账号');
1192
- if (!data.bind.length) issues.push('缺少代理池 1');
1193
- if (!data.promo.length) issues.push('缺少代理池 2');
1194
- if (!state.mounted) issues.push('卡片输入框尚未加载');
1195
- if (!data.billingReady) issues.push(`还有 ${data.billingMissingAccounts.length} 个账号账单地址未就绪`);
1196
- $('progressText').textContent = issues.length
1197
- ? `检查输入:${issues.join(';')}`
1198
- : `检查通过:已选择 ${data.accounts.length} 个账号。`;
1199
- });
1200
- $('fullFlowButton').addEventListener('click', () => runBatch('full', '提链 + 绑卡 + 提链 + 支付'));
1201
- $('batchBindLinkButton').addEventListener('click', () => runBatch('bind_only', '提链 + 绑卡'));
1202
- $('linkPayButton').addEventListener('click', () => runBatch('link_pay', '提链 + 支付'));
1203
- $('linkOnlyButton').addEventListener('click', () => runBatch('link_only', '提链'));
1204
- $('stopButton').addEventListener('click', () => {
1205
- state.stop = true;
1206
- $('stopButton').disabled = true;
1207
- appendLog('已停止后续账号任务。');
1208
- });
1209
- window.addEventListener('pagehide', saveAccountsNow);
1210
-
1211
- loadProxyDraft();
1212
- loadAccounts();
1213
- updateImportCount();
1214
- renderAccounts();
1215
- refresh();
1216
- log(state.accounts.length ? `已恢复 ${state.accounts.length} 个账号及其状态。` : '先在上方导入账号,再填写代理与卡片。');
1217
- void Promise.all([hydrateMissingFingerprints(), hydrateMissingBillingAddresses()]);
1218
- }());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/protocol-pay.css ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ :root{color-scheme:dark;--bg:#07111b;--panel:#0d1a27;--line:#233b4d;--text:#eef6fb;--muted:#8fa6b8;--cyan:#35d6c7;--blue:#4f8cff;--danger:#ff6b73;--ok:#46df92}*{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at 78% 5%,#12324a 0,transparent 32%),linear-gradient(145deg,#07111b,#09141f 55%,#061018);color:var(--text);font-family:Inter,"Segoe UI","Microsoft YaHei",sans-serif;min-height:100vh}.shell{width:min(1460px,calc(100% - 44px));margin:0 auto;padding:42px 0 70px}.hero{padding:10px 4px 30px;border-bottom:1px solid var(--line)}.eyebrow{font:700 12px/1.2 ui-monospace,monospace;letter-spacing:.18em;color:var(--cyan)}h1{font-size:clamp(34px,4vw,58px);margin:12px 0 8px;letter-spacing:-.04em}.hero p{margin:0;color:var(--muted);font-size:17px}.layout{display:grid;grid-template-columns:minmax(390px,520px) 1fr;gap:22px;margin-top:24px}.panel{background:linear-gradient(180deg,rgba(15,29,43,.96),rgba(9,20,31,.96));border:1px solid var(--line);border-radius:24px;box-shadow:0 24px 80px rgba(0,0,0,.24);padding:26px}.panel-title{display:flex;align-items:center;gap:14px;margin-bottom:24px}.panel-title>span{display:grid;place-items:center;width:44px;height:44px;border:1px solid var(--cyan);border-radius:14px;color:var(--cyan);font:800 13px ui-monospace,monospace}.panel-title div{display:flex;flex-direction:column;gap:4px}.panel-title b{font-size:21px}.panel-title small,label>span{color:var(--muted)}label{display:flex;flex-direction:column;gap:9px;margin-top:18px;font-weight:700;font-size:14px}textarea,input{width:100%;border:1px solid #2b4559;background:#07121d;color:var(--text);border-radius:15px;padding:15px 16px;font:500 15px/1.55 ui-monospace,"SFMono-Regular",Consolas,monospace;outline:none;resize:vertical}textarea:focus,input:focus{border-color:var(--cyan);box-shadow:0 0 0 3px rgba(53,214,199,.12)}.privacy{margin:16px 0;color:var(--muted);font-size:13px}button{border:0;border-radius:14px;background:linear-gradient(135deg,var(--cyan),#2fa9d8);color:#031016;padding:15px 18px;font-size:16px;font-weight:900;cursor:pointer}button:disabled{opacity:.5;cursor:not-allowed}.ghost{margin-left:auto;background:transparent;color:var(--muted);border:1px solid var(--line);padding:10px 14px;font-size:13px}.empty{min-height:340px;border:1px dashed #29485d;border-radius:18px;display:grid;place-content:center;text-align:center;gap:9px;color:var(--muted)}.empty b{font-size:22px;color:var(--text)}.jobs{display:grid;gap:15px}.job{border:1px solid var(--line);border-radius:18px;background:#08141f;padding:18px}.job-head{display:flex;align-items:flex-start;gap:14px}.badge{font:800 11px ui-monospace,monospace;color:var(--cyan);border:1px solid #2b786f;border-radius:999px;padding:6px 9px}.job-main{min-width:0;flex:1}.job-main b{display:block;font-size:17px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.job-main small{display:block;color:var(--muted);margin-top:6px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.progress{height:8px;background:#142434;border-radius:999px;overflow:hidden;margin:16px 0 10px}.progress i{display:block;height:100%;background:linear-gradient(90deg,var(--cyan),var(--blue));width:0;transition:width .3s}.stage{display:flex;justify-content:space-between;gap:14px;font-size:14px}.stage span:last-child{color:var(--muted)}.log{margin-top:14px;border-top:1px solid #1b3141;padding-top:12px;color:#abc0ce;font-size:13px;line-height:1.55}.result{margin-top:14px;padding:13px;border-radius:12px;background:rgba(70,223,146,.09);border:1px solid rgba(70,223,146,.28);color:var(--ok);word-break:break-word}.error{margin-top:14px;padding:13px;border-radius:12px;background:rgba(255,107,115,.08);border:1px solid rgba(255,107,115,.3);color:#ff969c;word-break:break-word}.status-ready .badge{color:var(--ok);border-color:var(--ok)}.status-error .badge{color:var(--danger);border-color:var(--danger)}@media(max-width:900px){.shell{width:min(100% - 24px,760px);padding-top:22px}.layout{grid-template-columns:1fr}.panel{padding:19px;border-radius:18px}.task-panel{min-height:380px}}.auto-proxy{margin-top:18px;padding:16px;border:1px solid rgba(53,214,199,.28);background:rgba(53,214,199,.07);border-radius:15px;display:flex;flex-direction:column;gap:7px}.auto-proxy b{color:var(--cyan);font:800 12px ui-monospace,monospace;letter-spacing:.14em}.auto-proxy span{color:var(--muted);font-size:14px;line-height:1.55}
2
+ .card-fields{display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-top:4px}.card-fields label{margin-top:14px}.card-fields .card-number{grid-column:1/-1}.card-fields input{font-size:16px;letter-spacing:.04em}@media(max-width:560px){.card-fields{grid-template-columns:1fr 1fr}.card-fields label:last-child{grid-column:1/-1}}
3
+
4
+ .pair-list{display:grid;gap:14px}.pair-row{border:1px solid var(--line);border-radius:17px;padding:16px;background:rgba(4,13,22,.45)}.pair-head{display:flex;align-items:center;justify-content:space-between}.pair-index{font:800 12px ui-monospace,monospace;letter-spacing:.12em;color:var(--cyan)}.pair-row label{margin-top:12px}.pair-row textarea{min-height:110px}.remove-pair{margin-left:auto;padding:7px 10px}.pair-actions{display:flex;justify-content:flex-end;margin:14px 0 18px}.status-prepared .badge{color:#ffd166;border-color:#ffd166}.status-prepared .progress i{background:linear-gradient(90deg,#ffd166,#ff9f43)}
static/protocol-pay.js ADDED
@@ -0,0 +1 @@
 
 
1
+ (()=>{const base=document.documentElement.dataset.apiBase||'', $=id=>document.getElementById(id),form=$("payForm"),list=$("pairList"),tpl=$("pairTemplate"),jobs=$("jobs"),empty=$("emptyState"),submit=$("submitButton"),polls=new Map(),esc=v=>String(v??"").replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));function renumber(){[...list.children].forEach((r,i)=>r.querySelector(".pair-index").textContent=`${String(i+1).padStart(2,"0")} / ACCOUNT`)}function add(){if(list.children.length>=50)return;const n=tpl.content.firstElementChild.cloneNode(true);n.querySelector(".remove-pair").onclick=()=>{if(list.children.length>1){n.remove();renumber()}};list.appendChild(n);renumber()}function draw(x){let n=document.querySelector(`[data-job="${x.id}"]`);if(!n){n=document.createElement("article");n.className="job";n.dataset.job=x.id;jobs.prepend(n)}n.className=`job status-${x.status}`;const logs=(x.logs||[]).slice(-4).map(v=>`<div>${esc(v.time)} &middot; ${esc(v.message)}</div>`).join(""),res=x.result&&Object.keys(x.result).length?`<div class="result">${esc(x.result.intent_status||x.result.status||x.stage||"Prepared")}</div>`:"",err=x.error?`<div class="error">${esc(x.error)}</div>`:"";n.innerHTML=`<div class="job-head"><span class="badge">${esc((x.status||"queued").toUpperCase())}</span><div class="job-main"><b>${esc(x.account_email||"AT account")}</b><small>${esc(x.checkout_url||"")}</small></div></div><div class="progress"><i style="width:${Number(x.progress||0)}%"></i></div><div class="stage"><b>${esc(x.stage||"Waiting")}</b><span>${Number(x.progress||0)}%</span></div><div class="log">${logs||esc(x.message||"")}</div>${res}${err}`;empty.hidden=true}async function get(id){const r=await fetch(`${base}/api/protocol-pay/jobs/${id}`,{cache:"no-store"}),d=await r.json();if(!r.ok||!d.ok)throw new Error(d.error||`HTTP ${r.status}`);draw(d.job);return d.job}async function waitPrepared(ids){for(;;){const states=await Promise.all(ids.map(get));if(states.every(x=>["prepared","error","cancelled"].includes(x.status)))return states;await new Promise(r=>setTimeout(r,1000))}}function pollFinal(id){if(polls.has(id))return;const t=setInterval(async()=>{try{const x=await get(id);if(["ready","error","cancelled","verification_required"].includes(x.status)){clearInterval(t);polls.delete(id)}}catch{}},1200);polls.set(id,t)}async function create(item){const r=await fetch(`${base}/api/protocol-pay/jobs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({access_token:item.at,checkout_url:item.url,defer_confirm:true})}),d=await r.json();if(!r.ok||!d.ok)throw new Error(d.error||`HTTP ${r.status}`);draw(d.job);return d.job.id}form.addEventListener("submit",async e=>{e.preventDefault();submit.disabled=true;try{const items=[...list.querySelectorAll(".pair-row")].map(r=>({at:r.querySelector(".pair-at").value.trim(),url:r.querySelector(".pair-url").value.trim()}));if(items.some(x=>!x.at||!x.url))throw new Error("AT and Checkout are required for every row");const ids=await Promise.all(items.map(create));const states=await waitPrepared(ids),ready=states.filter(x=>x.status==="prepared").map(x=>x.id);if(!ready.length)throw new Error("No task completed preparation");const r=await fetch(`${base}/api/protocol-pay/batch-confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({job_ids:ready})}),d=await r.json();if(!r.ok||!d.ok)throw new Error(d.error||`HTTP ${r.status}`);ready.forEach(pollFinal)}catch(e){alert(e.message)}finally{submit.disabled=false}});$("addPair").onclick=add;$("clearButton").onclick=()=>{jobs.innerHTML="";empty.hidden=false};add()})();
stripe_checkout.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Small Stripe transport compatibility layer used by the protocol worker."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import time
7
+ from typing import Any
8
+
9
+ from curl_ca_bundle import curl_session_kwargs, is_ca_bundle_error
10
+
11
+ try:
12
+ from curl_cffi.requests import Session
13
+ except ImportError: # pragma: no cover - dependency is declared in requirements.txt
14
+ Session = None # type: ignore[assignment]
15
+
16
+
17
+ STRIPE_API = "https://api.stripe.com"
18
+ STRIPE_VERSION_FULL = "2020-08-27"
19
+ DEFAULT_STRIPE_RUNTIME_VERSION = "3"
20
+ STRIPE_PROXY_REUSE_ATTEMPTS = max(
21
+ 1, min(10, int(os.getenv("STRIPE_PROXY_REUSE_ATTEMPTS", "3")))
22
+ )
23
+
24
+
25
+ def _retryable_transport_error(exc: Exception) -> bool:
26
+ if is_ca_bundle_error(exc):
27
+ return False
28
+ message = f"{type(exc).__name__}: {exc}".lower()
29
+ return any(
30
+ marker in message
31
+ for marker in (
32
+ "connectionerror",
33
+ "connecterror",
34
+ "could not connect",
35
+ "failed to connect",
36
+ "connection closed",
37
+ "connection reset",
38
+ "proxyerror",
39
+ "timeout",
40
+ "timed out",
41
+ "ssl",
42
+ "tls",
43
+ "curl: (7)",
44
+ "curl: (28)",
45
+ "curl: (35)",
46
+ "curl: (52)",
47
+ "curl: (55)",
48
+ "curl: (56)",
49
+ )
50
+ )
51
+
52
+
53
+ class RotatingStripeSession:
54
+ def __init__(
55
+ self,
56
+ proxy: str | None = None,
57
+ *,
58
+ impersonate: str = "chrome136",
59
+ retry_attempts: int = STRIPE_PROXY_REUSE_ATTEMPTS,
60
+ retry_delay: float = 0.5,
61
+ ) -> None:
62
+ self.proxy = str(proxy or "").strip()
63
+ self.impersonate = impersonate
64
+ self.retry_attempts = max(1, min(10, int(retry_attempts)))
65
+ self.retry_delay = max(0.0, min(5.0, float(retry_delay)))
66
+ self._session: Any = None
67
+
68
+ def _open(self) -> Any:
69
+ if Session is None:
70
+ raise RuntimeError("STRIPE_TRANSPORT_DEPENDENCY_MISSING: curl_cffi")
71
+ session = Session(impersonate=self.impersonate, **curl_session_kwargs())
72
+ try:
73
+ session.trust_env = False
74
+ except Exception:
75
+ pass
76
+ if self.proxy:
77
+ session.proxies = {"http": self.proxy, "https": self.proxy}
78
+ self._session = session
79
+ return session
80
+
81
+ def _reset(self) -> None:
82
+ current, self._session = self._session, None
83
+ try:
84
+ if current is not None:
85
+ current.close()
86
+ except Exception:
87
+ pass
88
+
89
+ def _request(self, method: str, url: str, **kwargs: Any) -> Any:
90
+ last_error: Exception | None = None
91
+ for attempt in range(1, self.retry_attempts + 1):
92
+ session = self._session or self._open()
93
+ try:
94
+ return getattr(session, method)(url, **kwargs)
95
+ except Exception as exc:
96
+ if not _retryable_transport_error(exc):
97
+ raise
98
+ last_error = exc
99
+ self._reset()
100
+ if attempt < self.retry_attempts and self.retry_delay:
101
+ time.sleep(self.retry_delay)
102
+ assert last_error is not None
103
+ raise RuntimeError(
104
+ f"STRIPE_PROXY_RETRY_EXHAUSTED: {self.retry_attempts} fresh connection(s); "
105
+ f"last={type(last_error).__name__}: {last_error}"
106
+ ) from last_error
107
+
108
+ def get(self, url: str, **kwargs: Any) -> Any:
109
+ return self._request("get", url, **kwargs)
110
+
111
+ def post(self, url: str, **kwargs: Any) -> Any:
112
+ return self._request("post", url, **kwargs)
113
+
114
+ def close(self) -> None:
115
+ self._reset()
116
+
117
+
118
+ def build_http(
119
+ proxy: str | None = None,
120
+ *,
121
+ impersonate: str = "chrome136",
122
+ retry_attempts: int = STRIPE_PROXY_REUSE_ATTEMPTS,
123
+ retry_delay: float = 0.5,
124
+ ) -> Any:
125
+ return RotatingStripeSession(
126
+ proxy,
127
+ impersonate=impersonate,
128
+ retry_attempts=retry_attempts,
129
+ retry_delay=retry_delay,
130
+ )
131
+
132
+
133
+ def _stripe_headers() -> dict[str, str]:
134
+ return {
135
+ "Accept": "application/json",
136
+ "Content-Type": "application/x-www-form-urlencoded",
137
+ "Origin": "https://js.stripe.com",
138
+ "Referer": "https://js.stripe.com/",
139
+ "User-Agent": "Mozilla/5.0",
140
+ }
141
+
142
+
143
+ def _find_next_action(value: Any) -> dict[str, Any]:
144
+ stack = [value]
145
+ visited: set[int] = set()
146
+ while stack:
147
+ current = stack.pop()
148
+ if isinstance(current, dict):
149
+ direct = current.get("next_action")
150
+ if isinstance(direct, dict):
151
+ return direct
152
+ identity = id(current)
153
+ if identity in visited:
154
+ continue
155
+ visited.add(identity)
156
+ stack.extend(reversed(list(current.values())))
157
+ elif isinstance(current, list):
158
+ identity = id(current)
159
+ if identity in visited:
160
+ continue
161
+ visited.add(identity)
162
+ stack.extend(reversed(current))
163
+ return {}
templates/card-flow.html ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="zh-CN" data-api-base="{{ request.script_root }}">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>批量绑卡、提链与协议支付</title>
7
+ <link rel="stylesheet" href="{{ url_for('static', filename='card-flow.css', v='32') }}">
8
+ <script src="https://js.stripe.com/v3/"></script>
9
+ </head>
10
+ <body>
11
+ <main class="shell batch-shell">
12
+ <section class="hero">
13
+ <span class="eyebrow">ONE CARD / MULTI AT / UNIFIED PAYMENT</span>
14
+ <h1>批量绑卡、提链与协议支付</h1>
15
+ <p>填写一次卡片信息,再输入多个 AT。每个账号会依次完成绑卡、Checkout 提链和协议支付。</p>
16
+ </section>
17
+
18
+ <section class="card batch-card">
19
+ <div class="steps batch-steps">
20
+ <span id="stepCard" class="active">1 填写卡片</span>
21
+ <span id="stepAt">2 输入多个 AT</span>
22
+ <span id="stepBind">3 批量绑卡</span>
23
+ <span id="stepLink">4 批量提链</span>
24
+ <span id="stepPay">5 协议支付</span>
25
+ </div>
26
+
27
+ <section class="batch-section">
28
+ <div class="section-title">
29
+ <div><b>卡片信息</b><small>卡号、有效期和 CVC 仅由 Stripe 安全组件处理</small></div>
30
+ <span class="tag">CARD FIRST</span>
31
+ </div>
32
+ <div class="card-fields-grid">
33
+ <label class="card-field card-number-field">
34
+ <span>&#21345;&#21495;</span>
35
+ <div id="cardNumberElement" class="card-field-box"></div>
36
+ </label>
37
+ <label class="card-field">
38
+ <span>&#26377;&#25928;&#26399;</span>
39
+ <div id="cardExpiryElement" class="card-field-box"></div>
40
+ </label>
41
+ <label class="card-field">
42
+ <span>CVC</span>
43
+ <div id="cardCvcElement" class="card-field-box"></div>
44
+ </label>
45
+ </div>
46
+ <div id="cardReady" class="inline-state">请先填写 AT 和代理池,再加载安全卡片输入框</div>
47
+ <button id="loadCardButton" class="secondary load-card-button" type="button" disabled>&#21152;&#36733;&#23433;&#20840;&#21345;&#29255;&#36755;&#20837;&#26694;</button>
48
+ </section>
49
+
50
+ <section class="batch-section">
51
+ <div class="section-title at-section-title">
52
+ <div><b>AT &#21015;&#34920;</b><small>&#27599;&#20010;&#36755;&#20837;&#26694;&#25903;&#25345;&#21407;&#22987; AT &#25110;&#21253;&#21547; accessToken &#30340; JSON</small></div>
53
+ <div class="at-title-actions">
54
+ <span id="atCount" class="tag">1 AT</span>
55
+ <input id="atFileInput" type="file" accept=".txt,.json,.jsonl,.csv,text/plain,application/json,text/csv" hidden>
56
+ <button id="importAtButton" class="secondary small import-at-button" type="button">&#8679; &#23548;&#20837;&#25991;&#20214;</button>
57
+ <button id="addAtButton" class="secondary small add-at-button" type="button">&#65291; &#28155;&#21152; AT</button>
58
+ </div>
59
+ </div>
60
+ <div id="atList" class="at-list"></div>
61
+ </section>
62
+
63
+ <section class="batch-section proxy-pool-section">
64
+ <div class="section-title">
65
+ <div><b>&#21452;&#20195;&#29702;&#27744;</b><small>&#20004;&#20010;&#27744;&#32844;&#36131;&#20998;&#31163;&#65292;&#19981;&#20877;&#23558;&#32654;&#22269;&#33410;&#28857;&#38169;&#29992;&#20026;&#32;TR&#32;&#20248;&#24800;&#33410;&#28857;</small></div>
66
+ <span class="tag">US + TR</span>
67
+ </div>
68
+ <div class="dual-proxy-grid">
69
+ <div class="proxy-pool-card">
70
+ <div class="proxy-pool-head"><b>&#20195;&#29702;&#27744;&#32;1</b><span id="bindProxyCount" class="tag">0 PROXY</span></div>
71
+ <small>&#32465;&#21345;&#19982;&#21019;&#24314;&#32;Checkout&#65306;&#35831;&#22635;&#32;US&#32;&#33410;&#28857;</small>
72
+ <textarea id="bindProxyPool" class="proxy-pool-input" spellcheck="false" autocomplete="off" placeholder="US proxy&#10;host:port:username:password&#10;socks5://username:password@host:port"></textarea>
73
+ </div>
74
+ <div class="proxy-pool-card">
75
+ <div class="proxy-pool-head"><b>&#20195;&#29702;&#27744;&#32;2</b><span id="promoProxyCount" class="tag">0 PROXY</span></div>
76
+ <small>&#24212;&#29992;&#20248;&#24800;&#19982;&#25552;&#38142;&#65306;&#35831;&#22635;&#32;TR&#32;&#33410;&#28857;</small>
77
+ <textarea id="promoProxyPool" class="proxy-pool-input" spellcheck="false" autocomplete="off" placeholder="TR proxy&#10;host:port:username:password&#10;socks5://username:password@host:port"></textarea>
78
+ </div>
79
+ </div>
80
+ <div class="proxy-pool-note">&#20195;&#29702;&#20165;&#20445;&#23384;&#22312;&#24403;&#21069;&#27983;&#35272;&#22120;&#26412;&#22320;&#65307;&#27599;&#20010;&#27744;&#26368;&#22810;&#32;&#53;&#48;&#48;&#32;&#26465;&#12290;</div>
81
+ </section>
82
+
83
+ <div class="action-row">
84
+ <label class="concurrency-control"><span>并发数</span><input id="batchConcurrency" type="number" min="1" max="200" value="200" inputmode="numeric"></label>
85
+ <button id="startButton" type="button" disabled>开始绑卡、提链并协议支付</button>
86
+ <button id="stopButton" class="secondary" type="button" disabled>停止</button>
87
+ </div>
88
+
89
+ <div class="progress-wrap">
90
+ <div class="progress-meta"><span id="progressText">等待开始</span><span id="progressPercent">0%</span></div>
91
+ <div class="progress-track"><i id="progressBar"></i></div>
92
+ </div>
93
+
94
+ <section class="batch-section result-section">
95
+ <div class="section-title">
96
+ <div><b>统一任务结果</b><small>账号、Checkout 链接和支付终态</small></div>
97
+ <div class="mini-actions">
98
+ <button id="copyButton" class="secondary small" type="button">&#22797;&#21046;&#20840;&#37096;&#38142;&#25509;</button>
99
+ <button id="clearButton" class="secondary small" type="button">清空</button>
100
+ </div>
101
+ </div>
102
+ <div id="taskRows" class="task-rows"></div>
103
+ </section>
104
+
105
+ <div id="status" class="status">请先填写卡片信息,再粘贴 AT 列表。</div>
106
+ </section>
107
+ </main>
108
+ <script src="{{ url_for('static', filename='card-flow-logic.js', v='2') }}"></script>
109
+ <script src="{{ url_for('static', filename='card-flow.js', v='49') }}"></script>
110
+ </body>
111
+ </html>
templates/card-long-flow.html ADDED
@@ -0,0 +1 @@
 
 
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Bind Card & Create Long Checkout</title><link rel="stylesheet" href="{{ url_for('static', filename='card-flow.css', v='4') }}"><script src="https://js.stripe.com/v3/"></script></head><body><main class="shell"><section class="hero"><span class="eyebrow">HOSTED ? LONG CHECKOUT</span><h1>Bind Card & Create Long Checkout</h1><p>Save the card with redisplay enabled, attach it as the account default, then generate a new Stripe Hosted Checkout link.</p></section><section class="card"><div class="steps"><span class="active">1 Card</span><span>2 Attach</span><span>3 Long Link</span><span>4 Confirm</span></div><form id="flowForm"><label>Card details</label><div id="paymentElement" class="stripe-box"></div><label>Billing address</label><div id="addressElement" class="stripe-box"></div><button id="submitButton" type="submit">Bind Card & Create Long Link</button></form><div id="status" class="status">Initializing secure payment form...</div><a id="checkoutLink" class="checkout-link" target="_blank" rel="noopener">Open Hosted Checkout</a></section></main><script src="{{ url_for('static', filename='card-long-flow.js', v='4') }}"></script></body></html>
templates/protocol-pay.html ADDED
@@ -0,0 +1 @@
 
 
1
+ <!doctype html><html lang="zh-CN" data-api-base="{{ request.script_root }}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>&#25209;&#37327;&#21327;&#35758;&#25903;&#20184;</title><link rel="stylesheet" href="{{ url_for('static', filename='protocol-pay.css', v='8') }}"></head><body><main class="shell"><header class="hero"><span class="eyebrow">BATCH PREPARE / SYNC CONFIRM</span><h1>&#25209;&#37327;&#21327;&#35758;&#25903;&#20184;</h1><p>&#27599;&#32452; AT &#19982; Checkout &#29420;&#31435;&#20934;&#22791;&#24050;&#32465;&#21345;&#12289;CustomerSession &#21644; ConfirmationToken&#65292;&#20840;&#37096;&#20934;&#22791;&#23436;&#25104;&#21518;&#21516;&#26102;&#25552;&#20132;&#35746;&#38405;&#12290;</p></header><section class="layout"><form id="payForm" class="panel form-panel"><div class="panel-title"><span>01</span><div><b>AT + Checkout</b><small>&#26368;&#22810; 50 &#32452;</small></div></div><div id="pairList" class="pair-list"></div><div class="pair-actions"><button id="addPair" class="ghost" type="button">+ &#28155;&#21152;&#19968;&#32452;</button></div><div class="auto-proxy"><b>PREPARE FIRST</b><span>&#20808;&#20934;&#22791;&#25152;&#26377;&#20219;&#21153;&#65292;&#19981;&#20250;&#25552;&#21069;&#25191;&#34892;&#35746;&#38405;&#65307;&#20934;&#22791;&#32467;&#26463;&#21518;&#32479;&#19968;&#37322;&#25918;&#12290;</span></div><button id="submitButton" type="submit">&#20934;&#22791;&#20840;&#37096;&#24182;&#21516;&#26102;&#35746;&#38405;</button></form><section class="panel task-panel"><div class="panel-title"><span>02</span><div><b>&#29420;&#31435;&#20219;&#21153;</b><small>&#20934;&#22791;&#23631;&#38556; / &#21516;&#26102;&#25552;&#20132;</small></div><button id="clearButton" class="ghost" type="button">&#28165;&#31354;&#26174;&#31034;</button></div><div id="emptyState" class="empty"><b>&#31561;&#24453;&#20219;&#21153;</b><span>&#28155;&#21152; AT &#21644;&#38142;&#25509;&#21518;&#25552;&#20132;&#12290;</span></div><div id="jobs" class="jobs"></div></section></section></main><template id="pairTemplate"><div class="pair-row"><div class="pair-head"><b class="pair-index"></b><button class="remove-pair ghost" type="button">&#21024;&#38500;</button></div><label><span>AT / Session JSON</span><textarea class="pair-at" rows="5" required></textarea></label><label><span>Checkout &#38142;&#25509;</span><input class="pair-url" type="url" placeholder="https://chatgpt.com/checkout/openai_llc/..." required></label></div></template><script src="{{ url_for('static', filename='protocol-pay.js', v='8') }}"></script></body></html>