dsh-reverse-plugin 0.3.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/package.json +3 -3
- package/preset/reverse.patch.yml +5 -5
- package/skills/android/adb-install/SKILL.md +50 -0
- package/skills/android/adb-install/agents/openai.yaml +4 -0
- package/skills/android/adb-install/references/linux.md +35 -0
- package/skills/android/adb-install/references/macos.md +67 -0
- package/skills/android/adb-install/references/sources.md +73 -0
- package/skills/android/adb-install/references/windows.md +73 -0
- package/skills/android/adb-install/scripts/list_downloads.py +105 -0
- package/skills/android/android-hook/SKILL.md +69 -0
- package/skills/android/android-hook/agents/openai.yaml +4 -0
- package/skills/android/android-hook/references/cli-and-frida-trace.md +59 -0
- package/skills/android/android-hook/references/frida-16-to-17.md +39 -0
- package/skills/android/android-hook/references/native-and-cmodule-api.md +85 -0
- package/skills/android/android-hook/references/process-and-memory-api.md +135 -0
- package/skills/android/android-hook/references/script-index.md +86 -0
- package/skills/android/android-hook/scripts/01-crypto/crypto-auto-dump.js +181 -0
- package/skills/android/android-hook/scripts/01-crypto/hook-base64.js +15 -0
- package/skills/android/android-hook/scripts/01-crypto/hook-cipher.js +37 -0
- package/skills/android/android-hook/scripts/02-network-ssl/bypass-conscrypt-pinning.js +26 -0
- package/skills/android/android-hook/scripts/02-network-ssl/bypass-ssl-pinning.js +54 -0
- package/skills/android/android-hook/scripts/02-network-ssl/bypass-vpn-proxy.js +39 -0
- package/skills/android/android-hook/scripts/02-network-ssl/dump-client-cert-p12.js +55 -0
- package/skills/android/android-hook/scripts/02-network-ssl/hook-url-okhttp.js +29 -0
- package/skills/android/android-hook/scripts/02-network-ssl/hook-webview.js +35 -0
- package/skills/android/android-hook/scripts/03-java-trace/activity-control.js +36 -0
- package/skills/android/android-hook/scripts/03-java-trace/art-method-spec.js +110 -0
- package/skills/android/android-hook/scripts/03-java-trace/hook-json.js +37 -0
- package/skills/android/android-hook/scripts/03-java-trace/hook-map.js +39 -0
- package/skills/android/android-hook/scripts/03-java-trace/hook-packed-classloader.js +29 -0
- package/skills/android/android-hook/scripts/03-java-trace/hook-storage.js +66 -0
- package/skills/android/android-hook/scripts/03-java-trace/hook-string.js +57 -0
- package/skills/android/android-hook/scripts/03-java-trace/hook-ui-log.js +19 -0
- package/skills/android/android-hook/scripts/03-java-trace/java-inspect-utils.js +81 -0
- package/skills/android/android-hook/scripts/03-java-trace/register-java-class.js +31 -0
- package/skills/android/android-hook/scripts/04-native-hook/enum-modules-imports.js +37 -0
- package/skills/android/android-hook/scripts/04-native-hook/hook-dlopen.js +60 -0
- package/skills/android/android-hook/scripts/04-native-hook/hook-dlsym.js +25 -0
- package/skills/android/android-hook/scripts/04-native-hook/hook-init-array.js +76 -0
- package/skills/android/android-hook/scripts/04-native-hook/hook-jni-newstringutf.js +38 -0
- package/skills/android/android-hook/scripts/04-native-hook/hook-jni-registernatives.js +43 -0
- package/skills/android/android-hook/scripts/04-native-hook/hook-libc-io-proc.js +48 -0
- package/skills/android/android-hook/scripts/04-native-hook/hook-mem-str.js +87 -0
- package/skills/android/android-hook/scripts/04-native-hook/hook-pthread.js +69 -0
- package/skills/android/android-hook/scripts/04-native-hook/wait-for-module.js +24 -0
- package/skills/android/android-hook/scripts/05-anti-frida/bypass-strstr-anti-frida.js +38 -0
- package/skills/android/android-hook/scripts/05-anti-frida/patch-memfd-frida-str.js +66 -0
- package/skills/android/android-hook/scripts/05-anti-frida/read-proc-maps.js +44 -0
- package/skills/android/android-hook/scripts/05-anti-frida/strip-rwxp.js +43 -0
- package/skills/android/android-hook/scripts/06-unpack-dump/dump-dex-defineclass.js +104 -0
- package/skills/android/android-hook/scripts/06-unpack-dump/load-dex.js +19 -0
- package/skills/android/android-hook/scripts/07-lowlevel-trace/arm64-patch-code.js +40 -0
- package/skills/android/android-hook/scripts/07-lowlevel-trace/got-hook.js +213 -0
- package/skills/android/android-hook/scripts/07-lowlevel-trace/stalker-cmodule-events.js +69 -0
- package/skills/android/android-hook/scripts/07-lowlevel-trace/stalker-trace.js +107 -0
- package/skills/android/android-hook/scripts/07-lowlevel-trace/yahfa-loader.mjs +292 -0
- package/skills/android/android-reverse/SKILL.md +73 -0
- package/skills/android/android-reverse/agents/openai.yaml +4 -0
- package/skills/android/android-reverse/references/developer-options.md +29 -0
- package/skills/android/android-root/SKILL.md +65 -0
- package/skills/android/android-root/agents/openai.yaml +4 -0
- package/skills/android/android-root/references/apatch.md +128 -0
- package/skills/android/android-root/references/kernelsu.md +134 -0
- package/skills/android/android-root/references/post-root-apps.md +31 -0
- package/skills/android/android-root/references/preflight-and-fastboot.md +208 -0
- package/skills/android/frida-install/SKILL.md +54 -0
- package/skills/android/frida-install/agents/openai.yaml +4 -0
- package/skills/android/frida-install/references/install-and-verify.md +126 -0
- package/skills/android/frida-install/references/rusda-releases.md +55 -0
- package/skills/android/reqable-capture/SKILL.md +70 -0
- package/skills/android/reqable-capture/agents/openai.yaml +4 -0
- package/skills/android/reqable-capture/references/capture-troubleshooting.md +56 -0
- package/skills/android/reqable-capture/references/cli-reference.md +110 -0
- package/skills/android/reqable-capture/scripts/reqable_cli.py +849 -0
- package/skills/android/reqable-install/SKILL.md +65 -0
- package/skills/android/reqable-install/agents/openai.yaml +4 -0
- package/skills/android/reqable-install/references/install-and-cert.md +96 -0
- package/skills/android/reqable-install/references/proxy-and-verify.md +63 -0
|
@@ -0,0 +1,849 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
@purpose 零第三方依赖的 Reqable 官方本地 HTTP API 与安卓零人工抓包 CLI,支持一键打通/清理真机抓包通道(自动拉起、对时、Root 注入系统 CA、adb reverse + 代理)及按需查包、筛包、导出 cURL,避免常驻 MCP 占用模型上下文。
|
|
4
|
+
@usage python3 reqable_cli.py <config|status|tabs|android-status|android-up|android-down|live|proxy|filter|list|get|curl|compose|raw> [options]
|
|
5
|
+
@customize 凭据默认保存于 ~/.config/ai-reverse-resources/reqable.json(权限 0600,仓库外),也可通过 --token / REQABLE_TOKEN 覆盖。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import base64
|
|
12
|
+
import datetime
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import platform
|
|
16
|
+
import shutil
|
|
17
|
+
import stat
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import time
|
|
21
|
+
import urllib.error
|
|
22
|
+
import urllib.request
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
DEFAULT_HOST = "127.0.0.1"
|
|
28
|
+
DEFAULT_PORT = 9000
|
|
29
|
+
DEFAULT_TIMEOUT = 15
|
|
30
|
+
LOCAL_CONFIG_PATH = Path.home() / ".config" / "ai-reverse-resources" / "reqable.json"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def reqable_data_dir() -> Path | None:
|
|
34
|
+
system = platform.system()
|
|
35
|
+
if system == "Darwin":
|
|
36
|
+
return Path.home() / "Library" / "Application Support" / "com.reqable.macosx"
|
|
37
|
+
if system == "Windows":
|
|
38
|
+
appdata = os.environ.get("APPDATA")
|
|
39
|
+
base = Path(appdata) if appdata else Path.home() / "AppData" / "Roaming"
|
|
40
|
+
return base / "Reqable"
|
|
41
|
+
if system == "Linux":
|
|
42
|
+
return Path.home() / ".local" / "share" / "com.reqable.linux"
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def reqable_capture_config_path() -> Path | None:
|
|
47
|
+
base = reqable_data_dir()
|
|
48
|
+
return base / "config" / "capture_config" if base else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def reqable_ca_cert_path(override: str | None = None) -> Path | None:
|
|
52
|
+
if override:
|
|
53
|
+
return Path(override).expanduser()
|
|
54
|
+
base = reqable_data_dir()
|
|
55
|
+
return base / "certificate" / "reqable-ca.crt" if base else None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def load_json_file(path: Path) -> dict[str, Any]:
|
|
59
|
+
if not path.is_file():
|
|
60
|
+
return {}
|
|
61
|
+
try:
|
|
62
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
63
|
+
return data if isinstance(data, dict) else {}
|
|
64
|
+
except (OSError, json.JSONDecodeError):
|
|
65
|
+
return {}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def resolve_connection(args: argparse.Namespace) -> tuple[str, int, str]:
|
|
69
|
+
local_cfg = load_json_file(LOCAL_CONFIG_PATH)
|
|
70
|
+
|
|
71
|
+
host = (
|
|
72
|
+
getattr(args, "host", None)
|
|
73
|
+
or os.environ.get("REQABLE_HOST")
|
|
74
|
+
or local_cfg.get("host")
|
|
75
|
+
or DEFAULT_HOST
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
port_val: Any = getattr(args, "port", None) or os.environ.get("REQABLE_PORT") or local_cfg.get("port")
|
|
79
|
+
if port_val is None:
|
|
80
|
+
cap_path = reqable_capture_config_path()
|
|
81
|
+
if cap_path:
|
|
82
|
+
port_val = load_json_file(cap_path).get("proxyPort")
|
|
83
|
+
port = int(port_val) if port_val else DEFAULT_PORT
|
|
84
|
+
|
|
85
|
+
token = (
|
|
86
|
+
getattr(args, "token", None)
|
|
87
|
+
or os.environ.get("REQABLE_TOKEN")
|
|
88
|
+
or os.environ.get("ACCESS_TOKEN")
|
|
89
|
+
or local_cfg.get("token")
|
|
90
|
+
or ""
|
|
91
|
+
)
|
|
92
|
+
return str(host), port, str(token)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def mask_token(token: str) -> str:
|
|
96
|
+
if not token:
|
|
97
|
+
return "<not-set>"
|
|
98
|
+
if len(token) <= 8:
|
|
99
|
+
return "*" * len(token)
|
|
100
|
+
return f"{token[:4]}...{token[-4:]} (len={len(token)})"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class ReqableClient:
|
|
104
|
+
def __init__(self, host: str, port: int, token: str, timeout: int = DEFAULT_TIMEOUT) -> None:
|
|
105
|
+
self.host = host
|
|
106
|
+
self.port = port
|
|
107
|
+
self.token = token
|
|
108
|
+
self.timeout = timeout
|
|
109
|
+
|
|
110
|
+
def request(self, method: str, route: str, payload: dict[str, Any] | None = None) -> Any:
|
|
111
|
+
if not route.startswith("/"):
|
|
112
|
+
route = "/" + route
|
|
113
|
+
url = f"http://{self.host}:{self.port}{route}"
|
|
114
|
+
headers = {"User-Agent": "ai-reverse-reqable-cli/1.0"}
|
|
115
|
+
if self.token:
|
|
116
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
117
|
+
data: bytes | None = None
|
|
118
|
+
if payload is not None:
|
|
119
|
+
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
120
|
+
headers["Content-Type"] = "application/json"
|
|
121
|
+
|
|
122
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method.upper())
|
|
123
|
+
# Bypass any host HTTP_PROXY env vars when talking to local Reqable API.
|
|
124
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
125
|
+
try:
|
|
126
|
+
with opener.open(req, timeout=self.timeout) as resp:
|
|
127
|
+
raw = resp.read().decode("utf-8", errors="replace")
|
|
128
|
+
except urllib.error.HTTPError as err:
|
|
129
|
+
err_body = err.read().decode("utf-8", errors="replace").strip()
|
|
130
|
+
hint = ""
|
|
131
|
+
if err.code == 401:
|
|
132
|
+
hint = (
|
|
133
|
+
" (提示:请在 Reqable 桌面端工具栏 MCP/API 设置中开启本地 API 并复制 Access Token,"
|
|
134
|
+
"然后运行 `reqable_cli.py config set --token <TOKEN>`)"
|
|
135
|
+
)
|
|
136
|
+
elif err.code == 403:
|
|
137
|
+
hint = " (提示:该写操作可能需要 Reqable Premium 权限或未开启对应 API 开关)"
|
|
138
|
+
raise SystemExit(f"HTTP {err.code} {method} {route}: {err_body}{hint}") from None
|
|
139
|
+
except (urllib.error.URLError, TimeoutError, OSError) as err:
|
|
140
|
+
raise SystemExit(
|
|
141
|
+
f"无法连接 Reqable 本地 API ({self.host}:{self.port}): {err}\n"
|
|
142
|
+
"请确认 Reqable Desktop (>=3.2.0) 已启动且监听端口正确。"
|
|
143
|
+
) from None
|
|
144
|
+
|
|
145
|
+
if not raw.strip():
|
|
146
|
+
return {"ok": True}
|
|
147
|
+
try:
|
|
148
|
+
return json.loads(raw)
|
|
149
|
+
except json.JSONDecodeError:
|
|
150
|
+
return raw
|
|
151
|
+
|
|
152
|
+
def resolve_tab_id(self, tab_arg: str | None) -> str:
|
|
153
|
+
if tab_arg:
|
|
154
|
+
return tab_arg
|
|
155
|
+
tabs = self.request("GET", "/tab/list")
|
|
156
|
+
if isinstance(tabs, dict):
|
|
157
|
+
for tab in tabs.get("tabs", []):
|
|
158
|
+
if tab.get("type") == "captureLive" and tab.get("id"):
|
|
159
|
+
return str(tab["id"])
|
|
160
|
+
if tabs.get("tabs"):
|
|
161
|
+
return str(tabs["tabs"][0]["id"])
|
|
162
|
+
return "live"
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def build_filters(args: argparse.Namespace) -> list[dict[str, Any]]:
|
|
166
|
+
filters: list[dict[str, Any]] = []
|
|
167
|
+
if getattr(args, "keyword", None):
|
|
168
|
+
f: dict[str, Any] = {"type": "keyword", "pattern": args.keyword}
|
|
169
|
+
if args.case_sensitive:
|
|
170
|
+
f["caseSensitive"] = True
|
|
171
|
+
if args.regex:
|
|
172
|
+
f["regex"] = True
|
|
173
|
+
filters.append(f)
|
|
174
|
+
if getattr(args, "host_filter", None):
|
|
175
|
+
filters.append({"type": "host", "hosts": args.host_filter})
|
|
176
|
+
if getattr(args, "url_filter", None):
|
|
177
|
+
filters.append({"type": "url", "urls": args.url_filter})
|
|
178
|
+
if getattr(args, "ip_filter", None):
|
|
179
|
+
filters.append({"type": "ip", "ips": args.ip_filter})
|
|
180
|
+
if getattr(args, "method_filter", None):
|
|
181
|
+
filters.append({"type": "method", "methods": [m.upper() for m in args.method_filter]})
|
|
182
|
+
if getattr(args, "code_filter", None):
|
|
183
|
+
filters.append({"type": "code", "codes": args.code_filter})
|
|
184
|
+
if any(getattr(args, k, None) is not None for k in ("app_name", "app_id", "app_pid")):
|
|
185
|
+
app_f: dict[str, Any] = {"type": "application"}
|
|
186
|
+
if args.app_name is not None:
|
|
187
|
+
app_f["name"] = args.app_name
|
|
188
|
+
if args.app_id is not None:
|
|
189
|
+
app_f["id"] = args.app_id
|
|
190
|
+
if args.app_pid is not None:
|
|
191
|
+
app_f["pid"] = args.app_pid
|
|
192
|
+
filters.append(app_f)
|
|
193
|
+
return filters
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def extract_ids(result: Any) -> list[int]:
|
|
197
|
+
if isinstance(result, list):
|
|
198
|
+
return [int(x) for x in result]
|
|
199
|
+
if isinstance(result, dict) and isinstance(result.get("items"), list):
|
|
200
|
+
return [int(x) for x in result["items"]]
|
|
201
|
+
return []
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def body_size(body: Any) -> int:
|
|
205
|
+
if not isinstance(body, dict):
|
|
206
|
+
return 0
|
|
207
|
+
text = body.get("text")
|
|
208
|
+
if not isinstance(text, str):
|
|
209
|
+
return 0
|
|
210
|
+
if body.get("encoding") == "file":
|
|
211
|
+
p = Path(text)
|
|
212
|
+
return p.stat().st_size if p.is_file() else 0
|
|
213
|
+
return len(text.encode("utf-8", errors="replace"))
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def save_body(body: Any, dest: Path) -> str:
|
|
217
|
+
if not isinstance(body, dict):
|
|
218
|
+
raise SystemExit("目标记录没有可保存的 Body。")
|
|
219
|
+
enc = body.get("encoding", "utf8")
|
|
220
|
+
text = body.get("text", "")
|
|
221
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
222
|
+
if enc == "base64":
|
|
223
|
+
dest.write_bytes(base64.b64decode(text))
|
|
224
|
+
elif enc == "file":
|
|
225
|
+
src = Path(text)
|
|
226
|
+
if not src.is_file():
|
|
227
|
+
raise SystemExit(f"Reqable Body 文件不存在: {src}")
|
|
228
|
+
dest.write_bytes(src.read_bytes())
|
|
229
|
+
else:
|
|
230
|
+
dest.write_text(str(text), encoding="utf-8")
|
|
231
|
+
return str(dest.resolve())
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def format_body_preview(body: Any, max_chars: int) -> dict[str, Any] | None:
|
|
235
|
+
if not isinstance(body, dict):
|
|
236
|
+
return None
|
|
237
|
+
enc = body.get("encoding", "utf8")
|
|
238
|
+
text = str(body.get("text", ""))
|
|
239
|
+
preview: dict[str, Any] = {"encoding": enc}
|
|
240
|
+
if body.get("mime"):
|
|
241
|
+
preview["mime"] = body["mime"]
|
|
242
|
+
if enc == "file":
|
|
243
|
+
preview["file"] = text
|
|
244
|
+
return preview
|
|
245
|
+
preview["length"] = len(text)
|
|
246
|
+
if max_chars > 0 and len(text) > max_chars:
|
|
247
|
+
preview["text"] = text[:max_chars] + f"\n... [truncated {len(text) - max_chars} chars; use --save-*-body or --full-body]"
|
|
248
|
+
preview["truncated"] = True
|
|
249
|
+
else:
|
|
250
|
+
preview["text"] = text
|
|
251
|
+
preview["truncated"] = False
|
|
252
|
+
return preview
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def cmd_config(args: argparse.Namespace) -> None:
|
|
256
|
+
if args.config_action == "set":
|
|
257
|
+
cfg = load_json_file(LOCAL_CONFIG_PATH)
|
|
258
|
+
if args.set_host:
|
|
259
|
+
cfg["host"] = args.set_host
|
|
260
|
+
elif "host" not in cfg:
|
|
261
|
+
cfg["host"] = DEFAULT_HOST
|
|
262
|
+
if args.set_port:
|
|
263
|
+
cfg["port"] = args.set_port
|
|
264
|
+
elif "port" not in cfg:
|
|
265
|
+
cfg["port"] = DEFAULT_PORT
|
|
266
|
+
if args.set_token is not None:
|
|
267
|
+
cfg["token"] = args.set_token
|
|
268
|
+
LOCAL_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
269
|
+
try:
|
|
270
|
+
os.chmod(LOCAL_CONFIG_PATH.parent, 0o700)
|
|
271
|
+
except OSError:
|
|
272
|
+
pass
|
|
273
|
+
LOCAL_CONFIG_PATH.write_text(json.dumps(cfg, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
274
|
+
try:
|
|
275
|
+
os.chmod(LOCAL_CONFIG_PATH, stat.S_IRUSR | stat.S_IWUSR)
|
|
276
|
+
except OSError:
|
|
277
|
+
pass
|
|
278
|
+
print(
|
|
279
|
+
json.dumps(
|
|
280
|
+
{
|
|
281
|
+
"saved": str(LOCAL_CONFIG_PATH),
|
|
282
|
+
"host": cfg.get("host"),
|
|
283
|
+
"port": cfg.get("port"),
|
|
284
|
+
"token": mask_token(str(cfg.get("token", ""))),
|
|
285
|
+
},
|
|
286
|
+
indent=2,
|
|
287
|
+
ensure_ascii=False,
|
|
288
|
+
)
|
|
289
|
+
)
|
|
290
|
+
return
|
|
291
|
+
|
|
292
|
+
host, port, token = resolve_connection(args)
|
|
293
|
+
print(
|
|
294
|
+
json.dumps(
|
|
295
|
+
{
|
|
296
|
+
"config_file": str(LOCAL_CONFIG_PATH),
|
|
297
|
+
"config_file_exists": LOCAL_CONFIG_PATH.is_file(),
|
|
298
|
+
"resolved_host": host,
|
|
299
|
+
"resolved_port": port,
|
|
300
|
+
"resolved_token": mask_token(token),
|
|
301
|
+
},
|
|
302
|
+
indent=2,
|
|
303
|
+
ensure_ascii=False,
|
|
304
|
+
)
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def cmd_status(client: ReqableClient) -> None:
|
|
309
|
+
status = client.request("GET", "/capture/live/status")
|
|
310
|
+
tabs = client.request("GET", "/tab/list")
|
|
311
|
+
print(
|
|
312
|
+
json.dumps(
|
|
313
|
+
{
|
|
314
|
+
"endpoint": f"http://{client.host}:{client.port}",
|
|
315
|
+
"live_capture": status,
|
|
316
|
+
"tabs": tabs.get("tabs", []) if isinstance(tabs, dict) else tabs,
|
|
317
|
+
},
|
|
318
|
+
indent=2,
|
|
319
|
+
ensure_ascii=False,
|
|
320
|
+
)
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def cmd_list(client: ReqableClient, args: argparse.Namespace) -> None:
|
|
325
|
+
tab_id = client.resolve_tab_id(args.tab)
|
|
326
|
+
ids = extract_ids(client.request("POST", "/capture/record/filter", {"tabId": tab_id, "filters": build_filters(args)}))
|
|
327
|
+
total = len(ids)
|
|
328
|
+
selected = ids[-args.limit :] if args.limit > 0 else ids
|
|
329
|
+
rows = []
|
|
330
|
+
for rid in reversed(selected):
|
|
331
|
+
rec = client.request("POST", "/capture/record/get", {"tabId": tab_id, "id": rid})
|
|
332
|
+
if not isinstance(rec, dict):
|
|
333
|
+
continue
|
|
334
|
+
req = rec.get("request") or {}
|
|
335
|
+
resp = rec.get("response") or {}
|
|
336
|
+
app = rec.get("application") or {}
|
|
337
|
+
rows.append(
|
|
338
|
+
{
|
|
339
|
+
"id": rec.get("id"),
|
|
340
|
+
"protocol": rec.get("protocol"),
|
|
341
|
+
"method": req.get("method"),
|
|
342
|
+
"code": resp.get("code"),
|
|
343
|
+
"url": rec.get("url"),
|
|
344
|
+
"app": app.get("id") or app.get("name"),
|
|
345
|
+
"req_bytes": body_size(req.get("body")),
|
|
346
|
+
"resp_bytes": body_size(resp.get("body")),
|
|
347
|
+
}
|
|
348
|
+
)
|
|
349
|
+
print(
|
|
350
|
+
json.dumps(
|
|
351
|
+
{"tabId": tab_id, "total_matched": total, "shown": len(rows), "records": rows},
|
|
352
|
+
indent=2,
|
|
353
|
+
ensure_ascii=False,
|
|
354
|
+
)
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def cmd_get(client: ReqableClient, args: argparse.Namespace) -> None:
|
|
359
|
+
tab_id = client.resolve_tab_id(args.tab)
|
|
360
|
+
rec = client.request("POST", "/capture/record/get", {"tabId": tab_id, "id": args.id})
|
|
361
|
+
if args.raw_json or not isinstance(rec, dict):
|
|
362
|
+
print(json.dumps(rec, indent=2, ensure_ascii=False))
|
|
363
|
+
return
|
|
364
|
+
|
|
365
|
+
saved: dict[str, str] = {}
|
|
366
|
+
req = rec.get("request") or {}
|
|
367
|
+
resp = rec.get("response") or {}
|
|
368
|
+
if args.save_req_body:
|
|
369
|
+
saved["request_body"] = save_body(req.get("body"), Path(args.save_req_body))
|
|
370
|
+
if args.save_resp_body:
|
|
371
|
+
saved["response_body"] = save_body(resp.get("body"), Path(args.save_resp_body))
|
|
372
|
+
|
|
373
|
+
max_chars = 0 if args.full_body else args.max_body_chars
|
|
374
|
+
out: dict[str, Any] = {
|
|
375
|
+
"id": rec.get("id"),
|
|
376
|
+
"uid": rec.get("uid"),
|
|
377
|
+
"protocol": rec.get("protocol"),
|
|
378
|
+
"url": rec.get("url"),
|
|
379
|
+
"application": rec.get("application"),
|
|
380
|
+
"connection": rec.get("connection"),
|
|
381
|
+
"request": {
|
|
382
|
+
"method": req.get("method"),
|
|
383
|
+
"path": req.get("path"),
|
|
384
|
+
"protocol": req.get("protocol"),
|
|
385
|
+
"headers": req.get("headers"),
|
|
386
|
+
},
|
|
387
|
+
"response": (
|
|
388
|
+
{
|
|
389
|
+
"code": resp.get("code"),
|
|
390
|
+
"status": resp.get("status"),
|
|
391
|
+
"protocol": resp.get("protocol"),
|
|
392
|
+
"headers": resp.get("headers"),
|
|
393
|
+
}
|
|
394
|
+
if resp
|
|
395
|
+
else None
|
|
396
|
+
),
|
|
397
|
+
}
|
|
398
|
+
if not args.headers_only:
|
|
399
|
+
out["request"]["body"] = format_body_preview(req.get("body"), max_chars)
|
|
400
|
+
if out["response"] is not None:
|
|
401
|
+
out["response"]["body"] = format_body_preview(resp.get("body"), max_chars)
|
|
402
|
+
if rec.get("messages"):
|
|
403
|
+
msgs = rec["messages"]
|
|
404
|
+
out["websocket_messages_total"] = len(msgs)
|
|
405
|
+
out["websocket_messages"] = msgs[-args.ws_limit :] if args.ws_limit > 0 else msgs
|
|
406
|
+
if saved:
|
|
407
|
+
out["saved_files"] = saved
|
|
408
|
+
print(json.dumps(out, indent=2, ensure_ascii=False))
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def run_cmd(cmd: list[str], timeout: int = 20) -> subprocess.CompletedProcess[str]:
|
|
412
|
+
try:
|
|
413
|
+
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
|
|
414
|
+
except FileNotFoundError as exc:
|
|
415
|
+
raise SystemExit(f"找不到必需命令 `{cmd[0]}`: {exc}") from None
|
|
416
|
+
except subprocess.TimeoutExpired:
|
|
417
|
+
raise SystemExit(f"命令执行超时 ({timeout}s): {' '.join(cmd)}") from None
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def resolve_adb_serial(serial_arg: str | None) -> str:
|
|
421
|
+
if not shutil.which("adb"):
|
|
422
|
+
raise SystemExit("未找到 `adb`,请先通过 adb-install 安装并配置 PATH。")
|
|
423
|
+
if serial_arg:
|
|
424
|
+
return serial_arg
|
|
425
|
+
proc = run_cmd(["adb", "devices"])
|
|
426
|
+
if proc.returncode != 0:
|
|
427
|
+
raise SystemExit(f"adb devices 执行失败: {proc.stderr.strip() or proc.stdout.strip()}")
|
|
428
|
+
online: list[str] = []
|
|
429
|
+
for line in proc.stdout.splitlines()[1:]:
|
|
430
|
+
parts = line.strip().split()
|
|
431
|
+
if len(parts) >= 2 and parts[1] == "device":
|
|
432
|
+
online.append(parts[0])
|
|
433
|
+
if not online:
|
|
434
|
+
raise SystemExit("未检测到在线 ADB 设备(请检查 USB 连接与 USB 调试授权)。")
|
|
435
|
+
if len(online) > 1:
|
|
436
|
+
raise SystemExit(f"检测到多台在线设备 {online},请使用 `-s <serial>` 指定目标设备。")
|
|
437
|
+
return online[0]
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def adb_run(serial: str, *args: str, timeout: int = 20) -> subprocess.CompletedProcess[str]:
|
|
441
|
+
return run_cmd(["adb", "-s", serial, *args], timeout=timeout)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def compute_ca_hash_name(ca_path: Path) -> str:
|
|
445
|
+
if not ca_path.is_file():
|
|
446
|
+
raise SystemExit(f"未找到 Reqable CA 根证书文件: {ca_path}(请先启动一次 Reqable Desktop 生成证书,或用 --ca-file 指定)")
|
|
447
|
+
if not shutil.which("openssl"):
|
|
448
|
+
raise SystemExit("未找到 `openssl`,无法计算系统 CA 证书主题哈希(<hash>.0)。")
|
|
449
|
+
proc = run_cmd(["openssl", "x509", "-inform", "PEM", "-subject_hash_old", "-noout", "-in", str(ca_path)])
|
|
450
|
+
if proc.returncode != 0 or not proc.stdout.strip():
|
|
451
|
+
raise SystemExit(f"openssl 解析证书哈希失败: {proc.stderr.strip()}")
|
|
452
|
+
return f"{proc.stdout.strip().splitlines()[0]}.0"
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def inspect_android_state(serial: str, port: int, ca_path: Path | None) -> dict[str, Any]:
|
|
456
|
+
release = adb_run(serial, "shell", "getprop ro.build.version.release").stdout.strip()
|
|
457
|
+
sdk_raw = adb_run(serial, "shell", "getprop ro.build.version.sdk").stdout.strip()
|
|
458
|
+
sdk = int(sdk_raw) if sdk_raw.isdigit() else 0
|
|
459
|
+
|
|
460
|
+
root_out = adb_run(serial, "shell", "su -c id").stdout.strip()
|
|
461
|
+
has_root = "uid=0" in root_out
|
|
462
|
+
|
|
463
|
+
host_epoch = int(time.time())
|
|
464
|
+
dev_epoch_raw = adb_run(serial, "shell", "date +%s").stdout.strip()
|
|
465
|
+
device_epoch = int(dev_epoch_raw) if dev_epoch_raw.isdigit() else None
|
|
466
|
+
skew = (device_epoch - host_epoch) if device_epoch is not None else None
|
|
467
|
+
|
|
468
|
+
ca_hash_name: str | None = None
|
|
469
|
+
ca_exists_apex: bool | None = None
|
|
470
|
+
ca_exists_system: bool | None = None
|
|
471
|
+
ca_ready = False
|
|
472
|
+
if ca_path and ca_path.is_file() and shutil.which("openssl"):
|
|
473
|
+
ca_hash_name = compute_ca_hash_name(ca_path)
|
|
474
|
+
sys_chk = adb_run(serial, "shell", f"test -f /system/etc/security/cacerts/{ca_hash_name} && echo YES || echo NO").stdout.strip()
|
|
475
|
+
ca_exists_system = sys_chk == "YES"
|
|
476
|
+
if sdk >= 34:
|
|
477
|
+
apex_chk = adb_run(serial, "shell", f"test -f /apex/com.android.conscrypt/cacerts/{ca_hash_name} && echo YES || echo NO").stdout.strip()
|
|
478
|
+
ca_exists_apex = apex_chk == "YES"
|
|
479
|
+
ca_ready = bool(ca_exists_apex and ca_exists_system)
|
|
480
|
+
else:
|
|
481
|
+
ca_ready = bool(ca_exists_system)
|
|
482
|
+
|
|
483
|
+
rev_out = adb_run(serial, "reverse", "--list").stdout
|
|
484
|
+
reverse_ready = f"tcp:{port} tcp:{port}" in rev_out
|
|
485
|
+
http_proxy = adb_run(serial, "shell", "settings get global http_proxy").stdout.strip()
|
|
486
|
+
|
|
487
|
+
vpn_chk = adb_run(serial, "shell", "ip link show 2>/dev/null | grep -E 'tun[0-9]+:' | head -n 1").stdout.strip()
|
|
488
|
+
active_vpn = bool(vpn_chk)
|
|
489
|
+
|
|
490
|
+
return {
|
|
491
|
+
"serial": serial,
|
|
492
|
+
"android_release": release,
|
|
493
|
+
"android_sdk": sdk,
|
|
494
|
+
"root": has_root,
|
|
495
|
+
"host_epoch": host_epoch,
|
|
496
|
+
"device_epoch": device_epoch,
|
|
497
|
+
"clock_skew_seconds": skew,
|
|
498
|
+
"ca_cert_path": str(ca_path) if ca_path else None,
|
|
499
|
+
"ca_hash_file": ca_hash_name,
|
|
500
|
+
"ca_installed_system": ca_exists_system,
|
|
501
|
+
"ca_installed_apex": ca_exists_apex,
|
|
502
|
+
"ca_ready": ca_ready,
|
|
503
|
+
"reverse_ready": reverse_ready,
|
|
504
|
+
"http_proxy": http_proxy,
|
|
505
|
+
"active_vpn_tun": active_vpn,
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def install_android_ca_tmpfs(serial: str, ca_path: Path, hash_name: str, sdk: int) -> None:
|
|
510
|
+
tmp_remote = f"/data/local/tmp/{hash_name}"
|
|
511
|
+
push_proc = adb_run(serial, "push", str(ca_path), tmp_remote)
|
|
512
|
+
if push_proc.returncode != 0:
|
|
513
|
+
raise SystemExit(f"推送 CA 证书到设备失败: {push_proc.stderr.strip() or push_proc.stdout.strip()}")
|
|
514
|
+
|
|
515
|
+
# Replicates standard Android 7-16 tmpfs + Conscrypt APEX nsenter CA injection (no GUI popup needed).
|
|
516
|
+
remote_script = f"""
|
|
517
|
+
set -e
|
|
518
|
+
CERT_FILE="{tmp_remote}"
|
|
519
|
+
HASH_NAME="{hash_name}"
|
|
520
|
+
STAGE="/data/local/tmp/reqable-cacerts-stage"
|
|
521
|
+
rm -rf "$STAGE"
|
|
522
|
+
mkdir -p "$STAGE"
|
|
523
|
+
if [ "{sdk}" -ge 34 ] && [ -d /apex/com.android.conscrypt/cacerts ]; then
|
|
524
|
+
cp -a /apex/com.android.conscrypt/cacerts/. "$STAGE/"
|
|
525
|
+
else
|
|
526
|
+
cp -a /system/etc/security/cacerts/. "$STAGE/"
|
|
527
|
+
fi
|
|
528
|
+
cp "$CERT_FILE" "$STAGE/$HASH_NAME"
|
|
529
|
+
chown -R 0:0 "$STAGE"
|
|
530
|
+
chmod 644 "$STAGE"/*
|
|
531
|
+
chcon -R u:object_r:system_file:s0 "$STAGE" 2>/dev/null || true
|
|
532
|
+
|
|
533
|
+
if ! grep -q " /system/etc/security/cacerts tmpfs " /proc/mounts; then
|
|
534
|
+
mount -t tmpfs tmpfs /system/etc/security/cacerts
|
|
535
|
+
fi
|
|
536
|
+
cp -a "$STAGE/." /system/etc/security/cacerts/
|
|
537
|
+
chown -R 0:0 /system/etc/security/cacerts
|
|
538
|
+
chmod 755 /system/etc/security/cacerts
|
|
539
|
+
chmod 644 /system/etc/security/cacerts/*
|
|
540
|
+
chcon -R u:object_r:system_file:s0 /system/etc/security/cacerts 2>/dev/null || true
|
|
541
|
+
|
|
542
|
+
if [ "{sdk}" -ge 34 ] && [ -d /apex/com.android.conscrypt/cacerts ]; then
|
|
543
|
+
APEX_DIR="/apex/com.android.conscrypt/cacerts"
|
|
544
|
+
nsenter --mount=/proc/1/ns/mnt -- /bin/mount --bind /system/etc/security/cacerts "$APEX_DIR"
|
|
545
|
+
ZYGOTE_PIDS=$(pidof zygote zygote64 2>/dev/null || true)
|
|
546
|
+
for ZPID in $ZYGOTE_PIDS; do
|
|
547
|
+
nsenter --mount="/proc/$ZPID/ns/mnt" -- /bin/mount --bind /system/etc/security/cacerts "$APEX_DIR" 2>/dev/null || true
|
|
548
|
+
for CPID in $(ps -o PID= --ppid "$ZPID" 2>/dev/null || true); do
|
|
549
|
+
nsenter --mount="/proc/$CPID/ns/mnt" -- /bin/mount --bind /system/etc/security/cacerts "$APEX_DIR" 2>/dev/null || true
|
|
550
|
+
done
|
|
551
|
+
done
|
|
552
|
+
fi
|
|
553
|
+
rm -rf "$STAGE" "$CERT_FILE"
|
|
554
|
+
""".strip()
|
|
555
|
+
|
|
556
|
+
proc = adb_run(serial, "shell", "su", "-c", remote_script, timeout=30)
|
|
557
|
+
if proc.returncode != 0:
|
|
558
|
+
raise SystemExit(f"ADB+Root 自动注入系统 CA 证书失败: {proc.stderr.strip() or proc.stdout.strip()}")
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def probe_reqable_api(client: ReqableClient, auto_launch: bool) -> dict[str, Any]:
|
|
562
|
+
def _try_status() -> dict[str, Any] | None:
|
|
563
|
+
url = f"http://{client.host}:{client.port}/capture/live/status"
|
|
564
|
+
headers = {"User-Agent": "ai-reverse-reqable-cli/1.0"}
|
|
565
|
+
if client.token:
|
|
566
|
+
headers["Authorization"] = f"Bearer {client.token}"
|
|
567
|
+
req = urllib.request.Request(url, headers=headers, method="GET")
|
|
568
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
569
|
+
try:
|
|
570
|
+
with opener.open(req, timeout=3) as resp:
|
|
571
|
+
return json.loads(resp.read().decode("utf-8", errors="replace"))
|
|
572
|
+
except urllib.error.HTTPError as err:
|
|
573
|
+
if err.code == 401:
|
|
574
|
+
raise SystemExit(
|
|
575
|
+
"Reqable 本地 API 返回 401 Unauthorized:请先运行 `reqable_cli.py config set --token <TOKEN>` 配置本地 Token。"
|
|
576
|
+
) from None
|
|
577
|
+
raise SystemExit(f"Reqable 本地 API 异常 HTTP {err.code}") from None
|
|
578
|
+
except (urllib.error.URLError, TimeoutError, OSError):
|
|
579
|
+
return None
|
|
580
|
+
|
|
581
|
+
res = _try_status()
|
|
582
|
+
launched = False
|
|
583
|
+
if res is None and auto_launch and platform.system() == "Darwin":
|
|
584
|
+
run_cmd(["open", "-a", "Reqable"])
|
|
585
|
+
launched = True
|
|
586
|
+
for _ in range(10):
|
|
587
|
+
time.sleep(1)
|
|
588
|
+
res = _try_status()
|
|
589
|
+
if res is not None:
|
|
590
|
+
break
|
|
591
|
+
if res is None:
|
|
592
|
+
raise SystemExit(
|
|
593
|
+
f"无法连接 Reqable 本地 API ({client.host}:{client.port}),请确认 Reqable Desktop (>=3.2.0) 已启动并开启本地 API。"
|
|
594
|
+
)
|
|
595
|
+
return {"launched": launched, "live_capture": res}
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def cmd_android_status(client: ReqableClient, args: argparse.Namespace) -> None:
|
|
599
|
+
serial = resolve_adb_serial(args.serial)
|
|
600
|
+
ca_path = reqable_ca_cert_path(args.ca_file)
|
|
601
|
+
api_info: dict[str, Any]
|
|
602
|
+
try:
|
|
603
|
+
api_info = {"reachable": True, "live_capture": client.request("GET", "/capture/live/status")}
|
|
604
|
+
except SystemExit as exc:
|
|
605
|
+
api_info = {"reachable": False, "error": str(exc)}
|
|
606
|
+
dev = inspect_android_state(serial, client.port, ca_path)
|
|
607
|
+
print(json.dumps({"endpoint": f"http://{client.host}:{client.port}", "reqable_api": api_info, "android": dev}, indent=2, ensure_ascii=False))
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def cmd_android_up(client: ReqableClient, args: argparse.Namespace) -> None:
|
|
611
|
+
actions: list[str] = []
|
|
612
|
+
api_probe = probe_reqable_api(client, auto_launch=not args.no_auto_launch)
|
|
613
|
+
if api_probe["launched"]:
|
|
614
|
+
actions.append("launched_reqable_desktop")
|
|
615
|
+
|
|
616
|
+
live_status = api_probe["live_capture"].get("status") if isinstance(api_probe["live_capture"], dict) else None
|
|
617
|
+
if live_status != "active" and not args.no_live_start:
|
|
618
|
+
client.request("POST", "/capture/live/on")
|
|
619
|
+
live_status = "active"
|
|
620
|
+
actions.append("started_live_capture")
|
|
621
|
+
|
|
622
|
+
serial = resolve_adb_serial(args.serial)
|
|
623
|
+
ca_path = reqable_ca_cert_path(args.ca_file)
|
|
624
|
+
state = inspect_android_state(serial, client.port, ca_path)
|
|
625
|
+
|
|
626
|
+
# 1. Clock sync (prevents SSLHandshakeException: Chain validation failed)
|
|
627
|
+
skew = state["clock_skew_seconds"]
|
|
628
|
+
if skew is not None and abs(skew) > args.max_skew and not args.no_sync_time:
|
|
629
|
+
if not state["root"]:
|
|
630
|
+
raise SystemExit(
|
|
631
|
+
f"检测到真机时钟偏差 {skew} 秒,但设备无 Root 无法自动对齐,请先在手机设置中开启自动校时。"
|
|
632
|
+
)
|
|
633
|
+
utc_str = datetime.datetime.now(datetime.timezone.utc).strftime("%m%d%H%M%Y.%S")
|
|
634
|
+
sync_proc = adb_run(serial, "shell", "su", "-c", f"date -u {utc_str}")
|
|
635
|
+
if sync_proc.returncode != 0:
|
|
636
|
+
raise SystemExit(f"自动同步真机时钟失败: {sync_proc.stderr.strip() or sync_proc.stdout.strip()}")
|
|
637
|
+
actions.append(f"synced_device_clock(was_skew={skew}s)")
|
|
638
|
+
|
|
639
|
+
# 2. System CA auto-injection via ADB+Root tmpfs+nsenter if missing
|
|
640
|
+
if not state["ca_ready"] and not args.no_install_ca:
|
|
641
|
+
if not state["root"]:
|
|
642
|
+
raise SystemExit("真机缺少 Reqable 系统 CA 证书且无 Root 权限,无法自动注入(请先执行 android-root)。")
|
|
643
|
+
if not ca_path or not ca_path.is_file():
|
|
644
|
+
raise SystemExit(f"未找到本机 Reqable CA 证书文件: {ca_path},请用 --ca-file 指定。")
|
|
645
|
+
hash_name = compute_ca_hash_name(ca_path)
|
|
646
|
+
install_android_ca_tmpfs(serial, ca_path, hash_name, state["android_sdk"])
|
|
647
|
+
actions.append(f"installed_system_ca_tmpfs({hash_name})")
|
|
648
|
+
|
|
649
|
+
# 3. USB adb reverse + global http_proxy (zero Wi-Fi / zero QR scan required)
|
|
650
|
+
rev_proc = adb_run(serial, "reverse", f"tcp:{client.port}", f"tcp:{client.port}")
|
|
651
|
+
if rev_proc.returncode != 0:
|
|
652
|
+
raise SystemExit(f"adb reverse 失败: {rev_proc.stderr.strip() or rev_proc.stdout.strip()}")
|
|
653
|
+
actions.append(f"adb_reverse(tcp:{client.port})")
|
|
654
|
+
|
|
655
|
+
proxy_val = f"127.0.0.1:{client.port}"
|
|
656
|
+
proxy_proc = adb_run(serial, "shell", f"settings put global http_proxy {proxy_val}")
|
|
657
|
+
if proxy_proc.returncode != 0:
|
|
658
|
+
raise SystemExit(f"设置手机 http_proxy 失败: {proxy_proc.stderr.strip() or proxy_proc.stdout.strip()}")
|
|
659
|
+
actions.append(f"set_http_proxy({proxy_val})")
|
|
660
|
+
|
|
661
|
+
final_state = inspect_android_state(serial, client.port, ca_path)
|
|
662
|
+
warnings: list[str] = []
|
|
663
|
+
if final_state["active_vpn_tun"]:
|
|
664
|
+
warnings.append("检测到手机存在活跃 VPN 网卡(tun*),第三方 VPN 可能会截胡全局 http_proxy 流量;若抓不到目标 App 请先暂停第三方 VPN。")
|
|
665
|
+
|
|
666
|
+
print(
|
|
667
|
+
json.dumps(
|
|
668
|
+
{
|
|
669
|
+
"ok": True,
|
|
670
|
+
"mode": "usb_zero_touch",
|
|
671
|
+
"endpoint": f"http://{client.host}:{client.port}",
|
|
672
|
+
"live_capture": live_status,
|
|
673
|
+
"actions": actions,
|
|
674
|
+
"warnings": warnings,
|
|
675
|
+
"android": final_state,
|
|
676
|
+
},
|
|
677
|
+
indent=2,
|
|
678
|
+
ensure_ascii=False,
|
|
679
|
+
)
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def cmd_android_down(client: ReqableClient, args: argparse.Namespace) -> None:
|
|
684
|
+
serial = resolve_adb_serial(args.serial)
|
|
685
|
+
adb_run(serial, "shell", "settings put global http_proxy :0")
|
|
686
|
+
adb_run(serial, "reverse", "--remove", f"tcp:{client.port}")
|
|
687
|
+
final_proxy = adb_run(serial, "shell", "settings get global http_proxy").stdout.strip()
|
|
688
|
+
print(
|
|
689
|
+
json.dumps(
|
|
690
|
+
{
|
|
691
|
+
"ok": True,
|
|
692
|
+
"serial": serial,
|
|
693
|
+
"http_proxy": final_proxy,
|
|
694
|
+
"removed_reverse": f"tcp:{client.port}",
|
|
695
|
+
},
|
|
696
|
+
indent=2,
|
|
697
|
+
ensure_ascii=False,
|
|
698
|
+
)
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def add_filter_flags(parser: argparse.ArgumentParser) -> None:
|
|
703
|
+
parser.add_argument("--tab", help="目标 Tab ID(默认自动选 captureLive 标签页)")
|
|
704
|
+
parser.add_argument("--keyword", help="跨 URL/Header/Body 关键字筛选")
|
|
705
|
+
parser.add_argument("--regex", action="store_true", help="将 --keyword 作为正则")
|
|
706
|
+
parser.add_argument("--case-sensitive", action="store_true", help="关键字区分大小写")
|
|
707
|
+
parser.add_argument("--host", dest="host_filter", action="append", help="精确 Host 筛选(可重复)")
|
|
708
|
+
parser.add_argument("--url", dest="url_filter", action="append", help="精确 URL 筛选(可重复)")
|
|
709
|
+
parser.add_argument("--ip", dest="ip_filter", action="append", help="精确远端 IP 筛选(可重复)")
|
|
710
|
+
parser.add_argument("--method", dest="method_filter", action="append", help="HTTP 方法筛选(可重复)")
|
|
711
|
+
parser.add_argument("--code", dest="code_filter", type=int, action="append", help="状态码筛选(可重复)")
|
|
712
|
+
parser.add_argument("--app-name", help="客户端应用名称子串")
|
|
713
|
+
parser.add_argument("--app-id", help="客户端包名 / Bundle ID")
|
|
714
|
+
parser.add_argument("--app-pid", type=int, help="客户端 PID")
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
718
|
+
parser = argparse.ArgumentParser(
|
|
719
|
+
prog="reqable_cli.py",
|
|
720
|
+
description="零依赖 Reqable 本地 HTTP API 命令行工具(无需注册 MCP)。",
|
|
721
|
+
)
|
|
722
|
+
parser.add_argument("--api-host", dest="host", help="覆盖 Reqable 本地 API Host(默认 127.0.0.1)")
|
|
723
|
+
parser.add_argument("--api-port", dest="port", type=int, help="覆盖 Reqable 本地 API 端口(默认读配置或 9000)")
|
|
724
|
+
parser.add_argument("--token", help="覆盖 Access Token(默认读 REQABLE_TOKEN 或本地配置)")
|
|
725
|
+
parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT, help="单次请求超时秒数(默认 15)")
|
|
726
|
+
|
|
727
|
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
|
728
|
+
|
|
729
|
+
p_cfg = sub.add_parser("config", help="管理仓库外本地连接配置与 Token(~/.config/ai-reverse-resources/reqable.json)")
|
|
730
|
+
cfg_sub = p_cfg.add_subparsers(dest="config_action", required=True)
|
|
731
|
+
p_cfg_set = cfg_sub.add_parser("set", help="保存本地 host/port/token(权限 0600)")
|
|
732
|
+
p_cfg_set.add_argument("--host", dest="set_host")
|
|
733
|
+
p_cfg_set.add_argument("--port", dest="set_port", type=int)
|
|
734
|
+
p_cfg_set.add_argument("--token", dest="set_token")
|
|
735
|
+
cfg_sub.add_parser("show", help="查看当前解析后的脱敏配置")
|
|
736
|
+
|
|
737
|
+
sub.add_parser("status", help="检查 Reqable 连通性、抓包状态与标签页")
|
|
738
|
+
sub.add_parser("tabs", help="列出当前打开的 Reqable 标签页")
|
|
739
|
+
|
|
740
|
+
p_astatus = sub.add_parser("android-status", help="只读检查真机时钟、系统 CA、adb reverse、代理与 VPN 状态")
|
|
741
|
+
p_astatus.add_argument("-s", "--serial", help="指定 ADB 设备序列号(多设备时必填)")
|
|
742
|
+
p_astatus.add_argument("--ca-file", help="覆盖本机 Reqable CA 证书路径(默认自动定位)")
|
|
743
|
+
|
|
744
|
+
p_aup = sub.add_parser("android-up", help="零人工一键打通真机抓包(拉起 Reqable → 对齐时钟 → Root 注入系统 CA → USB reverse + 代理)")
|
|
745
|
+
p_aup.add_argument("-s", "--serial", help="指定 ADB 设备序列号(多设备时必填)")
|
|
746
|
+
p_aup.add_argument("--ca-file", help="覆盖本机 Reqable CA 证书路径(默认自动定位)")
|
|
747
|
+
p_aup.add_argument("--max-skew", type=int, default=60, help="触发自动同步时钟的最大允许秒差(默认 60)")
|
|
748
|
+
p_aup.add_argument("--no-auto-launch", action="store_true", help="Reqable 未运行时不自动拉起桌面端")
|
|
749
|
+
p_aup.add_argument("--no-sync-time", action="store_true", help="跳过自动同步真机时钟")
|
|
750
|
+
p_aup.add_argument("--no-install-ca", action="store_true", help="跳过自动注入系统 CA 证书")
|
|
751
|
+
p_aup.add_argument("--no-live-start", action="store_true", help="不自动开启 Reqable 实时抓包")
|
|
752
|
+
|
|
753
|
+
p_adown = sub.add_parser("android-down", help="抓包结束一键清理(恢复 http_proxy :0 并移除 adb reverse)")
|
|
754
|
+
p_adown.add_argument("-s", "--serial", help="指定 ADB 设备序列号(多设备时必填)")
|
|
755
|
+
|
|
756
|
+
p_live = sub.add_parser("live", help="控制实时抓包开关或清空列表")
|
|
757
|
+
p_live.add_argument("action", choices=["start", "stop", "clear"])
|
|
758
|
+
|
|
759
|
+
p_proxy = sub.add_parser("proxy", help="切换桌面端系统代理")
|
|
760
|
+
p_proxy.add_argument("state", choices=["on", "off"])
|
|
761
|
+
|
|
762
|
+
p_filter = sub.add_parser("filter", help="按条件筛选并返回匹配 Record ID 列表")
|
|
763
|
+
add_filter_flags(p_filter)
|
|
764
|
+
p_filter.add_argument("--limit", type=int, default=50, help="最多返回最新 N 个 ID(默认 50,0 表示全部)")
|
|
765
|
+
|
|
766
|
+
p_list = sub.add_parser("list", help="按条件筛选并输出最新记录的紧凑摘要(防上下文膨胀)")
|
|
767
|
+
add_filter_flags(p_list)
|
|
768
|
+
p_list.add_argument("--limit", type=int, default=15, help="最多拉取最新 N 条摘要(默认 15)")
|
|
769
|
+
|
|
770
|
+
p_get = sub.add_parser("get", help="按 ID 查看单条抓包详情(默认截断大 Body)")
|
|
771
|
+
p_get.add_argument("id", type=int, help="数字 Record ID")
|
|
772
|
+
p_get.add_argument("--tab", help="目标 Tab ID(默认自动选 captureLive)")
|
|
773
|
+
p_get.add_argument("--headers-only", action="store_true", help="仅显示请求与响应头")
|
|
774
|
+
p_get.add_argument("--max-body-chars", type=int, default=2000, help="Body 预览最大字符数(默认 2000)")
|
|
775
|
+
p_get.add_argument("--full-body", action="store_true", help="不截断输出完整 Body")
|
|
776
|
+
p_get.add_argument("--save-req-body", help="将请求 Body 保存到指定文件路径")
|
|
777
|
+
p_get.add_argument("--save-resp-body", help="将响应 Body 保存到指定文件路径")
|
|
778
|
+
p_get.add_argument("--ws-limit", type=int, default=20, help="WebSocket 最多显示最新 N 帧(默认 20)")
|
|
779
|
+
p_get.add_argument("--raw-json", action="store_true", help="直接输出接口原始 JSON")
|
|
780
|
+
|
|
781
|
+
p_curl = sub.add_parser("curl", help="为指定 Record ID 生成 cURL 命令")
|
|
782
|
+
p_curl.add_argument("id", type=int)
|
|
783
|
+
p_curl.add_argument("--tab")
|
|
784
|
+
|
|
785
|
+
p_compose = sub.add_parser("compose", help="将指定 Record ID 发送到 Reqable 重发标签页")
|
|
786
|
+
p_compose.add_argument("id", type=int)
|
|
787
|
+
p_compose.add_argument("--tab")
|
|
788
|
+
|
|
789
|
+
p_raw = sub.add_parser("raw", help="直接调用任意 Reqable 官方本地 API 路由")
|
|
790
|
+
p_raw.add_argument("method", choices=["GET", "POST"])
|
|
791
|
+
p_raw.add_argument("route", help="如 /capture/rewrite/list")
|
|
792
|
+
p_raw.add_argument("--data", help="JSON 请求体字符串")
|
|
793
|
+
|
|
794
|
+
return parser
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
def main(argv: list[str] | None = None) -> None:
|
|
798
|
+
parser = build_parser()
|
|
799
|
+
args = parser.parse_args(argv)
|
|
800
|
+
|
|
801
|
+
if args.cmd == "config":
|
|
802
|
+
cmd_config(args)
|
|
803
|
+
return
|
|
804
|
+
|
|
805
|
+
host, port, token = resolve_connection(args)
|
|
806
|
+
client = ReqableClient(host=host, port=port, token=token, timeout=args.timeout)
|
|
807
|
+
|
|
808
|
+
if args.cmd == "status":
|
|
809
|
+
cmd_status(client)
|
|
810
|
+
elif args.cmd == "tabs":
|
|
811
|
+
print(json.dumps(client.request("GET", "/tab/list"), indent=2, ensure_ascii=False))
|
|
812
|
+
elif args.cmd == "android-status":
|
|
813
|
+
cmd_android_status(client, args)
|
|
814
|
+
elif args.cmd == "android-up":
|
|
815
|
+
cmd_android_up(client, args)
|
|
816
|
+
elif args.cmd == "android-down":
|
|
817
|
+
cmd_android_down(client, args)
|
|
818
|
+
elif args.cmd == "live":
|
|
819
|
+
route = {"start": "/capture/live/on", "stop": "/capture/live/off", "clear": "/capture/live/clear"}[args.action]
|
|
820
|
+
res = client.request("POST", route)
|
|
821
|
+
print(json.dumps({"action": args.action, "result": res}, indent=2, ensure_ascii=False))
|
|
822
|
+
elif args.cmd == "proxy":
|
|
823
|
+
res = client.request("POST", "/proxy/set", {"overrideSystem": args.state == "on"})
|
|
824
|
+
print(json.dumps({"overrideSystem": args.state == "on", "result": res}, indent=2, ensure_ascii=False))
|
|
825
|
+
elif args.cmd == "filter":
|
|
826
|
+
tab_id = client.resolve_tab_id(args.tab)
|
|
827
|
+
ids = extract_ids(client.request("POST", "/capture/record/filter", {"tabId": tab_id, "filters": build_filters(args)}))
|
|
828
|
+
shown = ids[-args.limit :] if args.limit > 0 else ids
|
|
829
|
+
print(json.dumps({"tabId": tab_id, "total_matched": len(ids), "ids": shown}, indent=2, ensure_ascii=False))
|
|
830
|
+
elif args.cmd == "list":
|
|
831
|
+
cmd_list(client, args)
|
|
832
|
+
elif args.cmd == "get":
|
|
833
|
+
cmd_get(client, args)
|
|
834
|
+
elif args.cmd == "curl":
|
|
835
|
+
tab_id = client.resolve_tab_id(args.tab)
|
|
836
|
+
res = client.request("POST", "/capture/record/generate/curl", {"tabId": tab_id, "id": args.id})
|
|
837
|
+
print(res if isinstance(res, str) else json.dumps(res, indent=2, ensure_ascii=False))
|
|
838
|
+
elif args.cmd == "compose":
|
|
839
|
+
tab_id = client.resolve_tab_id(args.tab)
|
|
840
|
+
res = client.request("POST", "/capture/record/compose", {"tabId": tab_id, "id": args.id})
|
|
841
|
+
print(json.dumps(res, indent=2, ensure_ascii=False))
|
|
842
|
+
elif args.cmd == "raw":
|
|
843
|
+
payload = json.loads(args.data) if args.data else None
|
|
844
|
+
res = client.request(args.method, args.route, payload)
|
|
845
|
+
print(res if isinstance(res, str) else json.dumps(res, indent=2, ensure_ascii=False))
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
if __name__ == "__main__":
|
|
849
|
+
main()
|