dsh-plugin-image-workbench 1.1.5 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +5 -3
  3. package/README.md +7 -3
  4. package/client.js +241 -241
  5. package/cordis.patch.yml +14 -14
  6. package/host.js +51 -0
  7. package/install.mjs +333 -387
  8. package/package.json +3 -2
  9. package/scripts/fetch-style-images.mjs +104 -0
  10. package/scripts/vendor-snapshot.py +154 -154
  11. package/server/access.py +26 -26
  12. package/server/app.py +1329 -1329
  13. package/server/catalog.py +147 -147
  14. package/server/composer.py +391 -391
  15. package/server/drafts.py +158 -158
  16. package/server/history.py +575 -575
  17. package/server/imaging.py +172 -172
  18. package/server/pool.py +1335 -1335
  19. package/server/pool_admin.py +921 -921
  20. package/server/pool_service.py +1073 -1073
  21. package/server/requirements.txt +6 -6
  22. package/server/smoke_check.py +402 -402
  23. package/server/static/access.html +202 -202
  24. package/vendor/chatgpt2api/source/.env.example +82 -82
  25. package/vendor/chatgpt2api/source/.python-version +1 -1
  26. package/vendor/chatgpt2api/source/LICENSE +21 -21
  27. package/vendor/chatgpt2api/source/README.md +391 -391
  28. package/vendor/chatgpt2api/source/VERSION +1 -1
  29. package/vendor/chatgpt2api/source/api/__init__.py +2 -2
  30. package/vendor/chatgpt2api/source/api/accounts.py +537 -537
  31. package/vendor/chatgpt2api/source/api/ai.py +217 -217
  32. package/vendor/chatgpt2api/source/api/app.py +62 -62
  33. package/vendor/chatgpt2api/source/api/errors.py +46 -46
  34. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -309
  35. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -120
  36. package/vendor/chatgpt2api/source/api/support.py +134 -134
  37. package/vendor/chatgpt2api/source/api/system.py +365 -365
  38. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -50
  39. package/vendor/chatgpt2api/source/config.default.json +108 -108
  40. package/vendor/chatgpt2api/source/main.py +9 -9
  41. package/vendor/chatgpt2api/source/pyproject.toml +27 -27
  42. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -186
  43. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -163
  44. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -13
  45. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -385
  46. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -129
  47. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -92
  48. package/vendor/chatgpt2api/source/services/account_service.py +1757 -1757
  49. package/vendor/chatgpt2api/source/services/auth_service.py +253 -253
  50. package/vendor/chatgpt2api/source/services/backup_service.py +671 -671
  51. package/vendor/chatgpt2api/source/services/config.py +667 -667
  52. package/vendor/chatgpt2api/source/services/content_filter.py +242 -242
  53. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -315
  54. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -260
  55. package/vendor/chatgpt2api/source/services/image_service.py +376 -376
  56. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -405
  57. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -76
  58. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -550
  59. package/vendor/chatgpt2api/source/services/log_service.py +337 -337
  60. package/vendor/chatgpt2api/source/services/model_service.py +182 -182
  61. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -267
  62. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -2763
  63. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -32
  64. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -2
  65. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -307
  66. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -238
  67. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -1644
  68. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -124
  69. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -19
  70. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -316
  71. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -86
  72. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -42
  73. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -53
  74. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -453
  75. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -160
  76. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -648
  77. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -5
  78. package/vendor/chatgpt2api/source/services/storage/base.py +38 -38
  79. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -194
  80. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -104
  81. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -183
  82. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -95
  83. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -531
  84. package/vendor/chatgpt2api/source/utils/helper.py +469 -469
  85. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -346
  86. package/vendor/chatgpt2api/source/utils/log.py +110 -110
  87. package/vendor/chatgpt2api/source/utils/pkce.py +19 -19
  88. package/vendor/chatgpt2api/source/utils/pow.py +207 -207
  89. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -159
  90. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -184
  91. package/vendor/chatgpt2api/source/uv.lock +904 -904
  92. package/vendor/chatgpt2api/source/web/bun.lock +1501 -1501
  93. package/vendor/chatgpt2api/source/web/components.json +24 -24
  94. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -17
  95. package/vendor/chatgpt2api/source/web/next.config.ts +40 -40
  96. package/vendor/chatgpt2api/source/web/package.json +58 -58
  97. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -5
  98. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -925
  99. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -1307
  100. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -224
  101. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -444
  102. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -9
  103. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -9
  104. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -172
  105. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -169
  106. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -39
  107. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -59
  108. package/vendor/chatgpt2api/source/web/src/app/globals.css +230 -230
  109. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -542
  110. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -554
  111. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -176
  112. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -1799
  113. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -732
  114. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -50
  115. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -101
  116. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -356
  117. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -30
  118. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -341
  119. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -447
  120. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -71
  121. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -491
  122. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -108
  123. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -169
  124. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -185
  125. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -379
  126. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -127
  127. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -200
  128. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -12
  129. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -886
  130. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -81
  131. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -422
  132. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -135
  133. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -1069
  134. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -49
  135. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -24
  136. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -434
  137. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -46
  138. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -18
  139. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -14
  140. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -263
  141. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -256
  142. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -41
  143. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -59
  144. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -46
  145. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -61
  146. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -27
  147. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -267
  148. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -132
  149. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -13
  150. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -19
  151. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -24
  152. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -149
  153. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -38
  154. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -175
  155. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -143
  156. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -29
  157. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -91
  158. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -269
  159. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -18
  160. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -127
  161. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -6
  162. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -85
  163. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -926
  164. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -26
  165. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -25
  166. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -93
  167. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -89
  168. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -6
  169. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -112
  170. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -33
  171. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -318
  172. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -42
