recovered from aaronjaworski710
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
# ChatGPT provider — copy env, do not commit secrets
|
||||
#
|
||||
# Egress switch (pick one backend):
|
||||
# core = project mihomo under .nodes/ (:17897) — no Clash Verge
|
||||
# clash = external Clash/mihomo (:7897)
|
||||
# list = only nodes.json / PROXY_LIST HTTP-SOCKS
|
||||
# direct = no proxy
|
||||
# auto = list → core → clash (default)
|
||||
# REGISTER_EGRESS=core
|
||||
# Persist: python -m register_core nodes egress set core
|
||||
|
||||
CHATGPT_EMAIL_SOURCE=gmail_imap
|
||||
CHATGPT_OTP_TIMEOUT=180
|
||||
|
||||
# Optional fixed URL (mainly with REGISTER_EGRESS=clash or direct override)
|
||||
# CHATGPT_PROXY=http://127.0.0.1:7897
|
||||
# CLASH_PROXY=http://127.0.0.1:7897
|
||||
|
||||
# HTTP/SOCKS pool (REGISTER_EGRESS=list|auto)
|
||||
# CHATGPT_PROXY_LIST=http://user:pass@1.2.3.4:8080,http://user:pass@5.6.7.8:8080
|
||||
# REGISTER_NODES_FILE=./nodes.json
|
||||
|
||||
# CHATGPT_PROXY_ROTATE_MODE=list
|
||||
# CHATGPT_PROXY_ROTATE_EVERY=1
|
||||
# CHATGPT_PROXY_ROTATE_REQUIRED=0
|
||||
@@ -0,0 +1,152 @@
|
||||
# ChatGPT / OpenAI platform provider
|
||||
|
||||
In-process protocol register for **new OpenAI platform accounts** (auth.openai.com
|
||||
PKCE + email OTP + oauth/token). Produces `refresh_token` / `access_token` for
|
||||
auth-file pools (CLIProxyAPI / codex-lb consumers), **not** a chat2api gateway.
|
||||
|
||||
## Stack
|
||||
|
||||
| Layer | Choice |
|
||||
|-------|--------|
|
||||
| Style | **In-process** (consumes `EmailSource`) |
|
||||
| HTTP | `curl_cffi` impersonate chrome (TLS fingerprint) |
|
||||
| Mail | `cloudflare` Worker default; override `gmail_imap` / `tinyhost` / `duckmail` |
|
||||
| Captcha | OpenAI Sentinel PoW (no browser Turnstile farm) |
|
||||
| CPA | **none** — never auto-inject production |
|
||||
|
||||
## Hub
|
||||
|
||||
```bash
|
||||
# pick egress: core=project mihomo, clash=external Clash, list, direct, auto
|
||||
python -m register_core nodes egress set core
|
||||
REGISTER_EGRESS=core ./register.sh chatgpt [count]
|
||||
# or per-run:
|
||||
./register.sh core run -p chatgpt -n 1 --egress clash --email-source cloudflare
|
||||
./register.sh chatgpt [count]
|
||||
# or layered:
|
||||
./register.sh core run -p chatgpt -n 1 --email-source cloudflare
|
||||
|
||||
# Project-owned nodes (no external VPN / Clash required):
|
||||
cp nodes.example.json nodes.json # edit real HTTP proxy URLs
|
||||
python -m register_core nodes check
|
||||
./providers/chatgpt/run-register.sh 1
|
||||
|
||||
# Or explicit pool:
|
||||
CHATGPT_PROXY_LIST='http://u:p@1.2.3.4:8080,http://u:p@5.6.7.8:8080' \
|
||||
./providers/chatgpt/run-register.sh 3
|
||||
# equivalent:
|
||||
./register.sh core run -p chatgpt -n 3 --email-source cloudflare \
|
||||
--proxy-list 'http://u:p@1.2.3.4:8080,http://u:p@5.6.7.8:8080'
|
||||
```
|
||||
|
||||
## Egress switch (core vs Clash)
|
||||
|
||||
| Backend | Meaning |
|
||||
|---------|---------|
|
||||
| `core` | project mihomo `.nodes` → `http://127.0.0.1:17897` |
|
||||
| `clash` | external Clash Verge/mihomo → `http://127.0.0.1:7897` |
|
||||
| `list` | only `nodes.json` / `PROXY_LIST` HTTP-SOCKS |
|
||||
| `direct` | no proxy |
|
||||
| `auto` | list → core → clash (default) |
|
||||
|
||||
```bash
|
||||
python -m register_core nodes egress show
|
||||
python -m register_core nodes egress set core # primary: list|core|direct
|
||||
REGISTER_EGRESS=core ./providers/chatgpt/run-register.sh 1
|
||||
```
|
||||
|
||||
```bash
|
||||
python -m register_core nodes import profile.yaml # merge HTTP/SOCKS + pack protocol
|
||||
python -m register_core nodes list|check|add 'http://u:p@host:port'
|
||||
python -m register_core nodes core start|select
|
||||
```
|
||||
|
||||
## Env
|
||||
|
||||
| Var | Default | Meaning |
|
||||
|-----|---------|---------|
|
||||
| `REGISTER_EGRESS` / `CHATGPT_EGRESS` | `auto` | Backend: `core`\|`clash`\|`list`\|`direct`\|`auto` |
|
||||
| `REGISTER_NODES_FILE` / `NODES_FILE` | `./nodes.json` | HTTP/SOCKS catalog |
|
||||
| `REGISTER_NODES` | `1` | Set `0` to ignore catalog |
|
||||
| `REGISTER_NODES_PREFLIGHT` | `1` | Probe catalog before register (list/auto) |
|
||||
| `REGISTER_NODES_MAX_FAIL` | `3` | Hard quarantine after consecutive proxy fails |
|
||||
| `REGISTER_NODES_SKIP_FAILED` | `1` | Skip quarantined nodes in rotation |
|
||||
| `REGISTER_NODES_COOLDOWN_RISK` | `600` | Soft cooldown (s) after `registration_disallowed` — **not** quarantine |
|
||||
| `REGISTER_NODES_COOLDOWN_NETWORK` | `120` | Soft cooldown (s) after network/proxy fail (still counts fail_count) |
|
||||
| `REGISTER_NODES_COOLDOWN_PER_USE` | `0` | Optional post-success cool; default **off** (small pools) |
|
||||
| `CLASH_PROXY` | `http://127.0.0.1:7897` | External Clash mixed port (`egress=clash`) |
|
||||
| `CHATGPT_PROXY` | empty | Fixed **register** egress URL override |
|
||||
| `CHATGPT_PROXY_LIST` / `PROXY_LIST` | empty | Self-controlled HTTP pool (skips catalog preflight) |
|
||||
| `CHATGPT_PROXY_ROTATE_MODE` / `PROXY_ROTATE_MODE` | auto | `off` \| `list` \| `nodes` \| `clash` |
|
||||
| `CHATGPT_PROXY_ROTATE_EVERY` | `1` | Rotate every N attempts |
|
||||
| `CHATGPT_MAIL_PROXY` / `EMAIL_PROXY` / `MAIL_PROXY` | empty | **Mail HTTP only** (tinyhost/Worker API). Default direct; never inherits register proxy |
|
||||
| `CHATGPT_EMAIL_SOURCE` | `cloudflare` | Pluggable: `cloudflare` \| `gmail_imap` \| `tinyhost` \| `duckmail` \| `auto` |
|
||||
| `CHATGPT_EMAIL_DOMAIN` | `publicvm.com` | Force tinyhost domain when source is tinyhost |
|
||||
| `CLOUDFLARE_API_BASE` | from `config.json` | Worker base (pxed: `https://temp-mail.mangoqwq.com`) |
|
||||
| `CLOUDFLARE_API_KEY` / `CLOUDFLARE_AUTH_MODE` | optional | Worker auth; mode `none`\|`bearer`\|`header` |
|
||||
| `CHATGPT_OTP_TIMEOUT` | `180` | OTP poll seconds (split across first + resend polls) |
|
||||
| `CHATGPT_SINK` | `providers/chatgpt/output/pipeline.jsonl` | private JSONL |
|
||||
| `CHATGPT_TIMEOUT` | `900` | pipeline timeout hint |
|
||||
|
||||
### Mail vs register egress
|
||||
|
||||
| Path | Proxy |
|
||||
|------|--------|
|
||||
| OpenAI register (`curl_cffi`) | `CHATGPT_PROXY` / `PROXY_LIST` / `nodes.json` / egress backend |
|
||||
| Email allocate/poll (HTTP Worker / tinyhost) | **direct** unless `CHATGPT_MAIL_PROXY` / `EMAIL_PROXY` / `MAIL_PROXY` |
|
||||
| Gmail IMAP (override) | local TLS to `imap.gmail.com` — not register pool |
|
||||
|
||||
Artifacts include redacted `register_proxy`, `mail_proxy`, and on `mail_miss` optional `otp_wait` (`OtpWaitDiagnostics`: poll_count, failure_class, …).
|
||||
|
||||
## Artifacts (gitignored)
|
||||
|
||||
```text
|
||||
providers/chatgpt/output/
|
||||
accounts.jsonl # append-only this-run records (0600)
|
||||
chatgpt-<email>-*.json # full token dump per success (0600)
|
||||
pipeline.jsonl # sink from hub
|
||||
```
|
||||
|
||||
Success attribution: `RegisterResult` returned from this process only — never
|
||||
read historical `accounts.jsonl` tail as this-run success.
|
||||
|
||||
## Secret shape
|
||||
|
||||
- `secret` = `refresh_token`
|
||||
- `secret_kind` = `refresh_token`
|
||||
- access/id tokens stored in artifacts / auth file, redacted in public dict
|
||||
|
||||
## Fail-fast / error taxonomy
|
||||
|
||||
- Missing email source / empty allocate → `FailFastError`
|
||||
- OTP timeout → `MailMissError` / `error_kind=mail_miss` (pipeline may stop under fail_fast). **Does not** cool or quarantine register nodes.
|
||||
- `create_account` risk → `error_kind=registration_disallowed` → soft cooldown (`REGISTER_NODES_COOLDOWN_RISK`) only
|
||||
- Network/proxy fail → fail_count + optional `REGISTER_NODES_COOLDOWN_NETWORK`; hard quarantine after `MAX_FAIL`
|
||||
- Sentinel soft-fail continues once; hard HTTP 4xx/5xx on register/OTP → fail attempt
|
||||
|
||||
`failure_class` (under `artifacts.otp_wait`, not a separate error_kind): `no_mail` | `parse_fail` | `stale_code` | `imap_error` | `aborted`.
|
||||
|
||||
## Manual-required
|
||||
|
||||
- **OTP inbox**: default `CHATGPT_EMAIL_SOURCE=cloudflare` against project Worker (`cloudflare_api_base` / `CLOUDFLARE_API_BASE`, e.g. `https://temp-mail.mangoqwq.com`). Override `gmail_imap` (catch-all `@mangoqwq.com`) or `tinyhost`/`duckmail` when needed. OpenAI OTP deliverability to Worker domains is asset-dependent; Gmail HTML parser still strips CSS poison when using IMAP.
|
||||
- **`create_account` → `registration_disallowed`**: protocol + OTP validated live; OpenAI risk engine still rejects final account create for some IP/domain/device combos. Needs cleaner residential egress and/or better-reputation mailbox domain — not fixed by payload shape alone. Code soft-cools the node; does not empty-retry spin.
|
||||
- Live OpenAI API usage probe (cost / policy) — verifier default is offline shape only
|
||||
- Phone challenge accounts (not handled; fail closed)
|
||||
- Live smoke on **pxed** (config.json already pins Worker base); Local Mac needs `cloudflare_api_base` or env overlay, not empty local config.
|
||||
- Live `ok=1` out号 is asset-dependent (OTP delivery + residential reputation). Code gate can ship with honest smoke diagnosis when assets block.
|
||||
|
||||
## Offline verify (code gate)
|
||||
|
||||
```bash
|
||||
.venv/bin/python -m unittest \
|
||||
test_otp_diagnostics test_chatgpt_error_kinds test_mail_proxy_separation \
|
||||
test_register_core_nodes test_register_core_proxy -v
|
||||
```
|
||||
|
||||
## Do not
|
||||
|
||||
- Hotmail plus-alias farm
|
||||
- Silent tebi/CPA production inject
|
||||
- Soft-inject / remint spin on entitlement or risk
|
||||
- Browser Selenium farms as primary path
|
||||
- Treat mail_miss as proxy death (no quarantine)
|
||||
@@ -0,0 +1 @@
|
||||
# ChatGPT product package (in-process protocol).
|
||||
@@ -0,0 +1,5 @@
|
||||
"""OpenAI / ChatGPT platform OAuth registration protocol (in-process)."""
|
||||
|
||||
from .flow import ChatGPTRegisterError, RegistrationResult, register_one
|
||||
|
||||
__all__ = ["ChatGPTRegisterError", "RegistrationResult", "register_one"]
|
||||
@@ -0,0 +1,73 @@
|
||||
"""OpenAI auth / platform OAuth constants (protocol register path)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
AUTH_BASE = "https://auth.openai.com"
|
||||
PLATFORM_BASE = "https://platform.openai.com"
|
||||
SENTINEL_BASE = "https://sentinel.openai.com"
|
||||
|
||||
# Platform OAuth client used by open-reg-auto / zhuce6-style protocol path.
|
||||
PLATFORM_OAUTH_CLIENT_ID = "app_2SKx67EdpoN0G6j64rFvigXD"
|
||||
PLATFORM_OAUTH_REDIRECT_URI = f"{PLATFORM_BASE}/auth/callback"
|
||||
PLATFORM_OAUTH_AUDIENCE = "https://api.openai.com/v1"
|
||||
|
||||
# curl_cffi 0.15 chrome* fingerprints from chrome119+ are Macintosh TLS profiles.
|
||||
# Headers MUST match the impersonate platform (Mac Chrome 145). Windows headers
|
||||
# with Mac JA3 previously produced a fingerprint mismatch risk signal.
|
||||
DEFAULT_IMPERSONATE = "chrome145"
|
||||
|
||||
USER_AGENT = (
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/145.0.0.0 Safari/537.36"
|
||||
)
|
||||
SEC_CH_UA = '"Google Chrome";v="145", "Not?A_Brand";v="8", "Chromium";v="145"'
|
||||
SEC_CH_UA_FULL = (
|
||||
'"Chromium";v="145.0.0.0", "Not:A-Brand";v="99.0.0.0", '
|
||||
'"Google Chrome";v="145.0.0.0"'
|
||||
)
|
||||
SEC_CH_UA_PLATFORM = '"macOS"'
|
||||
SEC_CH_UA_PLATFORM_VERSION = '"15.0.0"'
|
||||
SEC_CH_UA_ARCH = '"arm64"'
|
||||
|
||||
DEFAULT_TIMEOUT = 30
|
||||
SENTINEL_SDK = "https://sentinel.openai.com/sentinel/20260124ceb8/sdk.js"
|
||||
|
||||
COMMON_HEADERS: dict[str, str] = {
|
||||
"accept": "application/json",
|
||||
"accept-language": "en-US,en;q=0.9",
|
||||
"content-type": "application/json",
|
||||
"origin": AUTH_BASE,
|
||||
"priority": "u=1, i",
|
||||
"user-agent": USER_AGENT,
|
||||
"sec-ch-ua": SEC_CH_UA,
|
||||
"sec-ch-ua-arch": SEC_CH_UA_ARCH,
|
||||
"sec-ch-ua-bitness": '"64"',
|
||||
"sec-ch-ua-full-version-list": SEC_CH_UA_FULL,
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-model": '""',
|
||||
"sec-ch-ua-platform": SEC_CH_UA_PLATFORM,
|
||||
"sec-ch-ua-platform-version": SEC_CH_UA_PLATFORM_VERSION,
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-origin",
|
||||
}
|
||||
|
||||
NAVIGATE_HEADERS: dict[str, str] = {
|
||||
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
||||
"accept-language": "en-US,en;q=0.9",
|
||||
"user-agent": USER_AGENT,
|
||||
"sec-ch-ua": SEC_CH_UA,
|
||||
"sec-ch-ua-arch": SEC_CH_UA_ARCH,
|
||||
"sec-ch-ua-bitness": '"64"',
|
||||
"sec-ch-ua-full-version-list": SEC_CH_UA_FULL,
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-model": '""',
|
||||
"sec-ch-ua-platform": SEC_CH_UA_PLATFORM,
|
||||
"sec-ch-ua-platform-version": SEC_CH_UA_PLATFORM_VERSION,
|
||||
"sec-fetch-dest": "document",
|
||||
"sec-fetch-mode": "navigate",
|
||||
"sec-fetch-site": "same-origin",
|
||||
"sec-fetch-user": "?1",
|
||||
"upgrade-insecure-requests": "1",
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,148 @@
|
||||
"""OpenAI Sentinel proof-of-work token builder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from .constants import (
|
||||
SEC_CH_UA,
|
||||
SEC_CH_UA_PLATFORM,
|
||||
SENTINEL_BASE,
|
||||
SENTINEL_SDK,
|
||||
USER_AGENT,
|
||||
)
|
||||
|
||||
|
||||
class SentinelTokenGenerator:
|
||||
MAX_ATTEMPTS = 500_000
|
||||
ERROR_PREFIX = "wQ8Lk5FbGpA2NcR9dShT6gYjU7VxZ4D"
|
||||
|
||||
def __init__(self, device_id: str, ua: str = USER_AGENT) -> None:
|
||||
self.device_id = device_id
|
||||
self.user_agent = ua
|
||||
self.sid = str(uuid.uuid4())
|
||||
|
||||
@staticmethod
|
||||
def _fnv1a_32(text: str) -> str:
|
||||
h = 2166136261
|
||||
for ch in text:
|
||||
h ^= ord(ch)
|
||||
h = (h * 16777619) & 0xFFFFFFFF
|
||||
h ^= h >> 16
|
||||
h = (h * 2246822507) & 0xFFFFFFFF
|
||||
h ^= h >> 13
|
||||
h = (h * 3266489909) & 0xFFFFFFFF
|
||||
h ^= h >> 16
|
||||
return format(h & 0xFFFFFFFF, "08x")
|
||||
|
||||
def _get_config(self) -> list[Any]:
|
||||
perf_now = random.uniform(1000, 50000)
|
||||
return [
|
||||
"1920x1080",
|
||||
time.strftime(
|
||||
"%a %b %d %Y %H:%M:%S GMT+0000 (Coordinated Universal Time)",
|
||||
time.gmtime(),
|
||||
),
|
||||
4294705152,
|
||||
random.random(),
|
||||
self.user_agent,
|
||||
SENTINEL_SDK,
|
||||
None,
|
||||
None,
|
||||
"en-US",
|
||||
random.random(),
|
||||
random.choice(
|
||||
[
|
||||
"vendorSub-undefined",
|
||||
"plugins-undefined",
|
||||
"mimeTypes-undefined",
|
||||
"hardwareConcurrency-undefined",
|
||||
]
|
||||
),
|
||||
random.choice(
|
||||
["location", "implementation", "URL", "documentURI", "compatMode"]
|
||||
),
|
||||
random.choice(
|
||||
["Object", "Function", "Array", "Number", "parseFloat", "undefined"]
|
||||
),
|
||||
perf_now,
|
||||
self.sid,
|
||||
"",
|
||||
random.choice([4, 8, 12, 16]),
|
||||
time.time() * 1000 - perf_now,
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def _b64(data: Any) -> str:
|
||||
raw = json.dumps(data, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
return base64.b64encode(raw).decode("ascii")
|
||||
|
||||
def generate_requirements_token(self) -> str:
|
||||
data = self._get_config()
|
||||
data[3] = 1
|
||||
data[9] = round(random.uniform(5, 50))
|
||||
return "gAAAAAC" + self._b64(data)
|
||||
|
||||
def generate_token(self, seed: str, difficulty: str) -> str:
|
||||
start = time.time()
|
||||
data = self._get_config()
|
||||
difficulty = str(difficulty or "0")
|
||||
for i in range(self.MAX_ATTEMPTS):
|
||||
data[3] = i
|
||||
data[9] = round((time.time() - start) * 1000)
|
||||
payload = self._b64(data)
|
||||
if self._fnv1a_32(seed + payload)[: len(difficulty)] <= difficulty:
|
||||
return "gAAAAAB" + payload + "~S"
|
||||
return "gAAAAAB" + self.ERROR_PREFIX + self._b64(str(None))
|
||||
|
||||
|
||||
def build_sentinel_token(session: Any, device_id: str, flow: str) -> str:
|
||||
"""POST sentinel/req and return JSON string for openai-sentinel-token header."""
|
||||
generator = SentinelTokenGenerator(device_id, USER_AGENT)
|
||||
resp = session.post(
|
||||
f"{SENTINEL_BASE}/backend-api/sentinel/req",
|
||||
data=json.dumps(
|
||||
{
|
||||
"p": generator.generate_requirements_token(),
|
||||
"id": device_id,
|
||||
"flow": flow,
|
||||
}
|
||||
),
|
||||
headers={
|
||||
"Content-Type": "text/plain;charset=UTF-8",
|
||||
"Referer": f"{SENTINEL_BASE}/backend-api/sentinel/frame.html",
|
||||
"Origin": SENTINEL_BASE,
|
||||
"User-Agent": USER_AGENT,
|
||||
"sec-ch-ua": SEC_CH_UA,
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": SEC_CH_UA_PLATFORM,
|
||||
},
|
||||
timeout=20,
|
||||
)
|
||||
try:
|
||||
data = resp.json() if hasattr(resp, "json") else {}
|
||||
except Exception:
|
||||
data = {}
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
token = str(data.get("token") or "").strip()
|
||||
status = int(getattr(resp, "status_code", 0) or 0)
|
||||
if status != 200 or not token:
|
||||
raise RuntimeError(f"sentinel_req_failed_{status}")
|
||||
pow_data = data.get("proofofwork") or {}
|
||||
if isinstance(pow_data, dict) and pow_data.get("required") and pow_data.get("seed"):
|
||||
p_value = generator.generate_token(
|
||||
str(pow_data.get("seed") or ""),
|
||||
str(pow_data.get("difficulty") or "0"),
|
||||
)
|
||||
else:
|
||||
p_value = generator.generate_requirements_token()
|
||||
return json.dumps(
|
||||
{"p": p_value, "t": "", "c": token, "id": device_id, "flow": flow},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
@@ -0,0 +1,101 @@
|
||||
"""HTTP session helpers for ChatGPT protocol register."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
|
||||
from .constants import DEFAULT_IMPERSONATE, DEFAULT_TIMEOUT
|
||||
|
||||
|
||||
def create_session(
|
||||
proxy: str = "",
|
||||
*,
|
||||
impersonate: str = DEFAULT_IMPERSONATE,
|
||||
) -> Any:
|
||||
"""Prefer curl_cffi (TLS fingerprint); fall back to requests.
|
||||
|
||||
Default impersonate is aligned with constants.USER_AGENT / sec-ch-ua
|
||||
(Mac Chrome 145). Passing a mismatched platform is a risk-engine signal.
|
||||
"""
|
||||
proxy = (proxy or "").strip()
|
||||
try:
|
||||
from curl_cffi import requests as curl_requests
|
||||
|
||||
kwargs: dict[str, Any] = {"impersonate": impersonate, "verify": False}
|
||||
if proxy:
|
||||
kwargs["proxy"] = proxy
|
||||
return curl_requests.Session(**kwargs)
|
||||
except Exception:
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
|
||||
session = requests.Session()
|
||||
retry = Retry(
|
||||
total=2,
|
||||
connect=2,
|
||||
read=2,
|
||||
backoff_factor=0.5,
|
||||
status_forcelist=(429, 500, 502, 503, 504),
|
||||
)
|
||||
adapter = HTTPAdapter(max_retries=retry, pool_connections=20, pool_maxsize=20)
|
||||
session.mount("http://", adapter)
|
||||
session.mount("https://", adapter)
|
||||
session.verify = False
|
||||
if proxy:
|
||||
session.proxies.update({"http": proxy, "https": proxy})
|
||||
return session
|
||||
|
||||
|
||||
def request_with_retry(
|
||||
session: Any,
|
||||
method: str,
|
||||
url: str,
|
||||
*,
|
||||
retry_attempts: int = 3,
|
||||
timeout: float = DEFAULT_TIMEOUT,
|
||||
**kwargs: Any,
|
||||
) -> tuple[Any | None, str]:
|
||||
last_error = ""
|
||||
for _ in range(max(1, retry_attempts)):
|
||||
try:
|
||||
return session.request(method.upper(), url, timeout=timeout, **kwargs), ""
|
||||
except Exception as exc:
|
||||
last_error = str(exc)
|
||||
time.sleep(1)
|
||||
return None, last_error
|
||||
|
||||
|
||||
def quote_param(value: str) -> str:
|
||||
return quote(str(value), safe="")
|
||||
|
||||
|
||||
def response_json(resp: Any) -> dict:
|
||||
if resp is None:
|
||||
return {}
|
||||
try:
|
||||
data = resp.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def cookie_get(session: Any, name: str) -> str:
|
||||
jar = getattr(session, "cookies", None)
|
||||
if jar is None:
|
||||
return ""
|
||||
try:
|
||||
val = jar.get(name)
|
||||
if val:
|
||||
return str(val)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
for cookie in jar:
|
||||
if getattr(cookie, "name", "") == name:
|
||||
return str(getattr(cookie, "value", "") or "")
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env bash
|
||||
# ChatGPT / OpenAI platform register runner (in-process via register_core).
|
||||
# Usage:
|
||||
# ./providers/chatgpt/run-register.sh [count]
|
||||
#
|
||||
# Egress switch (pick one):
|
||||
# REGISTER_EGRESS=core # project mihomo .nodes :17897 (no Clash Verge)
|
||||
# REGISTER_EGRESS=clash # external Clash/mihomo :7897
|
||||
# REGISTER_EGRESS=list # only nodes.json / PROXY_LIST
|
||||
# REGISTER_EGRESS=direct # no proxy
|
||||
# REGISTER_EGRESS=auto # list → core → clash (default)
|
||||
#
|
||||
# Persist: python -m register_core nodes egress set core|clash|list|direct|auto
|
||||
set -euo pipefail
|
||||
|
||||
COUNT="${COUNT:-${1:-1}}"
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
if [[ -x "$ROOT/.venv/bin/python" ]]; then
|
||||
PY="$ROOT/.venv/bin/python"
|
||||
else
|
||||
PY="${PYTHON:-python3}"
|
||||
fi
|
||||
|
||||
export REGISTER_EGRESS="${REGISTER_EGRESS:-${EGRESS_BACKEND:-${CHATGPT_EGRESS:-}}}"
|
||||
export CHATGPT_PROXY="${CHATGPT_PROXY:-${MIMO_PROXY:-}}"
|
||||
# Default: project Cloudflare Worker temp-mail (config.json cloudflare_api_base).
|
||||
# Override with gmail_imap / tinyhost / duckmail when needed.
|
||||
export CHATGPT_EMAIL_SOURCE="${CHATGPT_EMAIL_SOURCE:-cloudflare}"
|
||||
# Optional force for tinyhost/auto only (adapter reads env). Prefer huychau.online over publicvm.
|
||||
# Examples: CHATGPT_EMAIL_DOMAIN=huychau.online or EMAIL_DOMAIN=huychau.online
|
||||
export CHATGPT_EMAIL_DOMAIN="${CHATGPT_EMAIL_DOMAIN:-${EMAIL_DOMAIN:-}}"
|
||||
export CHATGPT_PROXY_LIST="${CHATGPT_PROXY_LIST:-${PROXY_LIST:-}}"
|
||||
export CHATGPT_PROXY_ROTATE_MODE="${CHATGPT_PROXY_ROTATE_MODE:-${PROXY_ROTATE_MODE:-}}"
|
||||
export CHATGPT_PROXY_ROTATE_EVERY="${CHATGPT_PROXY_ROTATE_EVERY:-${PROXY_ROTATE_EVERY:-1}}"
|
||||
export REGISTER_NODES_FILE="${REGISTER_NODES_FILE:-${NODES_FILE:-$ROOT/nodes.json}}"
|
||||
export CLASH_PROXY="${CLASH_PROXY:-http://127.0.0.1:7897}"
|
||||
|
||||
SINK="${CHATGPT_SINK:-$ROOT/providers/chatgpt/output/pipeline.jsonl}"
|
||||
mkdir -p "$(dirname "$SINK")"
|
||||
|
||||
echo "[chatgpt] COUNT=$COUNT egress=${REGISTER_EGRESS:-auto} proxy=${CHATGPT_PROXY:-'(from egress)'} proxy_list=${CHATGPT_PROXY_LIST:-'(nodes/core)'} rotate=${CHATGPT_PROXY_ROTATE_MODE:-auto} email_source=$CHATGPT_EMAIL_SOURCE email_domain=${CHATGPT_EMAIL_DOMAIN:-'(source default)'}" >&2
|
||||
|
||||
ARGS=(
|
||||
-m register_core run
|
||||
-p chatgpt
|
||||
-n "$COUNT"
|
||||
--email-source "${CHATGPT_EMAIL_SOURCE}"
|
||||
--sink "$SINK"
|
||||
--timeout "${CHATGPT_TIMEOUT:-900}"
|
||||
)
|
||||
if [[ -n "${REGISTER_EGRESS}" ]]; then
|
||||
ARGS+=(--egress "${REGISTER_EGRESS}")
|
||||
fi
|
||||
if [[ -n "${CHATGPT_PROXY}" ]]; then
|
||||
ARGS+=(--proxy "${CHATGPT_PROXY}")
|
||||
fi
|
||||
if [[ -n "${CHATGPT_PROXY_LIST}" ]]; then
|
||||
ARGS+=(--proxy-list "${CHATGPT_PROXY_LIST}")
|
||||
fi
|
||||
if [[ -n "${CHATGPT_PROXY_ROTATE_MODE}" ]]; then
|
||||
ARGS+=(--proxy-rotate "${CHATGPT_PROXY_ROTATE_MODE}")
|
||||
fi
|
||||
if [[ -n "${CHATGPT_PROXY_ROTATE_EVERY}" ]]; then
|
||||
ARGS+=(--proxy-rotate-every "${CHATGPT_PROXY_ROTATE_EVERY}")
|
||||
fi
|
||||
|
||||
exec "$PY" "${ARGS[@]}"
|
||||
Reference in New Issue
Block a user