recovered from aaronjaworski710
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user