recovered from aaronjaworski710
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
# Providers
|
||||
|
||||
Product packages. Each provider owns its browser stack and (for black-box runners) its mailbox.
|
||||
|
||||
| Provider | Path | Stack | Hub | Status |
|
||||
|----------|------|-------|-----|--------|
|
||||
| **Grok / xAI** | root `register_cli.py` + `cpa_xai/` · notes in `providers/grok/` | Python + Drission | `./register.sh grok` | production |
|
||||
| **MiMo** | `providers/mimo/` | Node + Playwright | `./register.sh mimo` | production |
|
||||
| **ChatGPT / OpenAI** | `providers/chatgpt/` | Python + curl_cffi + EmailSource | `./register.sh chatgpt` | production protocol |
|
||||
| **typesafe.ai / jev** | `providers/typesafe/` | Python + requests + EmailSource | `./register.sh typesafe` | in-process protocol |
|
||||
| **_template** | `providers/_template/` | your choice | — | copy-me |
|
||||
|
||||
Layered orchestration (not a replacement for the above):
|
||||
|
||||
```bash
|
||||
./register.sh core list
|
||||
./register.sh core run -p mimo -n 1
|
||||
./register.sh core run -p grok -n 1 --no-verify
|
||||
./register.sh core run -p chatgpt -n 1 --email-source tinyhost
|
||||
./register.sh core run -p typesafe -n 1 --email-source tinyhost
|
||||
```
|
||||
|
||||
See [docs/ADDING_PROVIDER.md](../docs/ADDING_PROVIDER.md) and [ARCHITECTURE.md](../ARCHITECTURE.md).
|
||||
@@ -0,0 +1,4 @@
|
||||
# Copy to .env locally — never commit real values.
|
||||
# PROXY=http://127.0.0.1:7897
|
||||
# HEADLESS=true
|
||||
# COUNT=1
|
||||
@@ -0,0 +1,33 @@
|
||||
# Provider template: `{{name}}`
|
||||
|
||||
Copy this directory:
|
||||
|
||||
```bash
|
||||
cp -R providers/_template providers/myproduct
|
||||
```
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] `name` / aliases in `register_core/providers/registry.py`
|
||||
- [ ] Adapter `register_one` with **this-run** success attribution
|
||||
- [ ] Black-box? Add to `Pipeline._BLACKBOX_PROVIDERS`
|
||||
- [ ] `run-register.sh` or Python entry; hub case in `register.sh`
|
||||
- [ ] `.env.example` (no secrets)
|
||||
- [ ] Offline tests for attribution + redact
|
||||
- [ ] Row in `providers/README.md`
|
||||
|
||||
## Suggested layout
|
||||
|
||||
```text
|
||||
providers/myproduct/
|
||||
README.md
|
||||
.env.example
|
||||
run-register.sh # COUNT=1 production runner
|
||||
scripts/ # product-specific
|
||||
output/ # gitignored
|
||||
```
|
||||
|
||||
## Contract
|
||||
|
||||
Return `RegisterResult(ok=..., provider=..., email=..., secret=..., secret_kind=...)`.
|
||||
Never treat historical `output/*` tails as this-run success.
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Template product runner — replace with real signup.
|
||||
# Contract for register_core black-box adapters:
|
||||
# - Prefer printing one line: RESULT_JSON:{"ok":true,"email":"...","secret":"..."}
|
||||
# - Or append-only files with caller-owned offsets
|
||||
# - Exit non-zero on failure; do not exit 0 with empty identity
|
||||
set -euo pipefail
|
||||
|
||||
COUNT="${COUNT:-${1:-1}}"
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
OUT_DIR="$(cd "$(dirname "$0")" && pwd)/output"
|
||||
mkdir -p "$OUT_DIR"
|
||||
|
||||
echo "[template] COUNT=$COUNT ROOT=$ROOT" >&2
|
||||
echo "[template] Replace this runner. Failing closed." >&2
|
||||
exit 2
|
||||
@@ -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[@]}"
|
||||
@@ -0,0 +1,34 @@
|
||||
# Grok / xAI provider
|
||||
|
||||
## Runtime authority (current)
|
||||
|
||||
Grok production still lives at **repo root** for stable imports and pxed paths:
|
||||
|
||||
| Entry | Path |
|
||||
|-------|------|
|
||||
| Hub | `./register.sh grok [count] [threads]` |
|
||||
| CLI | `register_cli.py` |
|
||||
| GUI | `grok_register_ttk.py` |
|
||||
| OIDC / chat | `cpa_xai/` |
|
||||
| Adapter | `register_core/providers/grok_adapter.py` (black-box → CLI) |
|
||||
|
||||
Do **not** move these modules into this directory without a dedicated migrate milestone (breaks pxed `/personal/grok-register` scripts and import paths).
|
||||
|
||||
## Target package shape (future)
|
||||
|
||||
```text
|
||||
providers/grok/
|
||||
README.md
|
||||
run-register.sh # thin wrapper → root or package CLI
|
||||
py/ # optional package extract of register core
|
||||
assets/turnstilePatch/
|
||||
```
|
||||
|
||||
## Success gate
|
||||
|
||||
Register → SSO ledger → CPA OIDC mint → free Build **chat probe**.
|
||||
`entitlement_denied` is not remint-worthy; models-only 200 is not product success.
|
||||
|
||||
## Config
|
||||
|
||||
Use root `config.example.json` / `config.simple.example.json`. Secrets never committed.
|
||||
@@ -0,0 +1,7 @@
|
||||
# MiMo provider env (optional; register-one.js uses process env)
|
||||
MIMO_PROXY=http://127.0.0.1:7897
|
||||
XIAOMI_REGION=Singapore
|
||||
HEADLESS=true
|
||||
OTP_RETRIES=35
|
||||
# MIMO_INVITE_CODE=
|
||||
# TEMP_MAIL_BASE=https://tinyhost.shop
|
||||
@@ -0,0 +1,30 @@
|
||||
# MiMo @ pxed(ai-register-machine monorepo)
|
||||
|
||||
**源码权威**:部署目录下 `providers/mimo`(常见 `/personal/grok-register` 或 `ai-register-machine`)
|
||||
**Node runtime**:`/personal/mimo-register`(`npm ci` + playwright + 上游 `dist/`)
|
||||
|
||||
上游参考:[Rossevelt1313/MimoAuto](https://github.com/Rossevelt1313/MimoAuto)
|
||||
生产 runner:`scripts/register-one.js`(Geetest + 双 OTP + Create Key;**不要**只靠上游 worker)
|
||||
|
||||
## 一键(推荐)
|
||||
|
||||
```bash
|
||||
# monorepo hub
|
||||
bash /personal/grok-register/register.sh smoke mimo
|
||||
bash /personal/grok-register/register.sh mimo
|
||||
```
|
||||
|
||||
## 依赖
|
||||
|
||||
- clash:`bash /personal/grok-register/start-clash-for-grok.sh`(7897)
|
||||
- Xvfb `:99`
|
||||
- 禁止 `ga.dp.tech:8118`;git 用 `git -c http.proxy=http://127.0.0.1:7897`
|
||||
|
||||
## 产物
|
||||
|
||||
- `/personal/mimo-register/output/success_keys.txt`
|
||||
- `accounts.jsonl` / 失败截图
|
||||
|
||||
## 仅 TTS
|
||||
|
||||
Key 后调 `mimo-v2.5-tts`,无需 Pro。
|
||||
@@ -0,0 +1,124 @@
|
||||
# MiMo provider(ai-register-machine)
|
||||
|
||||
Xiaomi MiMo API Key 注册机,位于 monorepo 的 `providers/mimo`。
|
||||
|
||||
目标:**只要 TTS Key**(`mimo-v2.5-tts` 等),不跑 Pro 农场。
|
||||
|
||||
## 与 Grok 的关系
|
||||
|
||||
| | Grok | MiMo |
|
||||
|---|---|---|
|
||||
| 入口 | `./register.sh grok` | `./register.sh mimo` |
|
||||
| 运行时 | Python + DrissionPage | Node + Playwright |
|
||||
| 出口 | 共享 clash/mihomo `127.0.0.1:7897` | 同左 |
|
||||
| 邮箱 | Gmail / 独立临邮(禁 Hotmail alias) | tinyhost(sanitize 域名) |
|
||||
| 产物 | `cpa_auths/`、accounts(Grok/CPA 专用) | `output/success_keys.txt`、`accounts.jsonl`;CPA 走 **openai-compatibility / xiaomimimo**(不是 xai auth-dir) |
|
||||
| 验证码 | Turnstile 等 | **Geetest 滑块**(fullbg−bg 差分) |
|
||||
|
||||
**不做**语言层硬合并(两套浏览器栈)。共享的是:调度入口、代理/Xvfb 运维、fail-fast、pxed 布局约定。
|
||||
|
||||
## 生产路径
|
||||
|
||||
```bash
|
||||
# 在 monorepo 根
|
||||
./register.sh smoke mimo
|
||||
./register.sh mimo # 注册 1 个号
|
||||
COUNT=1 ./register.sh mimo
|
||||
```
|
||||
|
||||
底层 runner:`scripts/register-one.js`(已 E2E 验证):
|
||||
|
||||
1. Singapore 邮箱表单
|
||||
2. Geetest slide
|
||||
3. 注册 OTP(tinyhost)
|
||||
4. Account Authentication 二次 OTP
|
||||
5. platform console 协议勾选
|
||||
6. Create API Key → clipboard / DOM
|
||||
|
||||
上游 [MimoAuto](https://github.com/Rossevelt1313/MimoAuto) 的 `worker` **不解 Geetest**;pxed 请以 `register-one.js` 为准。
|
||||
|
||||
## pxed 部署
|
||||
|
||||
```text
|
||||
/personal/grok-register # 本 monorepo(含 providers/mimo 源码)
|
||||
/personal/mimo-register # Node runtime:npm ci + playwright chromium + dist/
|
||||
/personal/clash # mihomo
|
||||
```
|
||||
|
||||
同步脚本(源码权威在 monorepo):
|
||||
|
||||
```bash
|
||||
# 在 pxed
|
||||
cp -f /personal/grok-register/providers/mimo/scripts/register-one.js \
|
||||
/personal/mimo-register/scripts/register-one.js
|
||||
bash /personal/grok-register/register.sh mimo
|
||||
# 或
|
||||
MIMO_RUNTIME=/personal/mimo-register bash /personal/grok-register/providers/mimo/run-register.sh
|
||||
```
|
||||
|
||||
首次装 runtime(若尚未有 `/personal/mimo-register`):
|
||||
|
||||
```bash
|
||||
# clash 先起
|
||||
bash /personal/grok-register/start-clash-for-grok.sh
|
||||
git -c http.proxy=http://127.0.0.1:7897 clone https://github.com/Rossevelt1313/MimoAuto /personal/mimo-register
|
||||
cd /personal/mimo-register && npm ci
|
||||
# 拷贝 monorepo 生产 runner
|
||||
mkdir -p scripts
|
||||
cp /personal/grok-register/providers/mimo/scripts/*.js scripts/
|
||||
npx playwright install chromium
|
||||
```
|
||||
|
||||
## 环境变量
|
||||
|
||||
见 `.env.example`。常用:
|
||||
|
||||
- `MIMO_PROXY=http://127.0.0.1:7897`
|
||||
- `XIAOMI_REGION=Singapore`
|
||||
- `OTP_RETRIES=35`
|
||||
- `MIMO_INVITE_CODE=`(可选)
|
||||
- `HEADLESS=true`
|
||||
|
||||
## 产物
|
||||
|
||||
- `output/success_keys.txt`
|
||||
- `output/accounts.jsonl`(email / password / apiKey)
|
||||
- 失败截图:`output/failed-final.png`、`geetest-*.png`、`after-otp-round-*.png`
|
||||
|
||||
## 注入 CPA OpenAI provider
|
||||
|
||||
MiMo 是 **OpenAI-compatible API key**,写入 tebi `config.yaml` 的 `openai-compatibility` 渠道 **`xiaomimimo`**(`base-url: https://api.xiaomimimo.com/v1`),**不是** `auth-dir` 里的 `type: xai` JSON。
|
||||
|
||||
```bash
|
||||
# 必须显式 --config(或 CPA_CONFIG)。默认不再指向生产。
|
||||
# 本机 → tebi(BatchMode ssh 别名);生产路径需额外确认开关
|
||||
python3 providers/mimo/inject_cpa_openai.py \
|
||||
--ssh tebi-tunnel \
|
||||
--config /personal/cpa/config.yaml \
|
||||
--i-understand-production \
|
||||
--from-jsonl /path/to/accounts.jsonl
|
||||
|
||||
# 先 dry-run
|
||||
python3 providers/mimo/inject_cpa_openai.py \
|
||||
--config /tmp/cpa-config.yaml --dry-run --from-file keys.txt
|
||||
|
||||
# 或在 tebi 上本地
|
||||
python3 inject_cpa_openai.py \
|
||||
--config /personal/cpa/config.yaml \
|
||||
--i-understand-production \
|
||||
--from-file /personal/mimo-register/output/success_keys.txt
|
||||
```
|
||||
|
||||
- 幂等追加 `api-key-entries`;写前 `config.yaml.bak-mimo-<ts>`
|
||||
- **不 SIGHUP**(CLIProxyAPI fsnotify 热加载)
|
||||
- 默认模型:`mimo-v2.5-tts` / voiceclone / voicedesign
|
||||
- **拒绝**隐式生产路径:无 `--config`/`CPA_CONFIG` 直接 exit 2;生产 path 需 `--i-understand-production`(或 `--dry-run`)
|
||||
- 单测:`python3 test_mimo_cpa_openai_inject.py`
|
||||
|
||||
## 已知坑
|
||||
|
||||
- 容器坏代理 `ga.dp.tech:8118`:启动前 `unset` 代理,只用 clash
|
||||
- tinyhost 域名尾部 `.` / infinityfree → Next 禁用(runner 已 sanitize)
|
||||
- 回调 URL 查询串含 `platform.xiaomimimo.com` → 必须用 **hostname** 判断是否已上平台
|
||||
- 控制台中文弹窗:创建 Key 前必须勾协议 checkbox
|
||||
- 禁止空转批量;一次失败 fail-fast
|
||||
@@ -0,0 +1,472 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inject MiMo API keys into CPA openai-compatibility (OpenAI provider path).
|
||||
|
||||
MiMo keys are NOT xai auth-dir JSON. They go under config.yaml:
|
||||
|
||||
openai-compatibility:
|
||||
- name: xiaomimimo
|
||||
base-url: https://api.xiaomimimo.com/v1
|
||||
api-key-entries:
|
||||
- api-key: sk-...
|
||||
models:
|
||||
- name: mimo-v2.5-tts
|
||||
...
|
||||
|
||||
Idempotent: existing keys are left alone. Backs up config before write.
|
||||
Does not SIGHUP CPA (CLIProxyAPI watches config via fsnotify).
|
||||
|
||||
Usage:
|
||||
python inject_cpa_openai.py --config /path/to/config.yaml --key sk-...
|
||||
python inject_cpa_openai.py --config /path/to/config.yaml --from-file success_keys.txt
|
||||
python inject_cpa_openai.py --config /path/to/config.yaml --from-jsonl accounts.jsonl
|
||||
# production (explicit ack required):
|
||||
python inject_cpa_openai.py --config /personal/cpa/config.yaml --i-understand-production --from-jsonl ...
|
||||
# remote via ssh host (BatchMode):
|
||||
python inject_cpa_openai.py --ssh tebi-tunnel --config /personal/cpa/config.yaml \\
|
||||
--i-understand-production --from-jsonl ...
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_CHANNEL = "xiaomimimo"
|
||||
DEFAULT_BASE_URL = "https://api.xiaomimimo.com/v1"
|
||||
DEFAULT_MODELS = (
|
||||
"mimo-v2.5-tts",
|
||||
"mimo-v2.5-tts-voiceclone",
|
||||
"mimo-v2.5-tts-voicedesign",
|
||||
)
|
||||
# Production path is NOT the default — require --config or CPA_CONFIG explicitly.
|
||||
PROD_CONFIG_HINT = "/personal/cpa/config.yaml"
|
||||
# Allow hyphenated vendor keys (sk-hyper-..., sk-existing-...) while keeping sk- prefix.
|
||||
# Keep in sync with register_core.util.secrets (standalone script may run without package).
|
||||
_KEY_RE = re.compile(r"(sk-[A-Za-z0-9][A-Za-z0-9_-]{15,})")
|
||||
|
||||
|
||||
def _redact(key: str) -> str:
|
||||
k = key.strip()
|
||||
if len(k) <= 14:
|
||||
return "***"
|
||||
return f"{k[:10]}...{k[-4:]}"
|
||||
|
||||
|
||||
def extract_keys_from_text(text: str) -> list[str]:
|
||||
found: list[str] = []
|
||||
for m in _KEY_RE.finditer(text or ""):
|
||||
k = m.group(1)
|
||||
if k not in found:
|
||||
found.append(k)
|
||||
return found
|
||||
|
||||
|
||||
def extract_keys_from_jsonl(path: Path) -> list[str]:
|
||||
found: list[str] = []
|
||||
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
found.extend(extract_keys_from_text(line))
|
||||
continue
|
||||
for field in ("apiKey", "api_key", "key", "secret"):
|
||||
v = obj.get(field)
|
||||
if isinstance(v, str) and v.startswith("sk-") and v not in found:
|
||||
found.append(v.strip())
|
||||
return found
|
||||
|
||||
|
||||
def _channel_block_span(text: str, channel: str) -> tuple[int, int] | None:
|
||||
"""Return [start, end) of the openai-compatibility list item for channel."""
|
||||
m = re.search(r"(?m)^openai-compatibility:\s*$", text)
|
||||
if not m:
|
||||
return None
|
||||
start_block = m.end()
|
||||
next_top = re.search(r"(?m)^[A-Za-z0-9_-]+:\s*(?:#.*)?$", text[start_block:])
|
||||
end_block = start_block + (next_top.start() if next_top else len(text) - start_block)
|
||||
block = text[start_block:end_block]
|
||||
|
||||
# list items at indent 2: " - name:"
|
||||
item_starts = [m.start() for m in re.finditer(r"(?m)^ - name:\s*", block)]
|
||||
if not item_starts:
|
||||
return None
|
||||
for i, rel in enumerate(item_starts):
|
||||
abs_start = start_block + rel
|
||||
abs_end = start_block + (item_starts[i + 1] if i + 1 < len(item_starts) else len(block))
|
||||
head = text[abs_start : abs_start + 120]
|
||||
hm = re.match(r" - name:\s*[\"']?([^\"'\n#]+?)[\"']?\s*(?:#.*)?$", head.splitlines()[0])
|
||||
if not hm:
|
||||
continue
|
||||
name = hm.group(1).strip()
|
||||
if name == channel:
|
||||
return abs_start, abs_end
|
||||
return None
|
||||
|
||||
|
||||
def list_keys_in_entry(entry: str) -> list[str]:
|
||||
return extract_keys_from_text(entry)
|
||||
|
||||
|
||||
def ensure_channel_entry(
|
||||
text: str,
|
||||
*,
|
||||
channel: str,
|
||||
base_url: str,
|
||||
models: tuple[str, ...] | list[str],
|
||||
priority: int = 100,
|
||||
) -> tuple[str, bool]:
|
||||
"""Ensure xiaomimimo-style entry exists. Returns (new_text, created)."""
|
||||
span = _channel_block_span(text, channel)
|
||||
if span is not None:
|
||||
return text, False
|
||||
|
||||
models_yaml = "\n".join(
|
||||
f' - name: {m}\n alias: ""' for m in models
|
||||
)
|
||||
entry = (
|
||||
f" - name: {channel}\n"
|
||||
f" priority: {priority}\n"
|
||||
f" base-url: {base_url}\n"
|
||||
f" api-key-entries:\n"
|
||||
f" # injected by inject_cpa_openai.py\n"
|
||||
f"{models_yaml}\n"
|
||||
)
|
||||
# Prefer insert just after openai-compatibility:
|
||||
m = re.search(r"(?m)^openai-compatibility:\s*\n", text)
|
||||
if not m:
|
||||
raise SystemExit("config missing openai-compatibility: block")
|
||||
insert_at = m.end()
|
||||
return text[:insert_at] + entry + text[insert_at:], True
|
||||
|
||||
|
||||
def append_keys_to_entry(entry: str, keys: list[str]) -> tuple[str, list[str]]:
|
||||
"""Append missing api-key lines under api-key-entries. Returns (entry, added)."""
|
||||
existing = set(list_keys_in_entry(entry))
|
||||
to_add = [k for k in keys if k not in existing]
|
||||
if not to_add:
|
||||
return entry, []
|
||||
|
||||
lines = entry.splitlines(keepends=True)
|
||||
# Find api-key-entries: line
|
||||
ake_idx = None
|
||||
for i, line in enumerate(lines):
|
||||
if re.match(r"^ api-key-entries:\s*(?:#.*)?$", line):
|
||||
ake_idx = i
|
||||
break
|
||||
if ake_idx is None:
|
||||
# insert before models: or at end of entry (before trailing blank)
|
||||
models_idx = None
|
||||
for i, line in enumerate(lines):
|
||||
if re.match(r"^ models:\s*(?:#.*)?$", line):
|
||||
models_idx = i
|
||||
break
|
||||
insert_at = models_idx if models_idx is not None else len(lines)
|
||||
block = [" api-key-entries:\n"] + [f" - api-key: {k}\n" for k in to_add]
|
||||
lines[insert_at:insert_at] = block
|
||||
return "".join(lines), to_add
|
||||
|
||||
# Find last api-key under this section (indent 6: " - api-key")
|
||||
last = ake_idx
|
||||
for j in range(ake_idx + 1, len(lines)):
|
||||
line = lines[j]
|
||||
if re.match(r"^ - ", line) or re.match(r"^ ", line) or re.match(r"^\s*#", line) or line.strip() == "":
|
||||
# still in list / comments / blank inside section
|
||||
if re.match(r"^ - api-key:", line) or re.match(r"^ - ", line) or line.strip().startswith("#") or line.strip() == "":
|
||||
last = j
|
||||
continue
|
||||
# deeper nested under entry item
|
||||
if re.match(r"^ ", line):
|
||||
last = j
|
||||
continue
|
||||
# next sibling field at indent 4 (models/priority/base-url)
|
||||
if re.match(r"^ [a-zA-Z0-9_-]+:", line):
|
||||
break
|
||||
# next list item at indent 2
|
||||
if re.match(r"^ - ", line):
|
||||
break
|
||||
last = j
|
||||
|
||||
insert_lines = [f" - api-key: {k}\n" for k in to_add]
|
||||
lines[last + 1 : last + 1] = insert_lines
|
||||
return "".join(lines), to_add
|
||||
|
||||
|
||||
def inject_local(
|
||||
config_path: Path,
|
||||
keys: list[str],
|
||||
*,
|
||||
channel: str = DEFAULT_CHANNEL,
|
||||
base_url: str = DEFAULT_BASE_URL,
|
||||
models: tuple[str, ...] = DEFAULT_MODELS,
|
||||
priority: int = 100,
|
||||
dry_run: bool = False,
|
||||
) -> dict:
|
||||
if not keys:
|
||||
raise SystemExit("no keys to inject")
|
||||
if not config_path.is_file():
|
||||
raise SystemExit(f"config not found: {config_path}")
|
||||
|
||||
original = config_path.read_text(encoding="utf-8")
|
||||
text, created = ensure_channel_entry(
|
||||
original, channel=channel, base_url=base_url, models=models, priority=priority
|
||||
)
|
||||
span = _channel_block_span(text, channel)
|
||||
if span is None:
|
||||
raise SystemExit(f"channel {channel!r} still missing after ensure")
|
||||
start, end = span
|
||||
entry = text[start:end]
|
||||
new_entry, added = append_keys_to_entry(entry, keys)
|
||||
if not added and not created:
|
||||
return {
|
||||
"ok": True,
|
||||
"changed": False,
|
||||
"channel": channel,
|
||||
"added": [],
|
||||
"existing": [_redact(k) for k in list_keys_in_entry(entry)],
|
||||
"config": str(config_path),
|
||||
}
|
||||
|
||||
new_text = text[:start] + new_entry + text[end:]
|
||||
if dry_run:
|
||||
return {
|
||||
"ok": True,
|
||||
"changed": False,
|
||||
"dry_run": True,
|
||||
"channel": channel,
|
||||
"would_add": [_redact(k) for k in added],
|
||||
"created_channel": created,
|
||||
"config": str(config_path),
|
||||
}
|
||||
|
||||
ts = time.strftime("%Y%m%d-%H%M%S")
|
||||
backup = config_path.with_name(f"{config_path.name}.bak-mimo-{ts}")
|
||||
shutil.copy2(config_path, backup)
|
||||
|
||||
# atomic replace
|
||||
fd, tmp_name = tempfile.mkstemp(
|
||||
prefix=config_path.name + ".",
|
||||
suffix=".tmp",
|
||||
dir=str(config_path.parent),
|
||||
)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
f.write(new_text)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp_name, config_path)
|
||||
except Exception:
|
||||
try:
|
||||
os.unlink(tmp_name)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
# verify
|
||||
verify = config_path.read_text(encoding="utf-8")
|
||||
vspan = _channel_block_span(verify, channel)
|
||||
if vspan is None:
|
||||
raise SystemExit("post-write: channel missing (restoring not auto — check backup)")
|
||||
vkeys = set(list_keys_in_entry(verify[vspan[0] : vspan[1]]))
|
||||
missing = [k for k in keys if k not in vkeys]
|
||||
if missing:
|
||||
raise SystemExit(f"post-write: keys not present: {[ _redact(k) for k in missing ]}")
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"changed": True,
|
||||
"channel": channel,
|
||||
"added": [_redact(k) for k in added],
|
||||
"created_channel": created,
|
||||
"backup": str(backup),
|
||||
"config": str(config_path),
|
||||
"key_count": len(vkeys),
|
||||
}
|
||||
|
||||
|
||||
def inject_via_ssh(
|
||||
ssh_host: str,
|
||||
keys: list[str],
|
||||
*,
|
||||
config: str,
|
||||
channel: str = DEFAULT_CHANNEL,
|
||||
base_url: str = DEFAULT_BASE_URL,
|
||||
models: tuple[str, ...] = DEFAULT_MODELS,
|
||||
priority: int = 100,
|
||||
dry_run: bool = False,
|
||||
) -> dict:
|
||||
"""Ship this script + keys to remote python (keys via temp file, not argv)."""
|
||||
self_path = Path(__file__).resolve()
|
||||
remote_script = f"/tmp/inject_cpa_openai_{os.getpid()}.py"
|
||||
remote_keys = f"/tmp/mimo_keys_{os.getpid()}.txt"
|
||||
keys_blob = "\n".join(keys) + "\n"
|
||||
ssh_base = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=20", ssh_host]
|
||||
|
||||
up1 = subprocess.run(
|
||||
[
|
||||
"scp",
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"ConnectTimeout=20",
|
||||
str(self_path),
|
||||
f"{ssh_host}:{remote_script}",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if up1.returncode != 0:
|
||||
raise SystemExit(f"scp script failed: {up1.stderr or up1.stdout}")
|
||||
|
||||
up2 = subprocess.run(
|
||||
ssh_base + [f"cat > {remote_keys} && chmod 600 {remote_keys}"],
|
||||
input=keys_blob,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if up2.returncode != 0:
|
||||
raise SystemExit(f"upload keys failed: {up2.stderr or up2.stdout}")
|
||||
|
||||
parts = [
|
||||
"python3",
|
||||
remote_script,
|
||||
"--config",
|
||||
config,
|
||||
"--channel",
|
||||
channel,
|
||||
"--base-url",
|
||||
base_url,
|
||||
"--priority",
|
||||
str(priority),
|
||||
"--from-file",
|
||||
remote_keys,
|
||||
]
|
||||
for m in models:
|
||||
parts.extend(["--model", m])
|
||||
if dry_run:
|
||||
parts.append("--dry-run")
|
||||
remote_cmd = " ".join(parts) + f"; ec=$?; rm -f {remote_keys} {remote_script}; exit $ec"
|
||||
proc = subprocess.run(
|
||||
ssh_base + [remote_cmd],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
out = (proc.stdout or "") + (proc.stderr or "")
|
||||
if proc.returncode != 0:
|
||||
raise SystemExit(f"remote inject failed exit={proc.returncode}: {out[-2000:]}")
|
||||
for line in reversed(out.splitlines()):
|
||||
line = line.strip()
|
||||
if line.startswith("{") and line.endswith("}"):
|
||||
try:
|
||||
return json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
return {"ok": True, "raw": out[-1500:]}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
p = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Inject MiMo sk- keys into CPA openai-compatibility. "
|
||||
"Refuses implicit production paths: pass --config or CPA_CONFIG."
|
||||
)
|
||||
)
|
||||
p.add_argument(
|
||||
"--config",
|
||||
default=None,
|
||||
help=f"CPA config.yaml path (or env CPA_CONFIG). Prod hint: {PROD_CONFIG_HINT}",
|
||||
)
|
||||
p.add_argument("--channel", default=DEFAULT_CHANNEL)
|
||||
p.add_argument("--base-url", default=DEFAULT_BASE_URL)
|
||||
p.add_argument("--priority", type=int, default=100)
|
||||
p.add_argument("--model", action="append", dest="models")
|
||||
p.add_argument("--key", action="append", dest="keys")
|
||||
p.add_argument("--from-file", type=Path)
|
||||
p.add_argument("--from-jsonl", type=Path)
|
||||
p.add_argument("--ssh", help="ssh host alias (e.g. tebi-tunnel); runs inject on remote")
|
||||
p.add_argument("--dry-run", action="store_true")
|
||||
p.add_argument(
|
||||
"--i-understand-production",
|
||||
action="store_true",
|
||||
help="Required when --config points at production CPA path",
|
||||
)
|
||||
args = p.parse_args(argv)
|
||||
|
||||
config = (args.config or os.environ.get("CPA_CONFIG") or "").strip()
|
||||
if not config:
|
||||
print(
|
||||
"refusing: pass --config PATH or set CPA_CONFIG "
|
||||
f"(production example: --config {PROD_CONFIG_HINT} --i-understand-production)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
|
||||
config_path = Path(config)
|
||||
looks_prod = (
|
||||
str(config_path) == PROD_CONFIG_HINT
|
||||
or str(config_path).endswith("/personal/cpa/config.yaml")
|
||||
or str(config_path) == "/personal/cpa/config.yaml"
|
||||
)
|
||||
if looks_prod and not args.i_understand_production and not args.dry_run:
|
||||
print(
|
||||
"refusing production CPA path without --i-understand-production "
|
||||
"(or use --dry-run first)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
|
||||
keys: list[str] = []
|
||||
for k in args.keys or []:
|
||||
keys.extend(extract_keys_from_text(k))
|
||||
if args.from_file:
|
||||
keys.extend(extract_keys_from_text(args.from_file.read_text(encoding="utf-8", errors="replace")))
|
||||
if args.from_jsonl:
|
||||
keys.extend(extract_keys_from_jsonl(args.from_jsonl))
|
||||
# de-dupe preserve order
|
||||
uniq: list[str] = []
|
||||
for k in keys:
|
||||
if k not in uniq:
|
||||
uniq.append(k)
|
||||
keys = uniq
|
||||
if not keys:
|
||||
print("no sk- keys found", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
models = tuple(args.models) if args.models else DEFAULT_MODELS
|
||||
if args.ssh:
|
||||
result = inject_via_ssh(
|
||||
args.ssh,
|
||||
keys,
|
||||
config=config,
|
||||
channel=args.channel,
|
||||
base_url=args.base_url,
|
||||
models=models,
|
||||
priority=args.priority,
|
||||
dry_run=args.dry_run,
|
||||
)
|
||||
else:
|
||||
result = inject_local(
|
||||
config_path,
|
||||
keys,
|
||||
channel=args.channel,
|
||||
base_url=args.base_url,
|
||||
models=models,
|
||||
priority=args.priority,
|
||||
dry_run=args.dry_run,
|
||||
)
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
return 0 if result.get("ok") else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "xiaomi-mimo-api-key-generator",
|
||||
"version": "1.0.0",
|
||||
"description": "CLI automation bot that registers Xiaomi accounts, verifies OTP via temp mail, joins MiMo invite flow, and saves API keys.",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "ts-node src/index.ts",
|
||||
"cdp": "ts-node src/cdp-mode.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"chalk": "^4.1.2",
|
||||
"dotenv": "^16.4.5",
|
||||
"imap-simple": "1.6.3",
|
||||
"log-update": "^8.0.0",
|
||||
"playwright": "^1.48.1",
|
||||
"playwright-extra": "^4.3.6",
|
||||
"prompts": "^2.4.2",
|
||||
"proxy-chain": "^3.0.0",
|
||||
"puppeteer-extra-plugin-stealth": "^2.11.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/imap-simple": "^4.2.7",
|
||||
"@types/log-update": "^2.0.0",
|
||||
"@types/node": "^20.14.0",
|
||||
"@types/prompts": "^2.4.9",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.5.0"
|
||||
},
|
||||
"overrides": {
|
||||
"semver": "5.7.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env bash
|
||||
# MiMo one-shot register (production path: scripts/register-one.js).
|
||||
# Usage:
|
||||
# bash providers/mimo/run-register.sh
|
||||
# COUNT=1 bash providers/mimo/run-register.sh
|
||||
# Env:
|
||||
# MIMO_RUNTIME — dir with node_modules/playwright (default: this provider dir, or /personal/mimo-register)
|
||||
# MIMO_PROXY — default http://127.0.0.1:7897
|
||||
# HEADLESS — true|false (default true)
|
||||
# OTP_RETRIES — tinyhost poll retries (default 35)
|
||||
# MIMO_INVITE_CODE — optional
|
||||
set -euo pipefail
|
||||
|
||||
PROVIDER_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
if [[ -n "${MIMO_RUNTIME:-}" ]]; then
|
||||
RUNTIME="$MIMO_RUNTIME"
|
||||
elif [[ -d /personal/mimo-register/node_modules ]]; then
|
||||
RUNTIME=/personal/mimo-register
|
||||
elif [[ -d "$PROVIDER_DIR/node_modules" ]]; then
|
||||
RUNTIME="$PROVIDER_DIR"
|
||||
else
|
||||
RUNTIME="$PROVIDER_DIR"
|
||||
fi
|
||||
|
||||
SCRIPT_SRC="$PROVIDER_DIR/scripts/register-one.js"
|
||||
if [[ ! -f "$SCRIPT_SRC" ]]; then
|
||||
SCRIPT_SRC="$RUNTIME/scripts/register-one.js"
|
||||
fi
|
||||
if [[ ! -f "$SCRIPT_SRC" ]]; then
|
||||
echo "register-one.js not found under $PROVIDER_DIR or $RUNTIME" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Sync versioned script into runtime so require('../dist/temp-mail') resolves on pxed
|
||||
if [[ "$RUNTIME" != "$PROVIDER_DIR" ]]; then
|
||||
mkdir -p "$RUNTIME/scripts" "$RUNTIME/output" "$RUNTIME/logs"
|
||||
cp -f "$SCRIPT_SRC" "$RUNTIME/scripts/register-one.js"
|
||||
RUN_JS="$RUNTIME/scripts/register-one.js"
|
||||
cd "$RUNTIME"
|
||||
else
|
||||
mkdir -p "$PROVIDER_DIR/output" "$PROVIDER_DIR/logs"
|
||||
RUN_JS="$SCRIPT_SRC"
|
||||
cd "$PROVIDER_DIR"
|
||||
fi
|
||||
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy no_proxy NO_PROXY || true
|
||||
export PATH="/usr/local/bin:/usr/bin:/bin:${PATH:-}"
|
||||
|
||||
export MIMO_PROXY="${MIMO_PROXY:-http://127.0.0.1:7897}"
|
||||
export http_proxy="$MIMO_PROXY"
|
||||
export https_proxy="$MIMO_PROXY"
|
||||
export HTTP_PROXY="$MIMO_PROXY"
|
||||
export HTTPS_PROXY="$MIMO_PROXY"
|
||||
export NO_PROXY=127.0.0.1,localhost
|
||||
export no_proxy=127.0.0.1,localhost
|
||||
|
||||
export HEADLESS="${HEADLESS:-true}"
|
||||
export OTP_RETRIES="${OTP_RETRIES:-35}"
|
||||
export XIAOMI_REGION="${XIAOMI_REGION:-Singapore}"
|
||||
|
||||
ensure_clash() {
|
||||
if command -v ss >/dev/null 2>&1 && ss -lntp 2>/dev/null | grep -q ':7897'; then
|
||||
echo "[mimo] clash already up on 7897"
|
||||
return 0
|
||||
fi
|
||||
if command -v netstat >/dev/null 2>&1 && netstat -tlnp 2>/dev/null | grep -q '7897'; then
|
||||
echo "[mimo] clash already up on 7897"
|
||||
return 0
|
||||
fi
|
||||
local starter monorepo
|
||||
for monorepo in \
|
||||
"${GROK_CODE_ROOT:-}" \
|
||||
/personal/ai-register-machine \
|
||||
/personal/register-machine \
|
||||
/personal/grok-register \
|
||||
"$(cd "$PROVIDER_DIR/../.." && pwd)"
|
||||
do
|
||||
[[ -n "$monorepo" ]] || continue
|
||||
starter="$monorepo/start-clash-for-grok.sh"
|
||||
if [[ -x "$starter" ]]; then
|
||||
echo "[mimo] starting clash via $starter ..."
|
||||
bash "$starter"
|
||||
return $?
|
||||
fi
|
||||
done
|
||||
echo "[mimo] WARN: no clash starter; ensure $MIMO_PROXY is reachable" >&2
|
||||
return 0
|
||||
}
|
||||
|
||||
ensure_xvfb() {
|
||||
export DISPLAY="${DISPLAY:-:99}"
|
||||
if pgrep -f 'Xvfb :99' >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
if command -v Xvfb >/dev/null 2>&1; then
|
||||
Xvfb :99 -screen 0 1280x900x24 -ac -nolisten tcp >/tmp/xvfb-mimo.log 2>&1 &
|
||||
sleep 1
|
||||
fi
|
||||
}
|
||||
|
||||
COUNT="${COUNT:-1}"
|
||||
if [[ "${1:-}" =~ ^[0-9]+$ ]]; then
|
||||
COUNT="$1"
|
||||
fi
|
||||
|
||||
ensure_clash
|
||||
ensure_xvfb
|
||||
export DISPLAY="${DISPLAY:-:99}"
|
||||
|
||||
TS=$(date +%Y%m%d_%H%M%S)
|
||||
LOG_DIR="${RUNTIME}/logs"
|
||||
mkdir -p "$LOG_DIR" "${RUNTIME}/output"
|
||||
LOG="$LOG_DIR/mimo-register-${TS}.log"
|
||||
|
||||
echo "[mimo] runtime=$RUNTIME script=$RUN_JS proxy=$MIMO_PROXY count=$COUNT" | tee -a "$LOG"
|
||||
|
||||
ok=0
|
||||
fail=0
|
||||
for i in $(seq 1 "$COUNT"); do
|
||||
echo "=== mimo register $i/$COUNT ===" | tee -a "$LOG"
|
||||
set +e
|
||||
node "$RUN_JS" 2>&1 | tee -a "$LOG"
|
||||
code=${PIPESTATUS[0]}
|
||||
set -e
|
||||
if [[ $code -eq 0 ]]; then
|
||||
ok=$((ok + 1))
|
||||
else
|
||||
fail=$((fail + 1))
|
||||
echo "[mimo] fail-fast after error code=$code (no empty spin)" | tee -a "$LOG"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
echo "[mimo] done ok=$ok fail=$fail keys=${RUNTIME}/output/success_keys.txt" | tee -a "$LOG"
|
||||
if [[ $ok -lt 1 ]]; then
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,33 @@
|
||||
const { chromium } = require('playwright-extra');
|
||||
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
|
||||
const stealth = StealthPlugin();
|
||||
stealth.enabledEvasions.delete('user-agent-override');
|
||||
chromium.use(stealth);
|
||||
|
||||
(async () => {
|
||||
const proxy = process.env.SMOKE_PROXY || 'http://127.0.0.1:7897';
|
||||
const url = process.env.SMOKE_URL || 'https://account.xiaomi.com/';
|
||||
console.log('launch proxy=', proxy, 'url=', url);
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-blink-features=AutomationControlled'],
|
||||
proxy: { server: proxy },
|
||||
}).catch(async () => {
|
||||
return chromium.launch({
|
||||
headless: true,
|
||||
channel: 'chrome',
|
||||
args: ['--no-sandbox'],
|
||||
proxy: { server: proxy },
|
||||
});
|
||||
});
|
||||
const page = await browser.newPage();
|
||||
const resp = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });
|
||||
console.log('status', resp && resp.status(), 'final', page.url());
|
||||
console.log('title', await page.title());
|
||||
await page.screenshot({ path: 'output/smoke-xiaomi.png', fullPage: true }).catch(() => {});
|
||||
await browser.close();
|
||||
console.log('SMOKE_OK');
|
||||
})().catch((e) => {
|
||||
console.error('SMOKE_FAIL', e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
# Smoke: tinyhost API + Playwright open account.xiaomi.com via clash.
|
||||
set -euo pipefail
|
||||
|
||||
PROVIDER_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
if [[ -d /personal/mimo-register/node_modules ]]; then
|
||||
RUNTIME=/personal/mimo-register
|
||||
elif [[ -d "$PROVIDER_DIR/node_modules" ]]; then
|
||||
RUNTIME="$PROVIDER_DIR"
|
||||
else
|
||||
RUNTIME="$PROVIDER_DIR"
|
||||
fi
|
||||
|
||||
SMOKE_JS="$PROVIDER_DIR/scripts/smoke-browser.js"
|
||||
if [[ ! -f "$SMOKE_JS" ]]; then
|
||||
SMOKE_JS="$RUNTIME/scripts/smoke-browser.js"
|
||||
fi
|
||||
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy no_proxy NO_PROXY || true
|
||||
export PATH="/usr/local/bin:/usr/bin:/bin:${PATH:-}"
|
||||
export http_proxy="${MIMO_PROXY:-http://127.0.0.1:7897}"
|
||||
export https_proxy="$http_proxy"
|
||||
export HTTP_PROXY="$http_proxy"
|
||||
export HTTPS_PROXY="$http_proxy"
|
||||
export NO_PROXY=127.0.0.1,localhost
|
||||
export no_proxy=$NO_PROXY
|
||||
|
||||
if [[ -x /personal/grok-register/start-clash-for-grok.sh ]]; then
|
||||
if ! (ss -lntp 2>/dev/null | grep -q ':7897' || netstat -tlnp 2>/dev/null | grep -q '7897'); then
|
||||
bash /personal/grok-register/start-clash-for-grok.sh
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "=== tempmail tinyhost ==="
|
||||
curl -sS --max-time 20 'https://tinyhost.shop/api/random-domains/?limit=3' | head -c 400
|
||||
echo
|
||||
echo "=== playwright smoke xiaomi ==="
|
||||
cd "$RUNTIME"
|
||||
if [[ "$SMOKE_JS" != "$RUNTIME/scripts/smoke-browser.js" && -f "$SMOKE_JS" ]]; then
|
||||
mkdir -p "$RUNTIME/scripts"
|
||||
cp -f "$SMOKE_JS" "$RUNTIME/scripts/smoke-browser.js"
|
||||
node scripts/smoke-browser.js
|
||||
else
|
||||
node "$SMOKE_JS"
|
||||
fi
|
||||
echo SMOKE_OK
|
||||
@@ -0,0 +1,15 @@
|
||||
# typesafe provider — copy env, do not commit secrets
|
||||
#
|
||||
# Education / personal automation only. Default COUNT=1.
|
||||
# Do not copy the original farm defaults (ACCOUNT_COUNT=512 / CONCURRENCY=256).
|
||||
|
||||
# TYPESAFE_EMAIL_SOURCE=tinyhost
|
||||
# TYPESAFE_OTP_TIMEOUT=180
|
||||
# TYPESAFE_API_KEY_NAME=register-core
|
||||
|
||||
# Optional fixed URL (mainly with REGISTER_EGRESS=clash or direct override)
|
||||
# TYPESAFE_PROXY=http://127.0.0.1:7897
|
||||
|
||||
# HTTP/SOCKS pool (REGISTER_EGRESS=list|auto)
|
||||
# TYPESAFE_PROXY_LIST=http://user:pass@1.2.3.4:8080
|
||||
# REGISTER_NODES_FILE=./nodes.json
|
||||
@@ -0,0 +1,80 @@
|
||||
# typesafe.ai / jev console provider
|
||||
|
||||
In-process protocol register for **typesafe.ai console** accounts (Stytch
|
||||
magic-link + `/api/auth/callback` + `/api/api-keys`). Produces a this-run
|
||||
`api_key`. Ported from [Futureppo/typesafe_register](https://github.com/Futureppo/typesafe_register)
|
||||
(Apache-2.0) — **not** a drop-in of that script's 512-account / 256-worker farm.
|
||||
|
||||
## Stack
|
||||
|
||||
| Layer | Choice |
|
||||
|-------|--------|
|
||||
| Style | **In-process** (consumes `EmailSource`) |
|
||||
| HTTP | `requests` + ECDH `prime256v1` TLS pin |
|
||||
| Mail | `tinyhost` default (full body required for magic-link) |
|
||||
| Auth | Stytch magic-link, no browser / Turnstile |
|
||||
| CPA | **none** — never auto-inject production |
|
||||
|
||||
## Hub
|
||||
|
||||
```bash
|
||||
./register.sh typesafe [count]
|
||||
./register.sh core run -p typesafe -n 1 --email-source tinyhost
|
||||
# aliases: jev | typesafe-ai
|
||||
```
|
||||
|
||||
`TYPESAFE_LEGACY=1` falls back to `providers/typesafe/run-register.sh`.
|
||||
|
||||
```bash
|
||||
./register.sh smoke typesafe # tinyhost + console probe, no mailbox
|
||||
TYPESAFE_SMOKE_LIVE=1 ./register.sh smoke typesafe # n=1 this-run api_key
|
||||
```
|
||||
|
||||
## Env
|
||||
|
||||
| Var | Default | Meaning |
|
||||
|-----|---------|---------|
|
||||
| `TYPESAFE_EMAIL_SOURCE` | `tinyhost` | Must return full mail body (not OTP-only) |
|
||||
| `TYPESAFE_EMAIL_DOMAIN` | empty | Optional tinyhost domain pin |
|
||||
| `TYPESAFE_OTP_TIMEOUT` | `180` | Magic-link poll window (seconds) |
|
||||
| `TYPESAFE_API_KEY_NAME` | `register-core` | Console key label |
|
||||
| `TYPESAFE_PROXY` | empty | Fixed register egress |
|
||||
| `TYPESAFE_SKIP_CONSOLE_PROBE` | empty | Skip login GET+parse before mailbox allocate |
|
||||
| `TYPESAFE_SMOKE_LIVE` | `0` | `1` = n=1 live register from `./register.sh smoke typesafe` |
|
||||
| `REGISTER_EGRESS` | `auto` | `list` \| `core` \| `clash` \| `direct` \| `auto` |
|
||||
|
||||
Do **not** set `ACCOUNT_COUNT=512` / `CONCURRENCY=256`. Pipeline `count` /
|
||||
threads own scale. Default is `1`.
|
||||
|
||||
## Artifacts
|
||||
|
||||
- `providers/typesafe/output/` (0700)
|
||||
- `providers/typesafe/output/typesafe-<email>-<ts>.json` (0600) — this-run deliverable
|
||||
- Pipeline sink: `providers/typesafe/output/pipeline.jsonl`
|
||||
|
||||
Success = this-run `secret` / `secret_kind=api_key` plus a new 0600 json.
|
||||
Do **not** append full keys to `accounts.jsonl`; historical tails do not count.
|
||||
|
||||
## Mail
|
||||
|
||||
Cloudflare Worker / Gmail IMAP wrappers in this repo only extract 6-digit
|
||||
OTPs. typesafe login mail carries a Stytch URL, so the default source is
|
||||
tinyhost (subject + body + html). `sender_hint=typesafe`.
|
||||
|
||||
## Latest case (pxed, 2026-09-22)
|
||||
|
||||
`./register.sh typesafe 1000`, 8 workers, `--no-fail-fast`, egress
|
||||
`rotate=off` (fixed Clash mixed-port, this run did **not** rotate IP).
|
||||
|
||||
`CONTRACT_EXIT:0`, ok=976, fail=24 (`mail_miss`×17 no-mail timeouts,
|
||||
`session`×5 HTTP 500 on send, `oauth_callback`×2 HTTP 401). 976 new `0600`
|
||||
json files, dir `0700`, no `accounts.jsonl` append, no CPA inject.
|
||||
|
||||
Same day, smaller runs: n=100 → 97/3 `mail_miss`; after the magic-link parse
|
||||
fix, n=100 → 98/2 HTTP 500.
|
||||
|
||||
## Compliance
|
||||
|
||||
Education / personal automation only. May violate third-party ToS. No
|
||||
mass-farm defaults, no plus-alias, no CPA inject. This project recognizes
|
||||
the [LINUX DO](https://linux.do/) community.
|
||||
@@ -0,0 +1 @@
|
||||
# typesafe.ai / jev product package (in-process protocol).
|
||||
@@ -0,0 +1,5 @@
|
||||
"""typesafe.ai / jev console magic-link registration (in-process)."""
|
||||
|
||||
from .flow import TypesafeRegisterError, TypesafeResult, probe_console, register_one
|
||||
|
||||
__all__ = ["TypesafeRegisterError", "TypesafeResult", "probe_console", "register_one"]
|
||||
@@ -0,0 +1,24 @@
|
||||
"""typesafe.ai console constants (Stytch magic-link + Next.js Server Action)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
CONSOLE_BASE_URL = "https://console.typesafe.ai"
|
||||
LOGIN_PAGE_URL = f"{CONSOLE_BASE_URL}/login"
|
||||
# Fallback Next.js deployment id from the original public login snapshot.
|
||||
# Live HTML is authoritative (pxed 2026-09-22: fb80dfc7f55f4bf7a496bc9579755816f26fae3c);
|
||||
# mismatch is logged; the page $ACTION blob is always preferred.
|
||||
CONSOLE_DEPLOYMENT_ID = "cc6f6dca06537cc04123caaaf50ca5a76d506a92"
|
||||
|
||||
DEFAULT_API_KEY_NAME = "register-core"
|
||||
DEFAULT_TIMEOUT = 30
|
||||
TLS_ECDH_CURVE = "prime256v1"
|
||||
|
||||
USER_AGENT = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 Edg/147.0.0.0"
|
||||
)
|
||||
|
||||
COMMON_HEADERS: dict[str, str] = {
|
||||
"User-Agent": USER_AGENT,
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.7",
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
"""typesafe.ai Stytch magic-link + console API-key protocol.
|
||||
|
||||
Ported from Futureppo/typesafe_register (Apache-2.0) as an in-process flow.
|
||||
Mailbox comes from register_core EmailSource — do not use the original
|
||||
512/256 farm defaults or TEMPMAIL placeholders.
|
||||
|
||||
Success = this-run API key. Never treat historical accounts.json as ok.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from register_core.decode.extract import extract_typesafe_magic_link
|
||||
from register_core.errors import MailMissError
|
||||
|
||||
from .constants import (
|
||||
CONSOLE_BASE_URL,
|
||||
CONSOLE_DEPLOYMENT_ID,
|
||||
DEFAULT_API_KEY_NAME,
|
||||
DEFAULT_TIMEOUT,
|
||||
LOGIN_PAGE_URL,
|
||||
)
|
||||
|
||||
LogFn = Callable[[str], None]
|
||||
_deployment_drift_logged = False
|
||||
|
||||
|
||||
class TypesafeRegisterError(RuntimeError):
|
||||
"""Single-attempt registration failure (caller maps to RegisterResult)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
kind: str = "provider",
|
||||
step: str = "",
|
||||
steps: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.kind = kind
|
||||
self.step = step or ""
|
||||
self.steps: dict[str, Any] = dict(steps or {})
|
||||
|
||||
|
||||
@dataclass
|
||||
class TypesafeResult:
|
||||
ok: bool
|
||||
email: str = ""
|
||||
api_key: str = ""
|
||||
api_key_id: str = ""
|
||||
user_id: str = ""
|
||||
organization_id: str = ""
|
||||
organization_name: str = ""
|
||||
magic_link: str = ""
|
||||
error: str = ""
|
||||
error_kind: str = ""
|
||||
fail_step: str = ""
|
||||
steps: dict[str, Any] = field(default_factory=dict)
|
||||
deployment_id: str = ""
|
||||
deployment_mismatch: bool = False
|
||||
|
||||
def to_public_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"ok": self.ok,
|
||||
"email": self.email,
|
||||
"api_key": _preview(self.api_key),
|
||||
"api_key_id": self.api_key_id,
|
||||
"user_id": self.user_id,
|
||||
"organization_id": self.organization_id,
|
||||
"error": self.error,
|
||||
"error_kind": self.error_kind,
|
||||
"fail_step": self.fail_step,
|
||||
"step_keys": sorted(self.steps.keys()),
|
||||
"deployment_mismatch": self.deployment_mismatch,
|
||||
}
|
||||
|
||||
|
||||
def _preview(value: str) -> str:
|
||||
s = value or ""
|
||||
if not s:
|
||||
return ""
|
||||
if len(s) <= 8:
|
||||
return "***"
|
||||
return f"{s[:4]}…{s[-4:]}(len={len(s)})"
|
||||
|
||||
|
||||
def _action_snippet(page: str, limit: int = 400) -> str:
|
||||
"""Short $ACTION window for session failures — not the full login HTML."""
|
||||
raw = str(page or "")
|
||||
if not raw:
|
||||
return ""
|
||||
idx = raw.find("$ACTION_")
|
||||
if idx < 0:
|
||||
idx = raw.find('type="email"')
|
||||
if idx < 0:
|
||||
return raw[:limit]
|
||||
start = max(0, idx - 80)
|
||||
return raw[start : start + limit]
|
||||
|
||||
|
||||
def parse_login_action(page: str) -> dict[str, str]:
|
||||
"""Parse Next.js $ACTION_* blob + action id from the console login HTML."""
|
||||
raw = str(page or "")
|
||||
if not raw.strip():
|
||||
raise TypesafeRegisterError("login page empty", kind="session", step="login_action")
|
||||
pos = raw.find('type="email"')
|
||||
window = raw[:pos] if pos >= 0 else raw
|
||||
indexes = re.findall(r"\\?\$ACTION_(\d+):0", window)
|
||||
if not indexes:
|
||||
indexes = re.findall(r"\$ACTION_(\d+):0", window)
|
||||
if not indexes:
|
||||
raise TypesafeRegisterError(
|
||||
"login page missing $ACTION index",
|
||||
kind="session",
|
||||
step="login_action",
|
||||
steps={"login_action": {"ok": False, "html_snippet": _action_snippet(raw)}},
|
||||
)
|
||||
index = indexes[-1]
|
||||
ref_m = re.search(rf'\\?\$ACTION_{re.escape(index)}:0" value="([^"]+)"', raw)
|
||||
if not ref_m:
|
||||
ref_m = re.search(rf'\$ACTION_{re.escape(index)}:0" value="([^"]+)"', raw)
|
||||
if not ref_m:
|
||||
raise TypesafeRegisterError(
|
||||
"login page missing $ACTION ref",
|
||||
kind="session",
|
||||
step="login_action",
|
||||
steps={"login_action": {"ok": False, "html_snippet": _action_snippet(raw)}},
|
||||
)
|
||||
try:
|
||||
ref = json.loads(html.unescape(ref_m.group(1)))
|
||||
except Exception as exc:
|
||||
raise TypesafeRegisterError(
|
||||
f"login action ref json: {exc}",
|
||||
kind="session",
|
||||
step="login_action",
|
||||
) from exc
|
||||
action_id = str((ref or {}).get("id") or "").strip()
|
||||
if not action_id:
|
||||
raise TypesafeRegisterError(
|
||||
"login action id empty",
|
||||
kind="session",
|
||||
step="login_action",
|
||||
)
|
||||
blob_m = re.search(rf'\\?\$ACTION_{re.escape(index)}:2" value="([^"]+)"', raw)
|
||||
if not blob_m:
|
||||
blob_m = re.search(rf'\$ACTION_{re.escape(index)}:2" value="([^"]+)"', raw)
|
||||
if not blob_m:
|
||||
raise TypesafeRegisterError(
|
||||
"login page missing encrypted action blob",
|
||||
kind="session",
|
||||
step="login_action",
|
||||
steps={"login_action": {"ok": False, "html_snippet": _action_snippet(raw)}},
|
||||
)
|
||||
return {
|
||||
"action_id": action_id,
|
||||
"index": index,
|
||||
"blob": html.unescape(blob_m.group(1)),
|
||||
}
|
||||
|
||||
|
||||
def parse_deployment_id(page: str) -> str:
|
||||
m = re.search(r"dpl=([0-9a-f]{20,})", str(page or ""))
|
||||
return m.group(1) if m else ""
|
||||
|
||||
|
||||
def extract_magic_link(blob: str, subject: str = "") -> dict[str, str]:
|
||||
"""Return {public_token, token, magic_link} or empty dict."""
|
||||
hay = "\n".join([str(subject or ""), str(blob or "")])
|
||||
parsed = extract_typesafe_magic_link(hay)
|
||||
if not parsed:
|
||||
return {}
|
||||
return parsed
|
||||
|
||||
|
||||
def _usable_login_action(action: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""Return the action dict only when send_magic_link can POST it."""
|
||||
if not isinstance(action, dict):
|
||||
return None
|
||||
if not str(action.get("action_id") or "").strip():
|
||||
return None
|
||||
if not str(action.get("index") or "").strip():
|
||||
return None
|
||||
if not str(action.get("blob") or "").strip():
|
||||
return None
|
||||
return action
|
||||
|
||||
|
||||
def _classify_login_http(status: int, *, step: str, label: str) -> None:
|
||||
"""5xx / no status = network; 4xx = session. Do not parse error bodies as login HTML."""
|
||||
if status <= 0:
|
||||
raise TypesafeRegisterError(f"{label} no http status", kind="network", step=step)
|
||||
if status >= 500:
|
||||
raise TypesafeRegisterError(f"{label} HTTP {status}", kind="network", step=step)
|
||||
if status >= 400:
|
||||
raise TypesafeRegisterError(f"{label} HTTP {status}", kind="session", step=step)
|
||||
|
||||
|
||||
def _fetch_login_page_action(
|
||||
session: Any,
|
||||
*,
|
||||
log: LogFn | None = None,
|
||||
step: str = "login_action",
|
||||
label: str = "login GET",
|
||||
emit_status: bool = False,
|
||||
) -> tuple[dict[str, Any], int]:
|
||||
emit = log or (lambda _m: None)
|
||||
resp, err = _get(session, LOGIN_PAGE_URL, headers={"accept": "text/html,application/xhtml+xml"})
|
||||
if resp is None:
|
||||
raise TypesafeRegisterError(f"{label} failed: {err}", kind="network", step=step)
|
||||
status = int(getattr(resp, "status_code", 0) or 0)
|
||||
if emit_status:
|
||||
emit(f"{step} status={status}")
|
||||
_classify_login_http(status, step=step, label=label)
|
||||
page = getattr(resp, "text", "") or ""
|
||||
dpl = parse_deployment_id(page)
|
||||
if dpl and dpl != CONSOLE_DEPLOYMENT_ID:
|
||||
# Once per process. n=100 otherwise logs the same drift on every GET.
|
||||
global _deployment_drift_logged
|
||||
if not _deployment_drift_logged:
|
||||
_deployment_drift_logged = True
|
||||
emit(f"console deployment changed {CONSOLE_DEPLOYMENT_ID} -> {dpl}")
|
||||
action = parse_login_action(page)
|
||||
action["deployment_id"] = dpl
|
||||
action["deployment_mismatch"] = bool(dpl and dpl != CONSOLE_DEPLOYMENT_ID)
|
||||
return action, status
|
||||
|
||||
|
||||
def probe_console(
|
||||
session: Any | None = None,
|
||||
*,
|
||||
proxy: str = "",
|
||||
log: LogFn | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""GET + parse the login page *before* mailbox allocate.
|
||||
|
||||
Clash/list preflight is skipped for ``egress=clash``. A dead mixed port
|
||||
would otherwise burn a tinyhost address on the first login GET. HTTP 5xx
|
||||
is ``network``; 4xx is ``session``; parse failure is ``session``. The
|
||||
parsed ``action`` is returned so ``register_one`` can POST without a
|
||||
second login GET after allocate.
|
||||
"""
|
||||
from .session import create_session
|
||||
|
||||
sess = session if session is not None else create_session(proxy)
|
||||
action, status = _fetch_login_page_action(
|
||||
sess,
|
||||
log=log,
|
||||
step="console_probe",
|
||||
label="console probe",
|
||||
emit_status=True,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"status": status,
|
||||
"index": action.get("index"),
|
||||
"deployment_id": action.get("deployment_id") or "",
|
||||
"url": LOGIN_PAGE_URL,
|
||||
"action": {
|
||||
"action_id": action["action_id"],
|
||||
"index": action["index"],
|
||||
"blob": action["blob"],
|
||||
"deployment_id": str(action.get("deployment_id") or ""),
|
||||
"deployment_mismatch": bool(action.get("deployment_mismatch")),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def login_action(session: Any, *, log: LogFn | None = None) -> dict[str, Any]:
|
||||
action, _status = _fetch_login_page_action(
|
||||
session,
|
||||
log=log,
|
||||
step="login_action",
|
||||
label="login GET",
|
||||
emit_status=False,
|
||||
)
|
||||
return action
|
||||
|
||||
|
||||
def send_magic_link(
|
||||
session: Any,
|
||||
email: str,
|
||||
*,
|
||||
action: dict[str, Any] | None = None,
|
||||
log: LogFn | None = None,
|
||||
) -> dict[str, str]:
|
||||
emit = log or (lambda _m: None)
|
||||
last_status = 0
|
||||
last_redirect = ""
|
||||
for refresh in (False, True):
|
||||
current = action if (action and not refresh) else login_action(session, log=emit)
|
||||
action = current
|
||||
boundary = "----WebKitFormBoundary" + uuid.uuid4().hex[:16]
|
||||
idx = current["index"]
|
||||
body = (
|
||||
f"--{boundary}\r\nContent-Disposition: form-data; name=\"1\"\r\n\r\n{current['blob']}\r\n"
|
||||
f"--{boundary}\r\nContent-Disposition: form-data; name=\"_{idx}_email\"\r\n\r\n{email}\r\n"
|
||||
f"--{boundary}\r\nContent-Disposition: form-data; name=\"0\"\r\n\r\n[\"$@1\",\"$K{idx}\"]\r\n"
|
||||
f"--{boundary}--\r\n"
|
||||
).encode()
|
||||
resp, err = _post(
|
||||
session,
|
||||
LOGIN_PAGE_URL,
|
||||
data=body,
|
||||
headers={
|
||||
"content-type": f"multipart/form-data; boundary={boundary}",
|
||||
"next-action": current["action_id"],
|
||||
"accept": "text/x-component",
|
||||
"origin": CONSOLE_BASE_URL,
|
||||
"referer": LOGIN_PAGE_URL,
|
||||
"sec-fetch-site": "same-origin",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-dest": "empty",
|
||||
},
|
||||
)
|
||||
if resp is None:
|
||||
raise TypesafeRegisterError(
|
||||
f"send magic link failed: {err}",
|
||||
kind="network",
|
||||
step="send_magic_link",
|
||||
)
|
||||
last_status = int(getattr(resp, "status_code", 0) or 0)
|
||||
last_redirect = str(resp.headers.get("x-action-redirect", "") or "")
|
||||
if last_status == 200 and "sent=true" in last_redirect:
|
||||
return {
|
||||
"action_id": current["action_id"],
|
||||
"form_index": idx,
|
||||
"x_action_redirect": last_redirect,
|
||||
"deployment_id": str(current.get("deployment_id") or ""),
|
||||
"deployment_mismatch": bool(current.get("deployment_mismatch")),
|
||||
}
|
||||
emit(f"send_magic_link retry refresh={refresh} status={last_status}")
|
||||
raise TypesafeRegisterError(
|
||||
f"send magic link failed: HTTP {last_status} redirect={last_redirect!r}",
|
||||
kind="session",
|
||||
step="send_magic_link",
|
||||
)
|
||||
|
||||
|
||||
def auth_callback(session: Any, token: str) -> dict[str, Any]:
|
||||
token = (token or "").strip()
|
||||
if not token:
|
||||
raise TypesafeRegisterError("empty magic-link token", kind="oauth_callback", step="callback")
|
||||
resp, err = _post(
|
||||
session,
|
||||
f"{CONSOLE_BASE_URL}/api/auth/callback",
|
||||
json={"token": token, "tokenType": "magic_links", "preferredOrgId": None},
|
||||
headers={
|
||||
"content-type": "application/json",
|
||||
"accept": "*/*",
|
||||
"origin": CONSOLE_BASE_URL,
|
||||
"referer": f"{CONSOLE_BASE_URL}/auth/callback?stytch_token_type=magic_links",
|
||||
"sec-fetch-site": "same-origin",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-dest": "empty",
|
||||
},
|
||||
)
|
||||
if resp is None:
|
||||
raise TypesafeRegisterError(f"auth callback failed: {err}", kind="network", step="callback")
|
||||
status = int(getattr(resp, "status_code", 0) or 0)
|
||||
if status >= 400:
|
||||
raise TypesafeRegisterError(
|
||||
f"auth callback HTTP {status}",
|
||||
kind="oauth_callback",
|
||||
step="callback",
|
||||
)
|
||||
from .session import response_json
|
||||
|
||||
data = response_json(resp)
|
||||
if not data:
|
||||
raise TypesafeRegisterError("auth callback empty json", kind="oauth_callback", step="callback")
|
||||
return data
|
||||
|
||||
|
||||
def create_api_key(session: Any, name: str | None = None) -> dict[str, Any]:
|
||||
key_name = (name or os.environ.get("TYPESAFE_API_KEY_NAME") or DEFAULT_API_KEY_NAME).strip()
|
||||
resp, err = _post(
|
||||
session,
|
||||
f"{CONSOLE_BASE_URL}/api/api-keys",
|
||||
json={"name": key_name},
|
||||
headers={
|
||||
"content-type": "application/json",
|
||||
"accept": "*/*",
|
||||
"origin": CONSOLE_BASE_URL,
|
||||
"referer": f"{CONSOLE_BASE_URL}/keys",
|
||||
"sec-fetch-site": "same-origin",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-dest": "empty",
|
||||
},
|
||||
)
|
||||
if resp is None:
|
||||
raise TypesafeRegisterError(f"create api key failed: {err}", kind="network", step="api_key")
|
||||
status = int(getattr(resp, "status_code", 0) or 0)
|
||||
if status >= 400:
|
||||
raise TypesafeRegisterError(
|
||||
f"create api key HTTP {status}",
|
||||
kind="token",
|
||||
step="api_key",
|
||||
)
|
||||
from .session import response_json
|
||||
|
||||
data = response_json(resp)
|
||||
if not str(data.get("api_key") or "").strip():
|
||||
raise TypesafeRegisterError(
|
||||
"create api key missing api_key field",
|
||||
kind="token",
|
||||
step="api_key",
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
def save_result(result: TypesafeResult, path: Path) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
path.parent.chmod(0o700)
|
||||
except Exception:
|
||||
pass
|
||||
payload = {
|
||||
"ok": result.ok,
|
||||
"email": result.email,
|
||||
"api_key": result.api_key,
|
||||
"api_key_id": result.api_key_id,
|
||||
"user_id": result.user_id,
|
||||
"organization_id": result.organization_id,
|
||||
"organization_name": result.organization_name,
|
||||
"provider": "typesafe",
|
||||
}
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
try:
|
||||
path.chmod(0o600)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def register_one(
|
||||
*,
|
||||
email: str,
|
||||
proxy: str = "",
|
||||
magic_link_provider: Callable[[], str],
|
||||
log: LogFn | None = None,
|
||||
api_key_name: str | None = None,
|
||||
session: Any | None = None,
|
||||
action: dict[str, Any] | None = None,
|
||||
) -> TypesafeResult:
|
||||
"""Run login → send link → wait mail → callback → mint API key.
|
||||
|
||||
``action`` is the console-probe parse (same session). When usable, skip
|
||||
the post-allocate login GET so a transient 5xx cannot burn the mailbox.
|
||||
``send_magic_link`` still re-GETs on POST failure.
|
||||
"""
|
||||
from .session import create_session
|
||||
|
||||
emit = log or (lambda _m: None)
|
||||
steps: dict[str, Any] = {}
|
||||
sess = session if session is not None else create_session(proxy)
|
||||
result = TypesafeResult(ok=False, email=email)
|
||||
|
||||
try:
|
||||
emit(f"login_action email={email}")
|
||||
reused = _usable_login_action(action)
|
||||
if reused is not None:
|
||||
action = reused
|
||||
emit("login_action reused from console_probe")
|
||||
else:
|
||||
action = login_action(sess, log=emit)
|
||||
result.deployment_id = str(action.get("deployment_id") or "")
|
||||
result.deployment_mismatch = bool(action.get("deployment_mismatch"))
|
||||
steps["login_action"] = {
|
||||
"ok": True,
|
||||
"index": action.get("index"),
|
||||
"deployment_mismatch": result.deployment_mismatch,
|
||||
"reused_probe": reused is not None,
|
||||
}
|
||||
|
||||
emit("send_magic_link")
|
||||
sent = send_magic_link(sess, email, action=action, log=emit)
|
||||
steps["send_magic_link"] = {
|
||||
"ok": True,
|
||||
"redirect": sent.get("x_action_redirect", ""),
|
||||
}
|
||||
|
||||
emit("wait_magic_link")
|
||||
raw_link = str(magic_link_provider() or "").strip()
|
||||
parsed = extract_magic_link(raw_link)
|
||||
if not parsed:
|
||||
raise TypesafeRegisterError(
|
||||
"magic link missing or malformed",
|
||||
kind="mail_miss",
|
||||
step="wait_magic_link",
|
||||
steps=steps,
|
||||
)
|
||||
result.magic_link = parsed["magic_link"]
|
||||
steps["wait_magic_link"] = {"ok": True, "has_token": True}
|
||||
|
||||
emit("auth_callback")
|
||||
cb = auth_callback(sess, parsed["token"])
|
||||
result.user_id = str(cb.get("userId") or "")
|
||||
org = ((cb.get("org_memberships") or [{}])[0].get("org") or {})
|
||||
result.organization_id = str(org.get("id") or cb.get("selectedOrgId") or "")
|
||||
result.organization_name = str(org.get("name") or "")
|
||||
steps["callback"] = {
|
||||
"ok": True,
|
||||
"user_id": result.user_id,
|
||||
"organization_id": result.organization_id,
|
||||
}
|
||||
|
||||
emit("create_api_key")
|
||||
key = create_api_key(sess, api_key_name)
|
||||
result.api_key = str(key.get("api_key") or "").strip()
|
||||
result.api_key_id = str(key.get("id") or "")
|
||||
steps["api_key"] = {"ok": True, "api_key_id": result.api_key_id}
|
||||
if not result.api_key:
|
||||
raise TypesafeRegisterError(
|
||||
"missing api_key",
|
||||
kind="token",
|
||||
step="api_key",
|
||||
steps=steps,
|
||||
)
|
||||
result.ok = True
|
||||
result.steps = steps
|
||||
return result
|
||||
except TypesafeRegisterError as exc:
|
||||
if not exc.steps:
|
||||
exc.steps = steps
|
||||
result.error = str(exc)
|
||||
result.error_kind = exc.kind
|
||||
result.fail_step = exc.step
|
||||
result.steps = exc.steps or steps
|
||||
raise
|
||||
except MailMissError as exc:
|
||||
wrapped = TypesafeRegisterError(
|
||||
str(exc) or "magic link timeout",
|
||||
kind="mail_miss",
|
||||
step="wait_magic_link",
|
||||
steps=steps,
|
||||
)
|
||||
wrapped.__cause__ = exc
|
||||
raise wrapped from exc
|
||||
except Exception as exc:
|
||||
raise TypesafeRegisterError(
|
||||
f"unexpected: {exc}",
|
||||
kind="provider",
|
||||
step=result.fail_step or "register_one",
|
||||
steps=steps,
|
||||
) from exc
|
||||
|
||||
|
||||
def _get(session: Any, url: str, **kwargs: Any) -> tuple[Any | None, str]:
|
||||
from .session import request_with_retry
|
||||
|
||||
return request_with_retry(session, "GET", url, timeout=DEFAULT_TIMEOUT, **kwargs)
|
||||
|
||||
|
||||
def _post(session: Any, url: str, **kwargs: Any) -> tuple[Any | None, str]:
|
||||
from .session import request_with_retry
|
||||
|
||||
return request_with_retry(session, "POST", url, timeout=DEFAULT_TIMEOUT, **kwargs)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""HTTP session for typesafe.ai console (ECDH prime256v1 + requests)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ssl
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter, Retry
|
||||
|
||||
from .constants import COMMON_HEADERS, DEFAULT_TIMEOUT, TLS_ECDH_CURVE
|
||||
|
||||
|
||||
class TlsAdapter(HTTPAdapter):
|
||||
"""Pin an SSLContext so ECDH stays on prime256v1 (original script)."""
|
||||
|
||||
def __init__(self, ctx: ssl.SSLContext, **kw: Any) -> None:
|
||||
self._ctx = ctx
|
||||
super().__init__(**kw)
|
||||
|
||||
def init_poolmanager(self, *a: Any, **kw: Any) -> Any:
|
||||
kw["ssl_context"] = self._ctx
|
||||
return super().init_poolmanager(*a, **kw)
|
||||
|
||||
def proxy_manager_for(self, proxy: str, **kw: Any) -> Any:
|
||||
kw["ssl_context"] = self._ctx
|
||||
return super().proxy_manager_for(proxy, **kw)
|
||||
|
||||
|
||||
def create_session(proxy: str = "") -> requests.Session:
|
||||
"""Build a requests Session with the original script's ECDH pin."""
|
||||
ctx = ssl.create_default_context()
|
||||
try:
|
||||
ctx.set_ecdh_curve(TLS_ECDH_CURVE)
|
||||
except Exception:
|
||||
pass
|
||||
session = requests.Session()
|
||||
retry = Retry(total=2, backoff_factor=1, status_forcelist=(502, 503, 504))
|
||||
session.mount("https://", TlsAdapter(ctx, max_retries=retry))
|
||||
session.headers.update(COMMON_HEADERS)
|
||||
proxy = (proxy or "").strip()
|
||||
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 response_json(resp: Any) -> dict:
|
||||
if resp is None:
|
||||
return {}
|
||||
try:
|
||||
data = resp.json()
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env bash
|
||||
# typesafe.ai / jev console register runner (in-process via register_core).
|
||||
# Usage:
|
||||
# ./providers/typesafe/run-register.sh [count]
|
||||
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:-${TYPESAFE_EGRESS:-}}}"
|
||||
export TYPESAFE_PROXY="${TYPESAFE_PROXY:-${CHATGPT_PROXY:-${MIMO_PROXY:-}}}"
|
||||
# Magic-link needs a full mail body. tinyhost is the default; OTP-only
|
||||
# wrappers (cloudflare/gmail) cannot extract the Stytch URL.
|
||||
export TYPESAFE_EMAIL_SOURCE="${TYPESAFE_EMAIL_SOURCE:-tinyhost}"
|
||||
export TYPESAFE_EMAIL_DOMAIN="${TYPESAFE_EMAIL_DOMAIN:-${EMAIL_DOMAIN:-}}"
|
||||
export TYPESAFE_PROXY_LIST="${TYPESAFE_PROXY_LIST:-${PROXY_LIST:-}}"
|
||||
export TYPESAFE_PROXY_ROTATE_MODE="${TYPESAFE_PROXY_ROTATE_MODE:-${PROXY_ROTATE_MODE:-}}"
|
||||
export TYPESAFE_PROXY_ROTATE_EVERY="${TYPESAFE_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="${TYPESAFE_SINK:-$ROOT/providers/typesafe/output/pipeline.jsonl}"
|
||||
mkdir -p "$(dirname "$SINK")"
|
||||
|
||||
echo "[typesafe] COUNT=$COUNT egress=${REGISTER_EGRESS:-auto} proxy=${TYPESAFE_PROXY:-'(from egress)'} email_source=$TYPESAFE_EMAIL_SOURCE" >&2
|
||||
|
||||
ARGS=(
|
||||
-m register_core run
|
||||
-p typesafe
|
||||
-n "$COUNT"
|
||||
--email-source "${TYPESAFE_EMAIL_SOURCE}"
|
||||
--sink "$SINK"
|
||||
--timeout "${TYPESAFE_TIMEOUT:-900}"
|
||||
)
|
||||
if [[ -n "${REGISTER_EGRESS}" ]]; then
|
||||
ARGS+=(--egress "${REGISTER_EGRESS}")
|
||||
fi
|
||||
if [[ -n "${TYPESAFE_PROXY}" ]]; then
|
||||
ARGS+=(--proxy "${TYPESAFE_PROXY}")
|
||||
fi
|
||||
if [[ -n "${TYPESAFE_PROXY_LIST}" ]]; then
|
||||
ARGS+=(--proxy-list "${TYPESAFE_PROXY_LIST}")
|
||||
fi
|
||||
if [[ -n "${TYPESAFE_PROXY_ROTATE_MODE}" ]]; then
|
||||
ARGS+=(--proxy-rotate "${TYPESAFE_PROXY_ROTATE_MODE}")
|
||||
fi
|
||||
if [[ -n "${TYPESAFE_PROXY_ROTATE_EVERY}" ]]; then
|
||||
ARGS+=(--proxy-rotate-every "${TYPESAFE_PROXY_ROTATE_EVERY}")
|
||||
fi
|
||||
|
||||
exec "$PY" "${ARGS[@]}"
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env bash
|
||||
# typesafe.ai smoke.
|
||||
#
|
||||
# Default: connectivity only (tinyhost + console login parse). No mailbox.
|
||||
# Live n=1: TYPESAFE_SMOKE_LIVE=1 — COUNT=1, no CPA inject, this-run json only.
|
||||
# Never treat accounts.jsonl tail as success.
|
||||
set -euo pipefail
|
||||
|
||||
PROVIDER_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
ROOT="$(cd "$PROVIDER_DIR/../.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy || true
|
||||
export CPA_EXPORT_ENABLED=false
|
||||
export CPA_REMOTE_INJECT=false
|
||||
export CPA_PROBE_CHAT=false
|
||||
export COUNT=1
|
||||
|
||||
if [[ -x "$ROOT/.venv/bin/python" ]]; then
|
||||
PY="$ROOT/.venv/bin/python"
|
||||
else
|
||||
PY="${PYTHON:-python3}"
|
||||
fi
|
||||
|
||||
echo "=== tinyhost ==="
|
||||
curl -sS --max-time 20 -o /dev/null -w "tinyhost=%{http_code} time=%{time_total}\n" \
|
||||
https://tinyhost.shop || {
|
||||
echo "tinyhost unreachable" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
echo "=== console probe (no mailbox) ==="
|
||||
"$PY" - <<'PY'
|
||||
from providers.typesafe.protocol.flow import probe_console
|
||||
|
||||
info = probe_console(proxy="http://127.0.0.1:7897")
|
||||
print(
|
||||
"console_probe",
|
||||
"status=" + str(info.get("status")),
|
||||
"index=" + str(info.get("index")),
|
||||
"dpl=" + str(info.get("deployment_id") or "")[:12],
|
||||
)
|
||||
PY
|
||||
|
||||
if [[ "${TYPESAFE_SMOKE_LIVE:-0}" != "1" ]]; then
|
||||
echo "SMOKE_OK (probe only; set TYPESAFE_SMOKE_LIVE=1 for n=1 register)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "=== live n=1 (this-run api_key only) ==="
|
||||
mkdir -p logs providers/typesafe/output
|
||||
TS=$(date +%Y%m%d_%H%M%S)
|
||||
LOG="logs/typesafe_smoke_${TS}.log"
|
||||
BEFORE=$("$PY" - <<'PY'
|
||||
from pathlib import Path
|
||||
p = Path("providers/typesafe/output")
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
print(max((f.stat().st_mtime for f in p.glob("typesafe-*.json")), default=0))
|
||||
PY
|
||||
)
|
||||
|
||||
set +e
|
||||
./register.sh typesafe 1 >"$LOG" 2>&1
|
||||
RC=$?
|
||||
set -e
|
||||
echo "register_rc=$RC log=$LOG"
|
||||
|
||||
"$PY" - "$RC" "$LOG" "$BEFORE" <<'PY'
|
||||
import json, sys
|
||||
from pathlib import Path
|
||||
|
||||
rc = int(sys.argv[1])
|
||||
log = Path(sys.argv[2]).read_text(errors="replace")
|
||||
before = float(sys.argv[3])
|
||||
out = Path("providers/typesafe/output")
|
||||
fresh = [
|
||||
p for p in out.glob("typesafe-*.json")
|
||||
if p.stat().st_mtime >= before - 1
|
||||
]
|
||||
contract = None
|
||||
head, sep, tail = log.rpartition("CONTRACT_EXIT:")
|
||||
if sep:
|
||||
first = tail.strip().splitlines()[0].strip() if tail.strip() else ""
|
||||
try:
|
||||
contract = int(first)
|
||||
except ValueError:
|
||||
contract = None
|
||||
summary = None
|
||||
decoder = json.JSONDecoder()
|
||||
scan = head
|
||||
pos = 0
|
||||
while pos < len(scan):
|
||||
brace = scan.find("{", pos)
|
||||
if brace < 0:
|
||||
break
|
||||
try:
|
||||
obj, end = decoder.raw_decode(scan, brace)
|
||||
except json.JSONDecodeError:
|
||||
pos = brace + 1
|
||||
continue
|
||||
pos = end
|
||||
if isinstance(obj, dict) and "results" in obj and "ok" in obj:
|
||||
summary = obj
|
||||
|
||||
ok = bool(summary and int(summary.get("ok") or 0) == 1)
|
||||
kind = ""
|
||||
email = ""
|
||||
auth = None
|
||||
if summary and summary.get("results"):
|
||||
r0 = summary["results"][0]
|
||||
kind = str(r0.get("secret_kind") or "")
|
||||
email = str(r0.get("email") or "")
|
||||
if fresh:
|
||||
auth = json.loads(fresh[-1].read_text(encoding="utf-8"))
|
||||
|
||||
# Success = this-run secret_kind + new 0600 json. accounts.jsonl is ignored.
|
||||
live_ok = (
|
||||
rc == 0
|
||||
and contract == 0
|
||||
and ok
|
||||
and kind == "api_key"
|
||||
and auth is not None
|
||||
and bool(auth.get("ok"))
|
||||
and bool(str(auth.get("api_key") or "").strip())
|
||||
and (not email or auth.get("email") == email)
|
||||
)
|
||||
print(json.dumps({
|
||||
"live_ok": live_ok,
|
||||
"rc": rc,
|
||||
"contract_exit": contract,
|
||||
"secret_kind": kind,
|
||||
"email": email,
|
||||
"fresh_json": str(fresh[-1]) if fresh else "",
|
||||
"accounts_jsonl_ignored": True,
|
||||
}, ensure_ascii=False))
|
||||
if not live_ok:
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
echo SMOKE_OK
|
||||
Reference in New Issue
Block a user