File size: 13,037 Bytes
3ec0f02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
from __future__ import annotations
import json
import os
import re
import sys
import time
import base64
import hashlib
import uuid
from typing import Any

from curl_ca_bundle import curl_session_kwargs, is_ca_bundle_error

try:
    from curl_cffi.requests import Session
except ImportError:  # pragma: no cover - dependency is declared in requirements.txt
    Session = None  # type: ignore[assignment]

ACCOUNT_FILE = "/opt/reg153/success_accounts.jsonl"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0"
SET_DEFAULT_PROXY_REUSE_ATTEMPTS = max(
    1,
    min(
        10,
        int(
            os.getenv("SET_DEFAULT_PROXY_REUSE_ATTEMPTS")
            or os.getenv("CARD_BIND_PROXY_REUSE_ATTEMPTS")
            or "3"
        ),
    ),
)
SET_DEFAULT_REQUEST_TIMEOUT = max(
    5, min(60, int(os.getenv("SET_DEFAULT_REQUEST_TIMEOUT", "25")))
)


class UpstreamResponseError(RuntimeError):
    def __init__(self, error: str, status: int, detail: str = "") -> None:
        super().__init__(detail or f"HTTP {status}")
        self.error = error
        self.status = status
        self.detail = detail


def safe_detail(value: object) -> str:
    text = str(value or "")
    text = re.sub(r"(?i)((?:https?|socks5h?)://)[^/@\s]+@", r"\1***@", text)
    text = re.sub(
        r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+",
        "AT_REDACTED",
        text,
    )
    return text[:500]


def retryable_transport_error(exc: Exception) -> bool:
    if is_ca_bundle_error(exc):
        return False
    detail = f"{type(exc).__name__}: {exc}".lower()
    return any(
        marker in detail
        for marker in (
            "connectionerror",
            "connecterror",
            "could not connect",
            "failed to connect",
            "connection closed",
            "connection reset",
            "proxyerror",
            "timeout",
            "timed out",
            "ssl",
            "tls",
            "curl: (7)",
            "curl: (28)",
            "curl: (35)",
            "curl: (52)",
            "curl: (55)",
            "curl: (56)",
        )
    )


def helper_error_payload(exc: Exception) -> dict[str, Any]:
    if isinstance(exc, UpstreamResponseError):
        return {
            "ok": False,
            "error": exc.error,
            "status": exc.status,
            "detail": safe_detail(exc.detail),
        }
    detail = safe_detail(f"{type(exc).__name__}: {exc}")
    lowered = detail.lower()
    if is_ca_bundle_error(exc):
        error = "SET_DEFAULT_TLS_CA_BUNDLE_ERROR"
    elif isinstance(exc, ModuleNotFoundError):
        error = "SET_DEFAULT_DEPENDENCY_MISSING"
    elif retryable_transport_error(exc) or "proxy_retry_exhausted" in lowered:
        error = "SET_DEFAULT_UPSTREAM_NETWORK_ERROR"
    else:
        error = "SET_DEFAULT_HELPER_ERROR"
    return {"ok": False, "error": error, "detail": detail}


def proxy_variants(proxy: str) -> list[str]:
    value = str(proxy or "").strip()
    variants = [value]
    lowered = value.lower()
    if lowered.startswith("socks5h://"):
        variants.append("socks5://" + value[len("socks5h://") :])
    elif lowered.startswith("socks5://"):
        variants.append("socks5h://" + value[len("socks5://") :])
    return variants