@@ -1,648 +1,648 @@
1
- """Global outbound proxy and Cloudflare clearance helpers."""
2
-
3
- from __future__ import annotations
4
-
5
- from dataclasses import dataclass, field, replace
6
- import json
7
- import re
8
- import threading
9
- import time
10
- from typing import Callable, Mapping
11
- from urllib import request as urllib_request
12
- from urllib.parse import quote, urlparse
13
-
14
- from curl_cffi.requests import Session
15
-
16
- from services.config import config
17
-
18
-
19
- FlareSolverrRequestMethod = Callable[[str, bytes, dict[str, str], float], bytes]
20
-
21
-
22
- def normalize_proxy_url(url: str) -> str:
23
- """Normalize proxy URLs for curl_cffi.
24
-
25
- SOCKS proxies should use remote-DNS resolution by default, so generic
26
- ``socks://`` and ``socks5://`` inputs are upgraded to ``socks5h://``.
27
- HTTP/HTTPS/socks5h inputs are otherwise left untouched except trimming.
28
- """
29
- candidate = str(url or "").strip()
30
- if candidate and "://" not in candidate:
31
- candidate = _colon_proxy_to_url(candidate)
32
- lowered = candidate.lower()
33
- if lowered.startswith("socks://"):
34
- return "socks5h://" + candidate[len("socks://") :]
35
- if lowered.startswith("socks5://"):
36
- return "socks5h://" + candidate[len("socks5://") :]
37
- return candidate
38
-
39
-
40
- @dataclass(frozen=True)
41
- class ProxyRuntimeProfile:
42
- proxy_url: str = ""
43
- proxy_source: str = "direct"
44
- resource: bool = False
45
- runtime_enabled: bool = False
46
- egress_mode: str = "direct"
47
- skip_ssl_verify: bool = False
48
- reset_session_status_codes: tuple[int, ...] = field(default_factory=lambda: (403,))
49
- clearance: dict[str, object] = field(default_factory=dict, repr=False)
50
-
51
- @property
52
- def clearance_enabled(self) -> bool:
53
- return (
54
- self.runtime_enabled
55
- and bool(self.clearance.get("enabled"))
56
- and self.clearance_mode in {"manual", "flaresolverr"}
57
- )
58
-
59
- @property
60
- def clearance_mode(self) -> str:
61
- return str(self.clearance.get("mode") or "none").strip().lower()
62
-
63
- @property
64
- def refresh_interval(self) -> int:
65
- try:
66
- return max(0, int(self.clearance.get("refresh_interval") or 0))
67
- except (OverflowError, TypeError, ValueError):
68
- return 0
69
-
70
- @property
71
- def timeout_sec(self) -> int:
72
- try:
73
- return max(1, int(self.clearance.get("timeout_sec") or 60))
74
- except (OverflowError, TypeError, ValueError):
75
- return 60
76
-
77
-
78
- @dataclass(frozen=True)
79
- class ClearanceBundle:
80
- target_host: str
81
- proxy_url: str = ""
82
- cookies: dict[str, str] = field(default_factory=dict, repr=False)
83
- user_agent: str = ""
84
- created_at: float = field(default_factory=time.time)
85
- expires_at: float | None = None
86
-
87
- def is_valid_for(self, target_host: str, proxy_url: str, *, now: float | None = None) -> bool:
88
- host = _normalize_host(target_host)
89
- if self.target_host and host and _normalize_host(self.target_host) != host:
90
- return False
91
- if normalize_proxy_url(self.proxy_url) != normalize_proxy_url(proxy_url):
92
- return False
93
- if self.expires_at is not None and (time.time() if now is None else now) >= self.expires_at:
94
- return False
95
- return bool(self.cookies or self.user_agent)
96
-
97
- def cookie_header(self) -> str:
98
- return _cookies_to_header(self.cookies)
99
-
100
-
101
- class FlareSolverrClearanceProvider:
102
- def __init__(self, flaresolverr_url: str, request_method: FlareSolverrRequestMethod | None = None) -> None:
103
- self.flaresolverr_url = str(flaresolverr_url or "").strip().rstrip("/")
104
- self._request_method = request_method or self._urllib_post
105
-
106
- def get_clearance(self, target_url: str, proxy_url: str = "", timeout_sec: int = 60) -> ClearanceBundle | None:
107
- if not self.flaresolverr_url:
108
- return None
109
-
110
- timeout = _coerce_timeout(timeout_sec)
111
- payload: dict[str, object] = {
112
- "cmd": "request.get",
113
- "url": str(target_url or ""),
114
- "maxTimeout": int(timeout * 1000),
115
- }
116
- proxy_url = normalize_proxy_url(proxy_url)
117
- if proxy_url:
118
- payload["proxy"] = {"url": proxy_url}
119
-
120
- endpoint = f"{self.flaresolverr_url}/v1"
121
- try:
122
- body = json.dumps(payload).encode("utf-8")
123
- raw_response = self._request_method(
124
- endpoint,
125
- body,
126
- {"Content-Type": "application/json"},
127
- timeout,
128
- )
129
- data = json.loads(raw_response.decode("utf-8") if isinstance(raw_response, bytes) else raw_response)
130
- except Exception:
131
- return None
132
-
133
- if not isinstance(data, dict) or str(data.get("status") or "").lower() != "ok":
134
- return None
135
- solution = data.get("solution")
136
- if not isinstance(solution, dict):
137
- return None
138
-
139
- target_host = _host_from_url(target_url)
140
- cookies = _filter_flaresolverr_cookies(solution.get("cookies"), target_host)
141
- user_agent = str(solution.get("userAgent") or "").strip()
142
- if not cookies and not user_agent:
143
- return None
144
- return ClearanceBundle(
145
- target_host=target_host,
146
- proxy_url=proxy_url,
147
- cookies=cookies,
148
- user_agent=user_agent,
149
- )
150
-
151
- @staticmethod
152
- def _urllib_post(endpoint: str, body: bytes, headers: dict[str, str], timeout: float) -> bytes:
153
- req = urllib_request.Request(endpoint, data=body, headers=headers, method="POST")
154
- with urllib_request.urlopen(req, timeout=timeout) as response:
155
- return response.read()
156
-
157
-
158
- class ProxySettingsStore:
159
- def __init__(
160
- self,
161
- config_store=None,
162
- clearance_provider_factory: Callable[[str], FlareSolverrClearanceProvider] | None = None,
163
- ) -> None:
164
- self._config = config_store or config
165
- self._clearance_provider_factory = clearance_provider_factory or FlareSolverrClearanceProvider
166
- self._clearance_cache: dict[tuple[str, str], ClearanceBundle] = {}
167
- self._provider_cache: dict[str, FlareSolverrClearanceProvider] = {}
168
- self._flight_locks: dict[tuple[str, str], threading.Lock] = {}
169
- self._lock = threading.RLock()
170
-
171
- def get_profile(
172
- self,
173
- account: dict | None = None,
174
- proxy: str = "",
175
- resource: bool = False,
176
- upstream: bool = False,
177
- ) -> ProxyRuntimeProfile:
178
- runtime = self._get_runtime_settings()
179
- clearance = dict(runtime.get("clearance") if isinstance(runtime.get("clearance"), dict) else {})
180
- runtime_enabled = bool(runtime.get("enabled"))
181
- egress_mode = str(runtime.get("egress_mode") or "direct").strip().lower()
182
-
183
- account_proxy = _clean((account or {}).get("proxy") if isinstance(account, dict) else "")
184
- explicit_proxy = _clean(proxy)
185
- legacy_proxy = _clean(self._config.get_proxy_settings())
186
-
187
- runtime_proxy = ""
188
- runtime_proxy_source = "runtime"
189
- if upstream and runtime_enabled and egress_mode == "single_proxy":
190
- resource_proxy = _clean(runtime.get("resource_proxy_url")) if resource else ""
191
- runtime_proxy = resource_proxy or _clean(runtime.get("proxy_url"))
192
- runtime_proxy_source = "runtime_resource" if resource_proxy else "runtime"
193
-
194
- selected_proxy = ""
195
- source = "direct"
196
- if account_proxy:
197
- selected_proxy = account_proxy
198
- source = "account"
199
- elif runtime_proxy:
200
- selected_proxy = runtime_proxy
201
- source = runtime_proxy_source
202
- elif explicit_proxy:
203
- selected_proxy = explicit_proxy
204
- source = "explicit"
205
- elif legacy_proxy:
206
- selected_proxy = legacy_proxy
207
- source = "global"
208
-
209
- return ProxyRuntimeProfile(
210
- proxy_url=normalize_proxy_url(selected_proxy),
211
- proxy_source=source,
212
- resource=bool(resource),
213
- runtime_enabled=runtime_enabled,
214
- egress_mode=egress_mode,
215
- skip_ssl_verify=bool(runtime.get("skip_ssl_verify")) if runtime_enabled else False,
216
- reset_session_status_codes=_status_codes_tuple(runtime.get("reset_session_status_codes")),
217
- clearance=clearance,
218
- )
219
-
220
- def build_session_kwargs(
221
- self,
222
- account: dict | None = None,
223
- proxy: str = "",
224
- resource: bool = False,
225
- upstream: bool = False,
226
- **session_kwargs,
227
- ) -> dict[str, object]:
228
- profile = self.get_profile(account=account, proxy=proxy, resource=resource, upstream=upstream)
229
- if profile.proxy_url:
230
- session_kwargs["proxy"] = profile.proxy_url
231
- if profile.runtime_enabled and profile.skip_ssl_verify:
232
- session_kwargs["verify"] = False
233
- return session_kwargs
234
-
235
- def build_headers(
236
- self,
237
- headers: Mapping[str, object] | None = None,
238
- target_url: str = "https://chatgpt.com",
239
- account: dict | None = None,
240
- proxy: str = "",
241
- resource: bool = False,
242
- upstream: bool = True,
243
- ) -> dict[str, object]:
244
- merged_headers: dict[str, object] = dict(headers or {})
245
- profile = self.get_profile(account=account, proxy=proxy, resource=resource, upstream=upstream)
246
- if not profile.clearance_enabled:
247
- return merged_headers
248
-
249
- target_host = _host_from_url(target_url)
250
- bundle = self._bundle_for_headers(profile, target_host)
251
- if bundle is None or not bundle.is_valid_for(target_host, profile.proxy_url):
252
- return merged_headers
253
-
254
- if bundle.user_agent and _find_header_key(merged_headers, "user-agent") is None:
255
- merged_headers["User-Agent"] = bundle.user_agent
256
-
257
- if bundle.cookies:
258
- cookie_key = _find_header_key(merged_headers, "cookie") or "Cookie"
259
- existing_cookie = str(merged_headers.get(cookie_key) or "")
260
- cookie_header = _merge_cookie_header(existing_cookie, bundle.cookies)
261
- if cookie_header:
262
- merged_headers[cookie_key] = cookie_header
263
- return merged_headers
264
-
265
- def refresh_clearance(
266
- self,
267
- target_url: str = "https://chatgpt.com",
268
- account: dict | None = None,
269
- proxy: str = "",
270
- resource: bool = False,
271
- force: bool = False,
272
- upstream: bool = True,
273
- ) -> ClearanceBundle | None:
274
- profile = self.get_profile(account=account, proxy=proxy, resource=resource, upstream=upstream)
275
- if not profile.clearance_enabled:
276
- return None
277
-
278
- target_host = _host_from_url(target_url)
279
- key = self._cache_key(profile.proxy_url, target_host)
280
- if profile.clearance_mode == "manual":
281
- bundle = self._build_manual_bundle(profile, target_host)
282
- if bundle is not None:
283
- self._set_cached_bundle(key, bundle)
284
- return bundle
285
- if profile.clearance_mode != "flaresolverr":
286
- return None
287
-
288
- cached_before = self._get_cached_bundle(key)
289
- if cached_before is not None and not force and cached_before.is_valid_for(target_host, profile.proxy_url):
290
- return cached_before
291
-
292
- lock = self._get_flight_lock(key)
293
- if not lock.acquire(blocking=False):
294
- with lock:
295
- pass
296
- return self._get_cached_bundle(key) or cached_before
297
-
298
- try:
299
- cached_now = self._get_cached_bundle(key)
300
- if cached_now is not None and not force and cached_now.is_valid_for(target_host, profile.proxy_url):
301
- return cached_now
302
-
303
- flaresolverr_url = str(profile.clearance.get("flaresolverr_url") or "").strip()
304
- provider = self._get_provider(flaresolverr_url)
305
- new_bundle = provider.get_clearance(target_url, proxy_url=profile.proxy_url, timeout_sec=profile.timeout_sec)
306
- if new_bundle is not None:
307
- expires_at = time.time() + profile.refresh_interval if profile.refresh_interval else None
308
- if (
309
- not new_bundle.target_host
310
- or normalize_proxy_url(new_bundle.proxy_url) != normalize_proxy_url(profile.proxy_url)
311
- or new_bundle.expires_at != expires_at
312
- ):
313
- new_bundle = replace(
314
- new_bundle,
315
- target_host=new_bundle.target_host or target_host,
316
- proxy_url=profile.proxy_url,
317
- expires_at=expires_at,
318
- )
319
- self._set_cached_bundle(key, new_bundle)
320
- return new_bundle
321
- return cached_now or cached_before
322
- finally:
323
- lock.release()
324
-
325
- def invalidate_clearance(
326
- self,
327
- target_url: str = "https://chatgpt.com",
328
- account: dict | None = None,
329
- proxy: str = "",
330
- resource: bool = False,
331
- upstream: bool = True,
332
- ) -> None:
333
- profile = self.get_profile(account=account, proxy=proxy, resource=resource, upstream=upstream)
334
- target_host = _host_from_url(target_url)
335
- key = self._cache_key(profile.proxy_url, target_host)
336
- with self._lock:
337
- self._clearance_cache.pop(key, None)
338
-
339
- def get_runtime_status(self) -> dict[str, object]:
340
- profile = self.get_profile(upstream=True)
341
- with self._lock:
342
- cached_hosts = [host for _proxy, host in self._clearance_cache]
343
- cached_count = len(self._clearance_cache)
344
- return {
345
- "enabled": profile.runtime_enabled,
346
- "egress_mode": profile.egress_mode,
347
- "proxy_source": profile.proxy_source,
348
- "has_proxy": bool(profile.proxy_url),
349
- "clearance_enabled": profile.clearance_enabled,
350
- "clearance_mode": profile.clearance_mode,
351
- "has_clearance_bundle": cached_count > 0,
352
- "cached_clearance_hosts": sorted(set(cached_hosts)),
353
- }
354
-
355
- def _get_runtime_settings(self) -> dict[str, object]:
356
- try:
357
- runtime = self._config.get_proxy_runtime_settings()
358
- except AttributeError:
359
- runtime = {}
360
- return runtime if isinstance(runtime, dict) else {}
361
-
362
- def _bundle_for_headers(self, profile: ProxyRuntimeProfile, target_host: str) -> ClearanceBundle | None:
363
- key = self._cache_key(profile.proxy_url, target_host)
364
- if profile.clearance_mode == "manual":
365
- bundle = self._build_manual_bundle(profile, target_host)
366
- if bundle is not None:
367
- self._set_cached_bundle(key, bundle)
368
- return bundle
369
- if profile.clearance_mode == "flaresolverr":
370
- return self._get_cached_bundle(key)
371
- return None
372
-
373
- def _build_manual_bundle(self, profile: ProxyRuntimeProfile, target_host: str) -> ClearanceBundle | None:
374
- cookies = _parse_cookie_header(str(profile.clearance.get("cf_cookies") or ""))
375
- cf_clearance = str(profile.clearance.get("cf_clearance") or "").strip()
376
- if cf_clearance and "cf_clearance" not in cookies:
377
- cookies["cf_clearance"] = cf_clearance
378
- user_agent = str(profile.clearance.get("user_agent") or "").strip()
379
- if not cookies and not user_agent:
380
- return None
381
-
382
- now = time.time()
383
- expires_at = now + profile.refresh_interval if profile.refresh_interval else None
384
- return ClearanceBundle(
385
- target_host=target_host,
386
- proxy_url=profile.proxy_url,
387
- cookies=cookies,
388
- user_agent=user_agent,
389
- created_at=now,
390
- expires_at=expires_at,
391
- )
392
-
393
- def _get_provider(self, flaresolverr_url: str) -> FlareSolverrClearanceProvider:
394
- url = str(flaresolverr_url or "").strip().rstrip("/")
395
- with self._lock:
396
- provider = self._provider_cache.get(url)
397
- if provider is None:
398
- provider = self._clearance_provider_factory(url)
399
- self._provider_cache[url] = provider
400
- return provider
401
-
402
- def _get_flight_lock(self, key: tuple[str, str]) -> threading.Lock:
403
- with self._lock:
404
- lock = self._flight_locks.get(key)
405
- if lock is None:
406
- lock = threading.Lock()
407
- self._flight_locks[key] = lock
408
- return lock
409
-
410
- def _get_cached_bundle(self, key: tuple[str, str]) -> ClearanceBundle | None:
411
- with self._lock:
412
- return self._clearance_cache.get(key)
413
-
414
- def _set_cached_bundle(self, key: tuple[str, str], bundle: ClearanceBundle) -> None:
415
- with self._lock:
416
- self._clearance_cache[key] = bundle
417
-
418
- @staticmethod
419
- def _cache_key(proxy_url: str, target_host: str) -> tuple[str, str]:
420
- return (normalize_proxy_url(proxy_url), _normalize_host(target_host))
421
-
422
-
423
- def _clean(value: object) -> str:
424
- return str(value or "").strip()
425
-
426
-
427
- def _colon_proxy_to_url(url: str) -> str:
428
- parts = url.split(":", 3)
429
- if len(parts) == 4 and parts[1].isdigit():
430
- host, port, username, password = parts
431
- return f"http://{quote(username, safe='')}:{quote(password, safe='')}@{host}:{port}"
432
- if len(parts) == 2 and parts[1].isdigit():
433
- return f"http://{url}"
434
- return url
435
-
436
-
437
- def _normalize_host(host: str) -> str:
438
- return str(host or "").strip().strip(".").lower()
439
-
440
-
441
- def _host_from_url(url: str) -> str:
442
- candidate = str(url or "").strip()
443
- parsed = urlparse(candidate)
444
- if not parsed.hostname and candidate and "://" not in candidate:
445
- parsed = urlparse(f"https://{candidate}")
446
- return _normalize_host(parsed.hostname or "")
447
-
448
-
449
- def _status_codes_tuple(value: object) -> tuple[int, ...]:
450
- source = value if isinstance(value, list) else [403]
451
- codes: list[int] = []
452
- for item in source:
453
- if isinstance(item, bool):
454
- continue
455
- try:
456
- code = int(item)
457
- except (OverflowError, TypeError, ValueError):
458
- continue
459
- if 100 <= code <= 599 and code not in codes:
460
- codes.append(code)
461
- return tuple(codes or [403])
462
-
463
-
464
- def _coerce_timeout(value: object) -> float:
465
- try:
466
- timeout = float(value)
467
- except (OverflowError, TypeError, ValueError):
468
- timeout = 60.0
469
- return max(1.0, timeout)
470
-
471
-
472
- def _is_valid_proxy_url(url: str) -> bool:
473
- parsed = urlparse(normalize_proxy_url(url))
474
- return parsed.scheme in {"http", "https", "socks5", "socks5h"} and bool(parsed.netloc)
475
-
476
-
477
- def _domain_matches(host: str, domain: str) -> bool:
478
- normalized_host = _normalize_host(host)
479
- normalized_domain = _normalize_host(domain.lstrip("."))
480
- if not normalized_domain:
481
- return True
482
- return normalized_host == normalized_domain or normalized_host.endswith(f".{normalized_domain}")
483
-
484
-
485
- def _filter_flaresolverr_cookies(raw_cookies: object, target_host: str) -> dict[str, str]:
486
- if not isinstance(raw_cookies, list):
487
- return {}
488
-
489
- filtered_cookies: dict[str, str] = {}
490
- for item in raw_cookies:
491
- if not isinstance(item, dict):
492
- continue
493
- name = str(item.get("name") or "").strip()
494
- if not name:
495
- continue
496
- value = str(item.get("value") or "")
497
- domain = str(item.get("domain") or "").strip()
498
- if not domain or _domain_matches(target_host, domain):
499
- filtered_cookies[name] = value
500
- return filtered_cookies
501
-
502
-
503
- def _parse_cookie_header(header: str) -> dict[str, str]:
504
- cookies: dict[str, str] = {}
505
- for part in str(header or "").split(";"):
506
- name, sep, value = part.strip().partition("=")
507
- if sep and name:
508
- cookies[name.strip()] = value.strip()
509
- return cookies
510
-
511
-
512
- def _cookies_to_header(cookies: Mapping[str, str]) -> str:
513
- return "; ".join(f"{name}={value}" for name, value in cookies.items() if name)
514
-
515
-
516
- def _merge_cookie_header(existing_header: str, cookies: Mapping[str, str]) -> str:
517
- existing = str(existing_header or "").strip()
518
- existing_names = set(_parse_cookie_header(existing).keys())
519
- additions = [f"{name}={value}" for name, value in cookies.items() if name and name not in existing_names]
520
- if existing and additions:
521
- return existing.rstrip("; ") + "; " + "; ".join(additions)
522
- if existing:
523
- return existing
524
- return "; ".join(additions)
525
-
526
-
527
- def _find_header_key(headers: Mapping[str, object], name: str) -> str | None:
528
- target = name.lower()
529
- for key in headers:
530
- if str(key).lower() == target:
531
- return str(key)
532
- return None
533
-
534
-
535
- def _redact_url_credentials(text: str) -> str:
536
- return re.sub(
537
- r"((?:https?|socks5h?|socks)://)([^\s/@:]+):([^\s/@]+)@",
538
- r"\1[REDACTED]@",
539
- str(text or ""),
540
- flags=re.IGNORECASE,
541
- )
542
-
543
-
544
- def test_proxy(url: str = "", *, timeout: float = 15.0) -> dict:
545
- candidate = normalize_proxy_url(_clean(url))
546
- proxy_source = "input"
547
- if not candidate:
548
- profile = proxy_settings.get_profile(upstream=True)
549
- candidate = profile.proxy_url
550
- proxy_source = profile.proxy_source
551
- result_base = {"proxy_source": proxy_source, "has_proxy": bool(candidate)}
552
- if not candidate:
553
- return {
554
- "ok": False,
555
- "status": 0,
556
- "latency_ms": 0,
557
- "error": "no active proxy configured",
558
- **result_base,
559
- }
560
- if not _is_valid_proxy_url(candidate):
561
- return {
562
- "ok": False,
563
- "status": 0,
564
- "latency_ms": 0,
565
- "error": "invalid proxy url",
566
- **result_base,
567
- }
568
- session = Session(impersonate="edge101", verify=True, proxy=candidate)
569
- started = time.perf_counter()
570
- try:
571
- response = session.get(
572
- "https://chatgpt.com/api/auth/csrf",
573
- headers={"user-agent": "Mozilla/5.0 (chatgpt2api proxy test)"},
574
- timeout=timeout,
575
- )
576
- latency_ms = int((time.perf_counter() - started) * 1000)
577
- return {
578
- "ok": response.status_code < 500,
579
- "status": int(response.status_code),
580
- "latency_ms": latency_ms,
581
- "error": None if response.status_code < 500 else f"HTTP {response.status_code}",
582
- **result_base,
583
- }
584
- except Exception as exc:
585
- latency_ms = int((time.perf_counter() - started) * 1000)
586
- return {
587
- "ok": False,
588
- "status": 0,
589
- "latency_ms": latency_ms,
590
- "error": _redact_url_credentials(str(exc) or exc.__class__.__name__),
591
- **result_base,
592
- }
593
- finally:
594
- session.close()
595
-
596
-
597
- def test_clearance(target_url: str = "https://chatgpt.com") -> dict:
598
- target_url = str(target_url or "https://chatgpt.com").strip() or "https://chatgpt.com"
599
- started = time.perf_counter()
600
- status = proxy_settings.get_runtime_status()
601
- if not status.get("clearance_enabled"):
602
- return {
603
- "ok": False,
604
- "status": "disabled",
605
- "latency_ms": 0,
606
- "has_cookies": False,
607
- "user_agent": "",
608
- "error": "clearance is disabled",
609
- "runtime": status,
610
- }
611
- try:
612
- bundle = proxy_settings.refresh_clearance(target_url=target_url, force=True, upstream=True)
613
- except Exception as exc:
614
- latency_ms = int((time.perf_counter() - started) * 1000)
615
- return {
616
- "ok": False,
617
- "status": "error",
618
- "latency_ms": latency_ms,
619
- "has_cookies": False,
620
- "user_agent": "",
621
- "error": _redact_url_credentials(str(exc) or exc.__class__.__name__),
622
- "runtime": proxy_settings.get_runtime_status(),
623
- }
624
-
625
- latency_ms = int((time.perf_counter() - started) * 1000)
626
- runtime = proxy_settings.get_runtime_status()
627
- if bundle is None:
628
- return {
629
- "ok": False,
630
- "status": "failed",
631
- "latency_ms": latency_ms,
632
- "has_cookies": False,
633
- "user_agent": "",
634
- "error": "clearance refresh returned no bundle",
635
- "runtime": runtime,
636
- }
637
- return {
638
- "ok": True,
639
- "status": "ok",
640
- "latency_ms": latency_ms,
641
- "has_cookies": bool(bundle.cookies),
642
- "user_agent": bundle.user_agent or "",
643
- "error": None,
644
- "runtime": runtime,
645
- }
646
-
647
-
648
- proxy_settings = ProxySettingsStore()
1
+ """Global outbound proxy and Cloudflare clearance helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field, replace
6
+ import json
7
+ import re
8
+ import threading
9
+ import time
10
+ from typing import Callable, Mapping
11
+ from urllib import request as urllib_request
12
+ from urllib.parse import quote, urlparse
13
+
14
+ from curl_cffi.requests import Session
15
+
16
+ from services.config import config
17
+
18
+
19
+ FlareSolverrRequestMethod = Callable[[str, bytes, dict[str, str], float], bytes]
20
+
21
+
22
+ def normalize_proxy_url(url: str) -> str:
23
+ """Normalize proxy URLs for curl_cffi.
24
+
25
+ SOCKS proxies should use remote-DNS resolution by default, so generic
26
+ ``socks://`` and ``socks5://`` inputs are upgraded to ``socks5h://``.
27
+ HTTP/HTTPS/socks5h inputs are otherwise left untouched except trimming.
28
+ """
29
+ candidate = str(url or "").strip()
30
+ if candidate and "://" not in candidate:
31
+ candidate = _colon_proxy_to_url(candidate)
32
+ lowered = candidate.lower()
33
+ if lowered.startswith("socks://"):
34
+ return "socks5h://" + candidate[len("socks://") :]
35
+ if lowered.startswith("socks5://"):
36
+ return "socks5h://" + candidate[len("socks5://") :]
37
+ return candidate
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class ProxyRuntimeProfile:
42
+ proxy_url: str = ""
43
+ proxy_source: str = "direct"
44
+ resource: bool = False
45
+ runtime_enabled: bool = False
46
+ egress_mode: str = "direct"
47
+ skip_ssl_verify: bool = False
48
+ reset_session_status_codes: tuple[int, ...] = field(default_factory=lambda: (403,))
49
+ clearance: dict[str, object] = field(default_factory=dict, repr=False)
50
+
51
+ @property
52
+ def clearance_enabled(self) -> bool:
53
+ return (
54
+ self.runtime_enabled
55
+ and bool(self.clearance.get("enabled"))
56
+ and self.clearance_mode in {"manual", "flaresolverr"}
57
+ )
58
+
59
+ @property
60
+ def clearance_mode(self) -> str:
61
+ return str(self.clearance.get("mode") or "none").strip().lower()
62
+
63
+ @property
64
+ def refresh_interval(self) -> int:
65
+ try:
66
+ return max(0, int(self.clearance.get("refresh_interval") or 0))
67
+ except (OverflowError, TypeError, ValueError):
68
+ return 0
69
+
70
+ @property
71
+ def timeout_sec(self) -> int:
72
+ try:
73
+ return max(1, int(self.clearance.get("timeout_sec") or 60))
74
+ except (OverflowError, TypeError, ValueError):
75
+ return 60
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class ClearanceBundle:
80
+ target_host: str
81
+ proxy_url: str = ""
82
+ cookies: dict[str, str] = field(default_factory=dict, repr=False)
83
+ user_agent: str = ""
84
+ created_at: float = field(default_factory=time.time)
85
+ expires_at: float | None = None
86
+
87
+ def is_valid_for(self, target_host: str, proxy_url: str, *, now: float | None = None) -> bool:
88
+ host = _normalize_host(target_host)
89
+ if self.target_host and host and _normalize_host(self.target_host) != host:
90
+ return False
91
+ if normalize_proxy_url(self.proxy_url) != normalize_proxy_url(proxy_url):
92
+ return False
93
+ if self.expires_at is not None and (time.time() if now is None else now) >= self.expires_at:
94
+ return False
95
+ return bool(self.cookies or self.user_agent)
96
+
97
+ def cookie_header(self) -> str:
98
+ return _cookies_to_header(self.cookies)
99
+
100
+
101
+ class FlareSolverrClearanceProvider:
102
+ def __init__(self, flaresolverr_url: str, request_method: FlareSolverrRequestMethod | None = None) -> None:
103
+ self.flaresolverr_url = str(flaresolverr_url or "").strip().rstrip("/")
104
+ self._request_method = request_method or self._urllib_post
105
+
106
+ def get_clearance(self, target_url: str, proxy_url: str = "", timeout_sec: int = 60) -> ClearanceBundle | None:
107
+ if not self.flaresolverr_url:
108
+ return None
109
+
110
+ timeout = _coerce_timeout(timeout_sec)
111
+ payload: dict[str, object] = {
112
+ "cmd": "request.get",
113
+ "url": str(target_url or ""),
114
+ "maxTimeout": int(timeout * 1000),
115
+ }
116
+ proxy_url = normalize_proxy_url(proxy_url)
117
+ if proxy_url:
118
+ payload["proxy"] = {"url": proxy_url}
119
+
120
+ endpoint = f"{self.flaresolverr_url}/v1"
121
+ try:
122
+ body = json.dumps(payload).encode("utf-8")
123
+ raw_response = self._request_method(
124
+ endpoint,
125
+ body,
126
+ {"Content-Type": "application/json"},
127
+ timeout,
128
+ )
129
+ data = json.loads(raw_response.decode("utf-8") if isinstance(raw_response, bytes) else raw_response)
130
+ except Exception:
131
+ return None
132
+
133
+ if not isinstance(data, dict) or str(data.get("status") or "").lower() != "ok":
134
+ return None
135
+ solution = data.get("solution")
136
+ if not isinstance(solution, dict):
137
+ return None
138
+
139
+ target_host = _host_from_url(target_url)
140
+ cookies = _filter_flaresolverr_cookies(solution.get("cookies"), target_host)
141
+ user_agent = str(solution.get("userAgent") or "").strip()
142
+ if not cookies and not user_agent:
143
+ return None
144
+ return ClearanceBundle(
145
+ target_host=target_host,
146
+ proxy_url=proxy_url,
147
+ cookies=cookies,
148
+ user_agent=user_agent,
149
+ )
150
+
151
+ @staticmethod
152
+ def _urllib_post(endpoint: str, body: bytes, headers: dict[str, str], timeout: float) -> bytes:
153
+ req = urllib_request.Request(endpoint, data=body, headers=headers, method="POST")
154
+ with urllib_request.urlopen(req, timeout=timeout) as response:
155
+ return response.read()
156
+
157
+
158
+ class ProxySettingsStore:
159
+ def __init__(
160
+ self,
161
+ config_store=None,
162
+ clearance_provider_factory: Callable[[str], FlareSolverrClearanceProvider] | None = None,
163
+ ) -> None:
164
+ self._config = config_store or config
165
+ self._clearance_provider_factory = clearance_provider_factory or FlareSolverrClearanceProvider
166
+ self._clearance_cache: dict[tuple[str, str], ClearanceBundle] = {}
167
+ self._provider_cache: dict[str, FlareSolverrClearanceProvider] = {}
168
+ self._flight_locks: dict[tuple[str, str], threading.Lock] = {}
169
+ self._lock = threading.RLock()
170
+
171
+ def get_profile(
172
+ self,
173
+ account: dict | None = None,
174
+ proxy: str = "",
175
+ resource: bool = False,
176
+ upstream: bool = False,
177
+ ) -> ProxyRuntimeProfile:
178
+ runtime = self._get_runtime_settings()
179
+ clearance = dict(runtime.get("clearance") if isinstance(runtime.get("clearance"), dict) else {})
180
+ runtime_enabled = bool(runtime.get("enabled"))
181
+ egress_mode = str(runtime.get("egress_mode") or "direct").strip().lower()
182
+
183
+ account_proxy = _clean((account or {}).get("proxy") if isinstance(account, dict) else "")
184
+ explicit_proxy = _clean(proxy)
185
+ legacy_proxy = _clean(self._config.get_proxy_settings())
186
+
187
+ runtime_proxy = ""
188
+ runtime_proxy_source = "runtime"
189
+ if upstream and runtime_enabled and egress_mode == "single_proxy":
190
+ resource_proxy = _clean(runtime.get("resource_proxy_url")) if resource else ""
191
+ runtime_proxy = resource_proxy or _clean(runtime.get("proxy_url"))
192
+ runtime_proxy_source = "runtime_resource" if resource_proxy else "runtime"
193
+
194
+ selected_proxy = ""
195
+ source = "direct"
196
+ if account_proxy:
197
+ selected_proxy = account_proxy
198
+ source = "account"
199
+ elif runtime_proxy:
200
+ selected_proxy = runtime_proxy
201
+ source = runtime_proxy_source
202
+ elif explicit_proxy:
203
+ selected_proxy = explicit_proxy
204
+ source = "explicit"
205
+ elif legacy_proxy:
206
+ selected_proxy = legacy_proxy
207
+ source = "global"
208
+
209
+ return ProxyRuntimeProfile(
210
+ proxy_url=normalize_proxy_url(selected_proxy),
211
+ proxy_source=source,
212
+ resource=bool(resource),
213
+ runtime_enabled=runtime_enabled,
214
+ egress_mode=egress_mode,
215
+ skip_ssl_verify=bool(runtime.get("skip_ssl_verify")) if runtime_enabled else False,
216
+ reset_session_status_codes=_status_codes_tuple(runtime.get("reset_session_status_codes")),
217
+ clearance=clearance,
218
+ )
219
+
220
+ def build_session_kwargs(
221
+ self,
222
+ account: dict | None = None,
223
+ proxy: str = "",
224
+ resource: bool = False,
225
+ upstream: bool = False,
226
+ **session_kwargs,
227
+ ) -> dict[str, object]:
228
+ profile = self.get_profile(account=account, proxy=proxy, resource=resource, upstream=upstream)
229
+ if profile.proxy_url:
230
+ session_kwargs["proxy"] = profile.proxy_url
231
+ if profile.runtime_enabled and profile.skip_ssl_verify:
232
+ session_kwargs["verify"] = False
233
+ return session_kwargs
234
+
235
+ def build_headers(
236
+ self,
237
+ headers: Mapping[str, object] | None = None,
238
+ target_url: str = "https://chatgpt.com",
239
+ account: dict | None = None,
240
+ proxy: str = "",
241
+ resource: bool = False,
242
+ upstream: bool = True,
243
+ ) -> dict[str, object]:
244
+ merged_headers: dict[str, object] = dict(headers or {})
245
+ profile = self.get_profile(account=account, proxy=proxy, resource=resource, upstream=upstream)
246
+ if not profile.clearance_enabled:
247
+ return merged_headers
248
+
249
+ target_host = _host_from_url(target_url)
250
+ bundle = self._bundle_for_headers(profile, target_host)
251
+ if bundle is None or not bundle.is_valid_for(target_host, profile.proxy_url):
252
+ return merged_headers
253
+
254
+ if bundle.user_agent and _find_header_key(merged_headers, "user-agent") is None:
255
+ merged_headers["User-Agent"] = bundle.user_agent
256
+
257
+ if bundle.cookies:
258
+ cookie_key = _find_header_key(merged_headers, "cookie") or "Cookie"
259
+ existing_cookie = str(merged_headers.get(cookie_key) or "")
260
+ cookie_header = _merge_cookie_header(existing_cookie, bundle.cookies)
261
+ if cookie_header:
262
+ merged_headers[cookie_key] = cookie_header
263
+ return merged_headers
264
+
265
+ def refresh_clearance(
266
+ self,
267
+ target_url: str = "https://chatgpt.com",
268
+ account: dict | None = None,
269
+ proxy: str = "",
270
+ resource: bool = False,
271
+ force: bool = False,
272
+ upstream: bool = True,
273
+ ) -> ClearanceBundle | None:
274
+ profile = self.get_profile(account=account, proxy=proxy, resource=resource, upstream=upstream)
275
+ if not profile.clearance_enabled:
276
+ return None
277
+
278
+ target_host = _host_from_url(target_url)
279
+ key = self._cache_key(profile.proxy_url, target_host)
280
+ if profile.clearance_mode == "manual":
281
+ bundle = self._build_manual_bundle(profile, target_host)
282
+ if bundle is not None:
283
+ self._set_cached_bundle(key, bundle)
284
+ return bundle
285
+ if profile.clearance_mode != "flaresolverr":
286
+ return None
287
+
288
+ cached_before = self._get_cached_bundle(key)
289
+ if cached_before is not None and not force and cached_before.is_valid_for(target_host, profile.proxy_url):
290
+ return cached_before
291
+
292
+ lock = self._get_flight_lock(key)
293
+ if not lock.acquire(blocking=False):
294
+ with lock:
295
+ pass
296
+ return self._get_cached_bundle(key) or cached_before
297
+
298
+ try:
299
+ cached_now = self._get_cached_bundle(key)
300
+ if cached_now is not None and not force and cached_now.is_valid_for(target_host, profile.proxy_url):
301
+ return cached_now
302
+
303
+ flaresolverr_url = str(profile.clearance.get("flaresolverr_url") or "").strip()
304
+ provider = self._get_provider(flaresolverr_url)
305
+ new_bundle = provider.get_clearance(target_url, proxy_url=profile.proxy_url, timeout_sec=profile.timeout_sec)
306
+ if new_bundle is not None:
307
+ expires_at = time.time() + profile.refresh_interval if profile.refresh_interval else None
308
+ if (
309
+ not new_bundle.target_host
310
+ or normalize_proxy_url(new_bundle.proxy_url) != normalize_proxy_url(profile.proxy_url)
311
+ or new_bundle.expires_at != expires_at
312
+ ):
313
+ new_bundle = replace(
314
+ new_bundle,
315
+ target_host=new_bundle.target_host or target_host,
316
+ proxy_url=profile.proxy_url,
317
+ expires_at=expires_at,
318
+ )
319
+ self._set_cached_bundle(key, new_bundle)
320
+ return new_bundle
321
+ return cached_now or cached_before
322
+ finally:
323
+ lock.release()
324
+
325
+ def invalidate_clearance(
326
+ self,
327
+ target_url: str = "https://chatgpt.com",
328
+ account: dict | None = None,
329
+ proxy: str = "",
330
+ resource: bool = False,
331
+ upstream: bool = True,
332
+ ) -> None:
333
+ profile = self.get_profile(account=account, proxy=proxy, resource=resource, upstream=upstream)
334
+ target_host = _host_from_url(target_url)
335
+ key = self._cache_key(profile.proxy_url, target_host)
336
+ with self._lock:
337
+ self._clearance_cache.pop(key, None)
338
+
339
+ def get_runtime_status(self) -> dict[str, object]:
340
+ profile = self.get_profile(upstream=True)
341
+ with self._lock:
342
+ cached_hosts = [host for _proxy, host in self._clearance_cache]
343
+ cached_count = len(self._clearance_cache)
344
+ return {
345
+ "enabled": profile.runtime_enabled,
346
+ "egress_mode": profile.egress_mode,
347
+ "proxy_source": profile.proxy_source,
348
+ "has_proxy": bool(profile.proxy_url),
349
+ "clearance_enabled": profile.clearance_enabled,
350
+ "clearance_mode": profile.clearance_mode,
351
+ "has_clearance_bundle": cached_count > 0,
352
+ "cached_clearance_hosts": sorted(set(cached_hosts)),
353
+ }
354
+
355
+ def _get_runtime_settings(self) -> dict[str, object]:
356
+ try:
357
+ runtime = self._config.get_proxy_runtime_settings()
358
+ except AttributeError:
359
+ runtime = {}
360
+ return runtime if isinstance(runtime, dict) else {}
361
+
362
+ def _bundle_for_headers(self, profile: ProxyRuntimeProfile, target_host: str) -> ClearanceBundle | None:
363
+ key = self._cache_key(profile.proxy_url, target_host)
364
+ if profile.clearance_mode == "manual":
365
+ bundle = self._build_manual_bundle(profile, target_host)
366
+ if bundle is not None:
367
+ self._set_cached_bundle(key, bundle)
368
+ return bundle
369
+ if profile.clearance_mode == "flaresolverr":
370
+ return self._get_cached_bundle(key)
371
+ return None
372
+
373
+ def _build_manual_bundle(self, profile: ProxyRuntimeProfile, target_host: str) -> ClearanceBundle | None:
374
+ cookies = _parse_cookie_header(str(profile.clearance.get("cf_cookies") or ""))
375
+ cf_clearance = str(profile.clearance.get("cf_clearance") or "").strip()
376
+ if cf_clearance and "cf_clearance" not in cookies:
377
+ cookies["cf_clearance"] = cf_clearance
378
+ user_agent = str(profile.clearance.get("user_agent") or "").strip()
379
+ if not cookies and not user_agent:
380
+ return None
381
+
382
+ now = time.time()
383
+ expires_at = now + profile.refresh_interval if profile.refresh_interval else None
384
+ return ClearanceBundle(
385
+ target_host=target_host,
386
+ proxy_url=profile.proxy_url,
387
+ cookies=cookies,
388
+ user_agent=user_agent,
389
+ created_at=now,
390
+ expires_at=expires_at,
391
+ )
392
+
393
+ def _get_provider(self, flaresolverr_url: str) -> FlareSolverrClearanceProvider:
394
+ url = str(flaresolverr_url or "").strip().rstrip("/")
395
+ with self._lock:
396
+ provider = self._provider_cache.get(url)
397
+ if provider is None:
398
+ provider = self._clearance_provider_factory(url)
399
+ self._provider_cache[url] = provider
400
+ return provider
401
+
402
+ def _get_flight_lock(self, key: tuple[str, str]) -> threading.Lock:
403
+ with self._lock:
404
+ lock = self._flight_locks.get(key)
405
+ if lock is None:
406
+ lock = threading.Lock()
407
+ self._flight_locks[key] = lock
408
+ return lock
409
+
410
+ def _get_cached_bundle(self, key: tuple[str, str]) -> ClearanceBundle | None:
411
+ with self._lock:
412
+ return self._clearance_cache.get(key)
413
+
414
+ def _set_cached_bundle(self, key: tuple[str, str], bundle: ClearanceBundle) -> None:
415
+ with self._lock:
416
+ self._clearance_cache[key] = bundle
417
+
418
+ @staticmethod
419
+ def _cache_key(proxy_url: str, target_host: str) -> tuple[str, str]:
420
+ return (normalize_proxy_url(proxy_url), _normalize_host(target_host))
421
+
422
+
423
+ def _clean(value: object) -> str:
424
+ return str(value or "").strip()
425
+
426
+
427
+ def _colon_proxy_to_url(url: str) -> str:
428
+ parts = url.split(":", 3)
429
+ if len(parts) == 4 and parts[1].isdigit():
430
+ host, port, username, password = parts
431
+ return f"http://{quote(username, safe='')}:{quote(password, safe='')}@{host}:{port}"
432
+ if len(parts) == 2 and parts[1].isdigit():
433
+ return f"http://{url}"
434
+ return url
435
+
436
+
437
+ def _normalize_host(host: str) -> str:
438
+ return str(host or "").strip().strip(".").lower()
439
+
440
+
441
+ def _host_from_url(url: str) -> str:
442
+ candidate = str(url or "").strip()
443
+ parsed = urlparse(candidate)
444
+ if not parsed.hostname and candidate and "://" not in candidate:
445
+ parsed = urlparse(f"https://{candidate}")
446
+ return _normalize_host(parsed.hostname or "")
447
+
448
+
449
+ def _status_codes_tuple(value: object) -> tuple[int, ...]:
450
+ source = value if isinstance(value, list) else [403]
451
+ codes: list[int] = []
452
+ for item in source:
453
+ if isinstance(item, bool):
454
+ continue
455
+ try:
456
+ code = int(item)
457
+ except (OverflowError, TypeError, ValueError):
458
+ continue
459
+ if 100 <= code <= 599 and code not in codes:
460
+ codes.append(code)
461
+ return tuple(codes or [403])
462
+
463
+
464
+ def _coerce_timeout(value: object) -> float:
465
+ try:
466
+ timeout = float(value)
467
+ except (OverflowError, TypeError, ValueError):
468
+ timeout = 60.0
469
+ return max(1.0, timeout)
470
+
471
+
472
+ def _is_valid_proxy_url(url: str) -> bool:
473
+ parsed = urlparse(normalize_proxy_url(url))
474
+ return parsed.scheme in {"http", "https", "socks5", "socks5h"} and bool(parsed.netloc)
475
+
476
+
477
+ def _domain_matches(host: str, domain: str) -> bool:
478
+ normalized_host = _normalize_host(host)
479
+ normalized_domain = _normalize_host(domain.lstrip("."))
480
+ if not normalized_domain:
481
+ return True
482
+ return normalized_host == normalized_domain or normalized_host.endswith(f".{normalized_domain}")
483
+
484
+
485
+ def _filter_flaresolverr_cookies(raw_cookies: object, target_host: str) -> dict[str, str]:
486
+ if not isinstance(raw_cookies, list):
487
+ return {}
488
+
489
+ filtered_cookies: dict[str, str] = {}
490
+ for item in raw_cookies:
491
+ if not isinstance(item, dict):
492
+ continue
493
+ name = str(item.get("name") or "").strip()
494
+ if not name:
495
+ continue
496
+ value = str(item.get("value") or "")
497
+ domain = str(item.get("domain") or "").strip()
498
+ if not domain or _domain_matches(target_host, domain):
499
+ filtered_cookies[name] = value
500
+ return filtered_cookies
501
+
502
+
503
+ def _parse_cookie_header(header: str) -> dict[str, str]:
504
+ cookies: dict[str, str] = {}
505
+ for part in str(header or "").split(";"):
506
+ name, sep, value = part.strip().partition("=")
507
+ if sep and name:
508
+ cookies[name.strip()] = value.strip()
509
+ return cookies
510
+
511
+
512
+ def _cookies_to_header(cookies: Mapping[str, str]) -> str:
513
+ return "; ".join(f"{name}={value}" for name, value in cookies.items() if name)
514
+
515
+
516
+ def _merge_cookie_header(existing_header: str, cookies: Mapping[str, str]) -> str:
517
+ existing = str(existing_header or "").strip()
518
+ existing_names = set(_parse_cookie_header(existing).keys())
519
+ additions = [f"{name}={value}" for name, value in cookies.items() if name and name not in existing_names]
520
+ if existing and additions:
521
+ return existing.rstrip("; ") + "; " + "; ".join(additions)
522
+ if existing:
523
+ return existing
524
+ return "; ".join(additions)
525
+
526
+
527
+ def _find_header_key(headers: Mapping[str, object], name: str) -> str | None:
528
+ target = name.lower()
529
+ for key in headers:
530
+ if str(key).lower() == target:
531
+ return str(key)
532
+ return None
533
+
534
+
535
+ def _redact_url_credentials(text: str) -> str:
536
+ return re.sub(
537
+ r"((?:https?|socks5h?|socks)://)([^\s/@:]+):([^\s/@]+)@",
538
+ r"\1[REDACTED]@",
539
+ str(text or ""),
540
+ flags=re.IGNORECASE,
541
+ )
542
+
543
+
544
+ def test_proxy(url: str = "", *, timeout: float = 15.0) -> dict:
545
+ candidate = normalize_proxy_url(_clean(url))
546
+ proxy_source = "input"
547
+ if not candidate:
548
+ profile = proxy_settings.get_profile(upstream=True)
549
+ candidate = profile.proxy_url
550
+ proxy_source = profile.proxy_source
551
+ result_base = {"proxy_source": proxy_source, "has_proxy": bool(candidate)}
552
+ if not candidate:
553
+ return {
554
+ "ok": False,
555
+ "status": 0,
556
+ "latency_ms": 0,
557
+ "error": "no active proxy configured",
558
+ **result_base,
559
+ }
560
+ if not _is_valid_proxy_url(candidate):
561
+ return {
562
+ "ok": False,
563
+ "status": 0,
564
+ "latency_ms": 0,
565
+ "error": "invalid proxy url",
566
+ **result_base,
567
+ }
568
+ session = Session(impersonate="edge101", verify=True, proxy=candidate)
569
+ started = time.perf_counter()
570
+ try:
571
+ response = session.get(
572
+ "https://chatgpt.com/api/auth/csrf",
573
+ headers={"user-agent": "Mozilla/5.0 (chatgpt2api proxy test)"},
574
+ timeout=timeout,
575
+ )
576
+ latency_ms = int((time.perf_counter() - started) * 1000)
577
+ return {
578
+ "ok": response.status_code < 500,
579
+ "status": int(response.status_code),
580
+ "latency_ms": latency_ms,
581
+ "error": None if response.status_code < 500 else f"HTTP {response.status_code}",
582
+ **result_base,
583
+ }
584
+ except Exception as exc:
585
+ latency_ms = int((time.perf_counter() - started) * 1000)
586
+ return {
587
+ "ok": False,
588
+ "status": 0,
589
+ "latency_ms": latency_ms,
590
+ "error": _redact_url_credentials(str(exc) or exc.__class__.__name__),
591
+ **result_base,
592
+ }
593
+ finally:
594
+ session.close()
595
+
596
+
597
+ def test_clearance(target_url: str = "https://chatgpt.com") -> dict:
598
+ target_url = str(target_url or "https://chatgpt.com").strip() or "https://chatgpt.com"
599
+ started = time.perf_counter()
600
+ status = proxy_settings.get_runtime_status()
601
+ if not status.get("clearance_enabled"):
602
+ return {
603
+ "ok": False,
604
+ "status": "disabled",
605
+ "latency_ms": 0,
606
+ "has_cookies": False,
607
+ "user_agent": "",
608
+ "error": "clearance is disabled",
609
+ "runtime": status,
610
+ }
611
+ try:
612
+ bundle = proxy_settings.refresh_clearance(target_url=target_url, force=True, upstream=True)
613
+ except Exception as exc:
614
+ latency_ms = int((time.perf_counter() - started) * 1000)
615
+ return {
616
+ "ok": False,
617
+ "status": "error",
618
+ "latency_ms": latency_ms,
619
+ "has_cookies": False,
620
+ "user_agent": "",
621
+ "error": _redact_url_credentials(str(exc) or exc.__class__.__name__),
622
+ "runtime": proxy_settings.get_runtime_status(),
623
+ }
624
+
625
+ latency_ms = int((time.perf_counter() - started) * 1000)
626
+ runtime = proxy_settings.get_runtime_status()
627
+ if bundle is None:
628
+ return {
629
+ "ok": False,
630
+ "status": "failed",
631
+ "latency_ms": latency_ms,
632
+ "has_cookies": False,
633
+ "user_agent": "",
634
+ "error": "clearance refresh returned no bundle",
635
+ "runtime": runtime,
636
+ }
637
+ return {
638
+ "ok": True,
639
+ "status": "ok",
640
+ "latency_ms": latency_ms,
641
+ "has_cookies": bool(bundle.cookies),
642
+ "user_agent": bundle.user_agent or "",
643
+ "error": None,
644
+ "runtime": runtime,
645
+ }
646
+
647
+
648
+ proxy_settings = ProxySettingsStore()