class RotatingDefaultSession:
    def __init__(
        self,
        proxy: str,
        cookies: dict,
        *,
        retry_attempts: int = SET_DEFAULT_PROXY_REUSE_ATTEMPTS,
        retry_delay: float = 0.5,
    ) -> None:
        self.proxy = str(proxy or "").strip()
        self.cookies = dict(cookies or {})
        self.retry_attempts = max(1, min(10, int(retry_attempts)))
        self.retry_delay = max(0.0, min(5.0, float(retry_delay)))

    def _open(self, proxy: str):
        if Session is None:
            raise ModuleNotFoundError("curl_cffi is not installed")
        http = Session(impersonate="firefox144", **curl_session_kwargs())
        http.trust_env = False
        if proxy and proxy.upper() != "DIRECT":
            http.proxies = {"http": proxy, "https": proxy}
        for name, value in self.cookies.items():
            try:
                http.cookies.set(str(name), str(value), domain="chatgpt.com")
            except Exception:
                pass
        return http

    def request(self, method: str, url: str, **kwargs: Any):
        failures: list[str] = []
        last_error: Exception | None = None
        variants = proxy_variants(self.proxy)
        for attempt in range(1, self.retry_attempts + 1):
            for candidate_proxy in variants:
                http = None
                dns_mode = (
                    "remote_dns"
                    if candidate_proxy.lower().startswith("socks5h://")
                    else "local_dns"
                    if candidate_proxy.lower().startswith("socks5://")
                    else "default"
                )
                try:
                    http = self._open(candidate_proxy)
                    response = getattr(http, method)(url, **kwargs)
                    return response, f"curl_firefox144_{dns_mode}_round_{attempt}"
                except Exception as exc:
                    if is_ca_bundle_error(exc):
                        raise RuntimeError(
                            f"SET_DEFAULT_TLS_CA_BUNDLE_ERROR: {safe_detail(exc)}"
                        ) from exc
                    if not retryable_transport_error(exc):
                        raise
                    last_error = exc
                    failures.append(
                        f"round_{attempt}_{dns_mode}={type(exc).__name__}"
                    )
                finally:
                    try:
                        if http is not None:
                            http.close()
                    except Exception:
                        pass
            if attempt < self.retry_attempts and self.retry_delay:
                time.sleep(self.retry_delay)
        assert last_error is not None
        raise RuntimeError(
            "SET_DEFAULT_PROXY_RETRY_EXHAUSTED: "
            f"{self.retry_attempts} fresh connection round(s); "
            + "; ".join(failures)
            + f"; last={safe_detail(f'{type(last_error).__name__}: {last_error}')}"
        ) from last_error

    def get(self, url: str, **kwargs: Any):
        return self.request("get", url, **kwargs)

    def post(self, url: str, **kwargs: Any):
        return self.request("post", url, **kwargs)


def response_detail(response: object) -> str:
    try:
        payload = response.json()
    except Exception:
        return safe_detail(getattr(response, "text", ""))
    if isinstance(payload, dict):
        value = payload.get("detail") or payload.get("message") or payload.get("error")
        if isinstance(value, dict):
            value = value.get("message") or value.get("code") or value
        return safe_detail(value)
    return safe_detail(payload)


def load_account(email: str):
    match = None
    with open(ACCOUNT_FILE, encoding="utf-8", errors="ignore") as handle:
        for line in handle:
            try:
                item = json.loads(line)
            except Exception:
                continue
            if str(item.get("email") or "").strip().lower() == email:
                match = item
    return match


def list_payment_method_ids(
    http: RotatingDefaultSession, headers: dict, account_id: str
) -> tuple[set[str], str]:
    response, transport = http.get(
        "https://chatgpt.com/backend-api/payments/payment_methods",
        params={"account_id": account_id},
        headers=headers,
        timeout=SET_DEFAULT_REQUEST_TIMEOUT,
    )
    if response.status_code != 200:
        raise UpstreamResponseError(
            "PAYMENT_METHOD_LOOKUP_FAILED",
            response.status_code,
            response_detail(response),
        )
    try:
        payload = response.json()
    except Exception as exc:
        raise RuntimeError("PAYMENT_METHOD_LOOKUP_INVALID_RESPONSE") from exc
    if isinstance(payload, list):
        items = payload
    elif isinstance(payload, dict):
        items = payload.get("data") or payload.get("payment_methods") or []
    else:
        items = []
    return (
        {str(item.get("id") or "") for item in items if isinstance(item, dict)},
        transport,
    )


def main() -> int:
    email = str(sys.argv[1] if len(sys.argv) > 1 else "").strip().lower()
    payment_method_id = str(sys.argv[2] if len(sys.argv) > 2 else "").strip()
    if not re.fullmatch(r"pm_[A-Za-z0-9]+", payment_method_id):
        print(json.dumps({"ok": False, "error": "INVALID_PAYMENT_METHOD"}))
        return 2

    access_token_override = str(sys.argv[4] if len(sys.argv) > 4 else "").strip()
    account = None if access_token_override else load_account(email)
    if access_token_override:
        try:
            segment = access_token_override.split(".")[1]
            segment += "=" * (-len(segment) % 4)
            claims = json.loads(base64.urlsafe_b64decode(segment.encode()).decode())
            auth = claims.get("https://api.openai.com/auth") or {}
            profile = claims.get("https://api.openai.com/profile") or {}
            account_id_value = str(auth.get("chatgpt_account_id") or claims.get("account_id") or "").strip()
            token_hash = hashlib.sha256(access_token_override.encode()).hexdigest()
            decoded_email = str(profile.get("email") or claims.get("email") or email or f"external-{token_hash[:16]}@example.com").strip().lower()
            device_id = str(uuid.uuid5(uuid.NAMESPACE_URL, "reg153-external-at:" + account_id_value))
            account = {"email": decoded_email, "account_id": account_id_value, "access_token": access_token_override, "session_cookies": {"oai-did": device_id}, "proxy": "DIRECT"}
        except Exception:
            account = None
    if not account:
        print(json.dumps({"ok": False, "error": "ACCOUNT_NOT_FOUND"}))
        return 3
    if access_token_override:
        account = dict(account)
        account["access_token"] = access_token_override

    account_id = str(account.get("account_id") or "")
    access_token = str(account.get("access_token") or "")
    if not account_id or not access_token:
        print(json.dumps({"ok": False, "error": "ACCOUNT_SESSION_INCOMPLETE"}))
        return 4

    proxy = str(sys.argv[3] if len(sys.argv) > 3 else account.get("proxy") or "").strip()
    cookies = account.get("session_cookies") or {}
    if isinstance(cookies, str):
        try:
            cookies = json.loads(cookies)
        except Exception:
            cookies = {}
    headers = {
        "Authorization": "Bearer " + access_token,
        "ChatGPT-Account-Id": account_id,
        "OAI-Device-Id": str(cookies.get("oai-did") or ""),
        "User-Agent": UA,
        "Accept": "application/json",
        "Origin": "https://chatgpt.com",
        "Referer": "https://chatgpt.com/",
        "Content-Type": "application/json",
    }

    http = RotatingDefaultSession(proxy, dict(cookies))
    response, set_transport = http.post(
        "https://chatgpt.com/backend-api/payments/payment_method/default",
        json={"account_id": account_id, "payment_method_id": payment_method_id},
        headers=headers,
        timeout=SET_DEFAULT_REQUEST_TIMEOUT,
    )
    if response.status_code not in (200, 204):
        print(
            json.dumps(
                {
                    "ok": False,
                    "error": "SET_DEFAULT_FAILED",
                    "status": response.status_code,
                    "detail": response_detail(response),
                    "transport": set_transport,
                },
                ensure_ascii=True,
            )
        )
        return 5

    # Wait until the default endpoint's attachment is visible before Checkout.
    last_transport = set_transport
    for attempt in range(1, 13):
        payment_method_ids, last_transport = list_payment_method_ids(
            http, headers, account_id
        )
        if payment_method_id in payment_method_ids:
            print(
                json.dumps(
                    {
                        "ok": True,
                        "attached": True,
                        "attempt": attempt,
                        "transport": last_transport,
                    },
                    ensure_ascii=True,
                )
            )
            return 0
        time.sleep(1.0)

    print(
        json.dumps(
            {
                "ok": False,
                "error": "PAYMENT_METHOD_NOT_ATTACHED",
                "transport": last_transport,
            },
            ensure_ascii=True,
        )
    )
    return 6


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except SystemExit:
        raise
    except Exception as exc:
        print(json.dumps(helper_error_payload(exc), ensure_ascii=True))
        raise SystemExit(10)