dsh-reverse-plugin 0.0.0-stage → 0.3.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.
Files changed (45) hide show
  1. package/index.js +78 -0
  2. package/package.json +45 -4
  3. package/preset/js-reverse.patch.yml +179 -0
  4. package/skills/js/iv8-env-runtime/SKILL.md +159 -0
  5. package/skills/js/iv8-env-runtime/assets/entry-report-template.txt +23 -0
  6. package/skills/js/iv8-env-runtime/assets/env_starter.py +100 -0
  7. package/skills/js/iv8-env-runtime/references/case-function-iwencai.md +96 -0
  8. package/skills/js/iv8-env-runtime/references/case-intercept-douyin.md +133 -0
  9. package/skills/js/iv8-env-runtime/references/config-defaults-cheatsheet.md +75 -0
  10. package/skills/js/iv8-env-runtime/references/cross-platform-install.md +108 -0
  11. package/skills/js/iv8-env-runtime/references/iv8-api-contract.md +97 -0
  12. package/skills/js/iv8-env-runtime/references/network-and-eventloop.md +113 -0
  13. package/skills/js/iv8-env-runtime/references/part1-entry-location.md +138 -0
  14. package/skills/js/iv8-env-runtime/references/part1-mcp-tool-map.md +77 -0
  15. package/skills/js/iv8-env-runtime/references/part2-discovery.md +80 -0
  16. package/skills/js/iv8-env-runtime/references/patching-principles.md +91 -0
  17. package/skills/js/iv8-env-runtime/references/trap-blacklist.md +60 -0
  18. package/skills/js/iv8-env-runtime/references/version-gotchas.md +128 -0
  19. package/skills/js/iv8-env-runtime/scripts/consistency_lint.py +211 -0
  20. package/skills/js/iv8-env-runtime/scripts/defaults_audit.py +143 -0
  21. package/skills/js/iv8-env-runtime/scripts/monitor_env.py +185 -0
  22. package/skills/js/iv8-env-runtime/scripts/network_bridge.py +147 -0
  23. package/skills/js/iv8-env-runtime/scripts/parity_check.py +175 -0
  24. package/skills/js/iv8-env-runtime/scripts/preflight.py +144 -0
  25. package/skills/js/iv8-env-runtime/scripts/reproduce_stub_error.py +165 -0
  26. package/skills/js/iv8-env-runtime/scripts/run_target.py +150 -0
  27. package/skills/js/iv8-jsvmp-recovery/SKILL.md +129 -0
  28. package/skills/js/iv8-jsvmp-recovery/agents/openai.yaml +4 -0
  29. package/skills/js/iv8-jsvmp-recovery/references/case-study-douyin-a-bogus.md +320 -0
  30. package/skills/js/iv8-jsvmp-recovery/references/controlled-oracle-and-equivalence.md +247 -0
  31. package/skills/js/iv8-jsvmp-recovery/references/static-trace-evidence.md +289 -0
  32. package/skills/js/iv8-jsvmp-recovery/references/vmp-domain-model.md +212 -0
  33. package/skills/js/iv8-jsvmp-recovery/scripts/verify-equivalence.py +281 -0
  34. package/skills/js/js-ast-deobfuscation/SKILL.md +140 -0
  35. package/skills/js/js-ast-deobfuscation/agents/openai.yaml +4 -0
  36. package/skills/js/js-ast-deobfuscation/references/anti-patterns.md +325 -0
  37. package/skills/js/js-ast-deobfuscation/references/first-pass.md +255 -0
  38. package/skills/js/js-ast-deobfuscation/references/interaction-and-stopping.md +758 -0
  39. package/skills/js/js-ast-deobfuscation/references/iv8-runtime-observation.md +773 -0
  40. package/skills/js/js-ast-deobfuscation/references/jsvmp-identification.md +328 -0
  41. package/skills/js/js-ast-deobfuscation/references/methods-and-evidence.md +460 -0
  42. package/skills/js/js-ast-deobfuscation/references/patterns-and-priority.md +516 -0
  43. package/skills/js/js-ast-deobfuscation/references/validation-contract.md +604 -0
  44. package/skills/js/js-ast-deobfuscation/scripts/prepare-source.mjs +921 -0
  45. package/README.md +0 -3
@@ -0,0 +1,147 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ network_bridge.py — iv8 真实网络桥接(阶段 P3,固化四步握手)
5
+
6
+ ======================================================================
7
+ 四步握手红线(社区版无真实网络传输栈,真请求必须走 Python 侧):
8
+ 1) JS 侧发起 XHR/fetch —— iv8 只记账到 netLog,不真正发出请求。
9
+ 2) 暂停在这里,从 netLog 取出目标请求(url/method/headers/body)。
10
+ 3) Python 侧用真实 HTTP 客户端(requests / curl_cffi ...)真发,
11
+ 代理 / TLS 指纹 / cookie 池 / verify 由调用者决定。
12
+ 4) ctx.add_resource(url, body, status, headers) 注入响应,
13
+ 再 eventLoop.drain() 推进事件循环 —— XHR 回调此时才命中注入的响应。
14
+ 顺序错了(比如没 drain 就读结果,或没 add_resource 就 drain)都会拿到空/半成品。
15
+
16
+ ⚠ GIL 警告:
17
+ ctx.expose() 暴露给 JS 的 Python 函数,在被 JS 调用期间会持有 GIL 并阻塞
18
+ 当前 V8 执行与其他 Python 线程,是完全同步阻塞的。因此:
19
+ - 暴露的桥接函数要尽量轻量,别在里面塞重逻辑;
20
+ - 高并发场景优先用下面 bridge_request() 的「外部真发 + add_resource 注入」模式,
21
+ 而不是把 requests.get 直接 expose 进 JS 里循环调用。
22
+ ======================================================================
23
+
24
+ 用途:
25
+ 提供一个可复用的 bridge_request():在 iv8 里让目标 JS 发起请求 → 从 netLog 捞出
26
+ 该请求 → Python 侧真发 → add_resource 注入响应 → drain 推进 → 返回真实响应。
27
+ 以及 __main__ 里一段最小可跑演示。
28
+
29
+ 用法(库调用):
30
+ import iv8, requests
31
+ from network_bridge import bridge_request
32
+ with iv8.JSContext(environment={...}) as ctx:
33
+ ctx.eval(open("target.js").read())
34
+ # 让目标 JS 发起它的请求(这里只入 netLog,不真发)
35
+ ctx.eval("window.startCollect()")
36
+ resp_text = bridge_request(
37
+ ctx,
38
+ url_substr="/api/collect", # 用于在 netLog 中定位目标请求
39
+ session=requests.Session(), # 由调用者提供,携带代理/cookie/TLS 策略
40
+ verify=False, # curl_cffi/requests 自签名场景可关
41
+ )
42
+
43
+ 本文件属于 iv8-env-runtime skill。
44
+ 交叉引用:事件循环 drain/advance 语义与 netLog 结构见
45
+ references/network-and-eventloop.md;
46
+ iv8 权威 API 见 references/iv8-api-contract.md。
47
+ """
48
+
49
+ import sys
50
+
51
+
52
+ def _find_entry(netlog, url_substr):
53
+ """在 netLog.entries 里按 url 子串定位目标请求,取最后一条匹配(通常是最新)。"""
54
+ match = None
55
+ for e in netlog:
56
+ if not isinstance(e, dict):
57
+ continue
58
+ if url_substr in str(e.get("url", "")):
59
+ match = e
60
+ return match
61
+
62
+
63
+ def bridge_request(ctx, url_substr, session=None, method=None,
64
+ extra_headers=None, verify=True, proxies=None, timeout=15):
65
+ """执行一次四步握手,返回注入到 iv8 后由 JS 侧收到的响应体文本。
66
+
67
+ 参数:
68
+ ctx : 已载入目标 JS 且已触发发请求的 iv8.JSContext。
69
+ url_substr : 在 netLog 中定位目标请求的 url 子串。
70
+ session : 调用者提供的 HTTP 客户端(requests.Session / curl_cffi.Session);
71
+ None 时用一次性 requests。代理/TLS 指纹/cookie 全由它决定。
72
+ method : 覆盖请求方法;None 时用 netLog 记的方法。
73
+ extra_headers: 追加/覆盖到真发请求上的头(如补 cookie/referer)。
74
+ verify : 传给客户端的 TLS 校验开关(curl_cffi 自签名场景常关)。
75
+ proxies : 传给客户端的代理配置。
76
+ timeout : 真发超时秒数。
77
+
78
+ 返回:注入后的响应体文本(同时已 add_resource + drain,JS 侧回调已命中)。
79
+ """
80
+ # 步骤 2:从 netLog 捞出目标请求(此前 JS 已 step 1 发起,仅入账未真发)
81
+ netlog = ctx.eval("window.__iv8__.netLog.entries", to_py=True)
82
+ entry = _find_entry(netlog, url_substr)
83
+ if entry is None:
84
+ raise LookupError(
85
+ "netLog 中没有匹配 '{}' 的请求:确认目标 JS 已真的发起该请求,"
86
+ "且 url_substr 写对了。当前 netLog 有 {} 条。".format(url_substr, len(netlog)))
87
+
88
+ url = entry.get("url")
89
+ req_method = (method or entry.get("method") or "GET").upper()
90
+ headers = dict(entry.get("headers") or {})
91
+ if extra_headers:
92
+ headers.update(extra_headers)
93
+ body = entry.get("body") or entry.get("postData")
94
+
95
+ # 步骤 3:Python 侧真发(客户端由调用者决定,携带代理/cookie/TLS 指纹)
96
+ if session is None:
97
+ import requests
98
+ session = requests.Session()
99
+ resp = session.request(req_method, url, headers=headers, data=body,
100
+ verify=verify, proxies=proxies, timeout=timeout)
101
+
102
+ # 步骤 4:注入响应 → drain 推进 → JS 侧 XHR 回调命中
103
+ ctx.add_resource(
104
+ url=url,
105
+ body=resp.text,
106
+ status=resp.status_code,
107
+ headers=dict(resp.headers),
108
+ )
109
+ ctx.eval("window.__iv8__.eventLoop.drain()")
110
+ return resp.text
111
+
112
+
113
+ # ---------------------------------------------------------------------------
114
+ # 最小可跑演示(需已安装 iv8 与 requests):JS 发 XHR → 桥接真发 httpbin → 注入 → 读结果
115
+ # ---------------------------------------------------------------------------
116
+ def _demo():
117
+ try:
118
+ import iv8
119
+ import requests # noqa: F401 —— bridge_request 内部用;此处仅校验可导入
120
+ except Exception as e: # noqa: BLE001
121
+ print("[network_bridge][demo] 依赖缺失:{};先跑 preflight.py。".format(e), file=sys.stderr)
122
+ return 2
123
+
124
+ with iv8.JSContext() as ctx:
125
+ ctx.eval("""
126
+ window.__iv8__.page.load({
127
+ baseURL: 'https://example.com',
128
+ html: '<html><body></body></html>'
129
+ });
130
+ """)
131
+ # 步骤 1:JS 侧发起异步 XHR(社区版只入 netLog,不真发)
132
+ ctx.eval("""
133
+ var xhr = new XMLHttpRequest();
134
+ xhr.open('GET', 'https://httpbin.org/get?foo=bar');
135
+ xhr.onload = function () { window._demoResult = xhr.responseText; };
136
+ xhr.send();
137
+ """)
138
+ # 步骤 2/3/4:桥接
139
+ body = bridge_request(ctx, url_substr="httpbin.org/get")
140
+ print("[network_bridge][demo] 注入响应长度:{}".format(len(body)))
141
+ got = ctx.eval("window._demoResult")
142
+ print("[network_bridge][demo] JS 侧收到长度:{}".format(len(got) if got else 0))
143
+ return 0
144
+
145
+
146
+ if __name__ == "__main__":
147
+ sys.exit(_demo())
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """parity_check.py —— P4 验收对账:iv8 产物 vs 真机产物,逐字符/逐字段找首个差异。
4
+
5
+ 作用(对应 SKILL.md 的 P4「parity 对账 + 服务器判决唯一真相」):
6
+ 把「iv8 补环境跑出来的签名/token」和「真实浏览器抓到的同场景签名/token」放一起,
7
+ 逐字符(或逐字段,若是 JSON/query-string)对比,定位第一个不一致的位置,
8
+ 帮你把「补环境哪里还没对齐」收窄到具体字段。
9
+
10
+ ⚠ 铁律(本 skill 的验收真相层):
11
+ 本地一致只是「必要不充分」条件。parity 全绿也不代表过盾——
12
+ 很多签名含时间戳/随机盐,本来就该逐次不同;对账目的是排查「结构性字段」对齐,
13
+ 不是要求整串相等。**唯一的最终真相是把 iv8 产物发到目标服务器,看它判 200 / code=0。**
14
+ 算出来被服务器拒 → 回 P3 继续补环境;返回 403(风控/IP/频率)→ 不是环境问题,别在补环境里空转。
15
+ 服务器判决怎么读见 references/part2-discovery.md。
16
+
17
+ 对账模式(自动判定,也可 --mode 强制):
18
+ - raw :整串逐字符对比,报首个差异下标 + 两侧上下文窗口
19
+ - kv :query-string(a=1&b=2)逐键对比,报缺键/多键/值不同
20
+ - json :JSON 逐字段递归对比,报首个路径差异
21
+
22
+ 关系与边界:
23
+ - 上游:iv8 产物来自 assets/env_starter.py 跑出的签名;真机产物来自 js-reverse MCP
24
+ 或真实浏览器抓包(找入口/抓真机产物见 references/part1-entry-location.md)。
25
+ - 本脚本只做「本地一致性」这一必要条件;充分条件(服务器判决)由你手动发包核对。
26
+
27
+ 用法:
28
+ python parity_check.py <iv8产物> <真机产物> [--mode raw|kv|json] [--file]
29
+ 默认两个位置参数是「值本身」;加 --file 则当作文件路径读取内容。
30
+ 示例:
31
+ python parity_check.py "a_bogus=xxx" "a_bogus=yyy"
32
+ python parity_check.py iv8_out.txt real_out.txt --file
33
+ python parity_check.py iv8.json real.json --file --mode json
34
+ """
35
+
36
+ import argparse
37
+ import json
38
+ import sys
39
+ from urllib.parse import parse_qsl
40
+
41
+
42
+ def _read(value, is_file):
43
+ if not is_file:
44
+ return value
45
+ with open(value, "r", encoding="utf-8") as f:
46
+ return f.read().strip()
47
+
48
+
49
+ def guess_mode(a, b):
50
+ """自动判定对账模式。"""
51
+ for s in (a, b):
52
+ t = s.strip()
53
+ if t[:1] in "{[":
54
+ try:
55
+ json.loads(t)
56
+ return "json"
57
+ except ValueError:
58
+ pass
59
+ if ("=" in a and ("&" in a or "&" in b)) or ("=" in a and "=" in b and " " not in a):
60
+ return "kv"
61
+ return "raw"
62
+
63
+
64
+ def check_raw(a, b):
65
+ """逐字符对比,返回 (是否一致, 报告文本)。"""
66
+ if a == b:
67
+ return True, f"完全一致(长度 {len(a)})"
68
+ n = min(len(a), len(b))
69
+ idx = next((i for i in range(n) if a[i] != b[i]), n)
70
+ lo = max(0, idx - 20)
71
+ win_a = a[lo:idx + 20]
72
+ win_b = b[lo:idx + 20]
73
+ report = [
74
+ f"首个差异位置: 下标 {idx}(长度 iv8={len(a)} / 真机={len(b)})",
75
+ f" iv8 : ...{win_a!r}",
76
+ f" 真机: ...{win_b!r}",
77
+ ]
78
+ if idx < n:
79
+ report.append(f" 差异字符: iv8={a[idx]!r} 真机={b[idx]!r}")
80
+ else:
81
+ longer = "iv8" if len(a) > len(b) else "真机"
82
+ report.append(f" 前 {idx} 字符相同,{longer} 更长(尾部多出内容)")
83
+ return False, "\n".join(report)
84
+
85
+
86
+ def check_kv(a, b):
87
+ """query-string 逐键对比。"""
88
+ da = dict(parse_qsl(a, keep_blank_values=True))
89
+ db = dict(parse_qsl(b, keep_blank_values=True))
90
+ keys = list(dict.fromkeys(list(da) + list(db)))
91
+ diffs = []
92
+ for k in keys:
93
+ if k not in da:
94
+ diffs.append(f" [多键] 真机有、iv8 缺: {k}={db[k]!r}")
95
+ elif k not in db:
96
+ diffs.append(f" [缺键] iv8 有、真机缺: {k}={da[k]!r}")
97
+ elif da[k] != db[k]:
98
+ diffs.append(f" [值异] {k}: iv8={da[k]!r} 真机={db[k]!r}")
99
+ if not diffs:
100
+ return True, f"所有键值一致(共 {len(keys)} 键)"
101
+ return False, f"共 {len(diffs)} 处键差异:\n" + "\n".join(diffs)
102
+
103
+
104
+ def _first_json_diff(a, b, path="$"):
105
+ """递归找 JSON 首个字段差异,返回路径描述或 None。"""
106
+ if type(a) is not type(b) and not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
107
+ return f"{path}: 类型不同 iv8={type(a).__name__} 真机={type(b).__name__}"
108
+ if isinstance(a, dict):
109
+ for k in dict.fromkeys(list(a) + list(b)):
110
+ if k not in a:
111
+ return f"{path}.{k}: iv8 缺此键(真机={b[k]!r})"
112
+ if k not in b:
113
+ return f"{path}.{k}: 真机缺此键(iv8={a[k]!r})"
114
+ d = _first_json_diff(a[k], b[k], f"{path}.{k}")
115
+ if d:
116
+ return d
117
+ return None
118
+ if isinstance(a, list):
119
+ if len(a) != len(b):
120
+ return f"{path}: 数组长度不同 iv8={len(a)} 真机={len(b)}"
121
+ for i, (x, y) in enumerate(zip(a, b)):
122
+ d = _first_json_diff(x, y, f"{path}[{i}]")
123
+ if d:
124
+ return d
125
+ return None
126
+ if a != b:
127
+ return f"{path}: 值不同 iv8={a!r} 真机={b!r}"
128
+ return None
129
+
130
+
131
+ def check_json(a, b):
132
+ try:
133
+ ja, jb = json.loads(a), json.loads(b)
134
+ except ValueError as e:
135
+ return False, f"JSON 解析失败: {e}(改用 --mode raw)"
136
+ diff = _first_json_diff(ja, jb)
137
+ if diff is None:
138
+ return True, "所有字段一致"
139
+ return False, "首个字段差异:\n " + diff
140
+
141
+
142
+ def main():
143
+ ap = argparse.ArgumentParser(description="iv8 产物 vs 真机产物 对账;服务器判决才是最终真相")
144
+ ap.add_argument("iv8_value", help="iv8 补环境产物(值,或加 --file 传路径)")
145
+ ap.add_argument("real_value", help="真机产物(值,或加 --file 传路径)")
146
+ ap.add_argument("--mode", choices=["raw", "kv", "json"], default="auto", help="对账模式(默认自动判定)")
147
+ ap.add_argument("--file", action="store_true", help="把两个位置参数当作文件路径读取")
148
+ args = ap.parse_args()
149
+
150
+ a = _read(args.iv8_value, args.file)
151
+ b = _read(args.real_value, args.file)
152
+
153
+ mode = args.mode if args.mode != "auto" else guess_mode(a, b)
154
+ print(f"对账模式: {mode}\n")
155
+
156
+ ok, report = {"raw": check_raw, "kv": check_kv, "json": check_json}[mode](a, b)
157
+ print(report)
158
+
159
+ print("\n" + "=" * 72)
160
+ if ok:
161
+ print("本地对账: 一致 ✓(必要条件满足)")
162
+ else:
163
+ print("本地对账: 不一致 ✗ → 回 P3 补环境(对准差异字段)")
164
+ print(
165
+ "⚠ 本地一致只是必要不充分。最终真相 = 把 iv8 产物发到目标服务器看判决:\n"
166
+ " 服务器 200 / code=0 才算翻过;被拒→回 P3;403(风控/IP/频率)→ 非环境问题。\n"
167
+ " (含时间戳/随机盐的签名本就逐次不同,对账看结构性字段而非整串相等。)\n"
168
+ " 服务器判决怎么读见 references/part2-discovery.md。"
169
+ )
170
+ # 退出码:本地一致 0 / 不一致 1(便于脚本串联),但仍以服务器判决为准
171
+ sys.exit(0 if ok else 1)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ preflight.py — iv8 环境就绪硬前置门(阶段 P0)
5
+
6
+ 用途:
7
+ 在做任何补环境工作之前,先跑这一步。它按当前平台/架构/Python 版本判定
8
+ iv8 能否安装与运行,装错平台或版本直接硬阻断(sys.exit 非 0),并在成功时
9
+ 打印已安装的 iv8.__version__ —— 这个版本号是「单一真相源」,
10
+ references/version-gotchas.md 的所有版本门控(E1 btoa、E2 MessageChannel、
11
+ E4 WASM 等)都以此处打印的实测版本为准,不要凭记忆判断。
12
+
13
+ 用法:
14
+ python3 scripts/preflight.py
15
+ 退出码 0 = 环境就绪;非 0 = 阻断(终端会打印具体原因与修复指引)。
16
+
17
+ 约束(来自 iv8 README,实测 0.1.3):
18
+ - Windows x64 / Linux x86_64:pip 官方源可装(PyPI,Python 3.9–3.14)。
19
+ - Linux aarch64:需自查 manylinux aarch64 wheel 是否可得。
20
+ - macOS 仅 Apple Silicon(arm64) 实验版,不上 PyPI,去 GitHub Releases 下 wheel。
21
+ 支持 Python 3.11–3.14、macOS 14+。Intel Mac 或 Py<3.11 一律不支持。
22
+ - 项目强制用 uv 管理依赖(见 CLAUDE.md)。
23
+
24
+ 本文件属于 iv8-env-runtime skill。
25
+ 交叉引用:安装细节见 references/cross-platform-install.md;
26
+ 版本坑门控见 references/version-gotchas.md(消费本脚本打印的版本号)。
27
+ """
28
+
29
+ import platform
30
+ import sys
31
+
32
+ GH_RELEASES = "https://github.com/HanZzzzz000/iv8/releases"
33
+
34
+
35
+ def _py_tag():
36
+ """把 3.11 -> 'cp311',供拼 macOS wheel 名用。"""
37
+ return "cp{}{}".format(sys.version_info.major, sys.version_info.minor)
38
+
39
+
40
+ def _fail(msg):
41
+ """打印阻断原因并以非 0 退出。"""
42
+ print("\n[preflight][阻断] " + msg, file=sys.stderr)
43
+ sys.exit(2)
44
+
45
+
46
+ def _guide_install():
47
+ """按平台/架构/Python 版本给出安装指引;不支持的组合直接 _fail。
48
+
49
+ 返回 True 表示「本平台应当已经能 import iv8」(走 PyPI 或已下载的 wheel),
50
+ 仅用于决定后续冒烟测试的措辞。
51
+ """
52
+ system = platform.system()
53
+ machine = platform.machine().lower()
54
+ py = sys.version_info
55
+
56
+ print("[preflight] 平台检测:system={} machine={} python={}.{}.{}".format(
57
+ system, machine, py.major, py.minor, py.micro))
58
+
59
+ # ---- Windows ----
60
+ if system == "Windows":
61
+ if machine not in ("amd64", "x86_64"):
62
+ _fail("Windows 仅支持 x64(当前 machine={}),无预编译 wheel。".format(machine))
63
+ if not (3, 9) <= (py.major, py.minor) <= (3, 14):
64
+ _fail("iv8 支持 Python 3.9–3.14,当前 {}.{} 不在范围内。".format(py.major, py.minor))
65
+ print("[preflight] Windows x64:uv pip install iv8 (PyPI 官方源)")
66
+ return True
67
+
68
+ # ---- Linux ----
69
+ if system == "Linux":
70
+ if machine in ("x86_64", "amd64"):
71
+ if not (3, 9) <= (py.major, py.minor) <= (3, 14):
72
+ _fail("iv8 支持 Python 3.9–3.14,当前 {}.{} 不在范围内。".format(py.major, py.minor))
73
+ print("[preflight] Linux x86_64:uv pip install iv8 (PyPI,manylinux)")
74
+ return True
75
+ if machine in ("aarch64", "arm64"):
76
+ # aarch64 wheel 是否发布随版本变化,不写死结论,交给用户核对。
77
+ print("[preflight] Linux aarch64:README 明确的官方轮子是 x64 manylinux。")
78
+ print(" 请自查 PyPI/Releases 是否提供 manylinux aarch64 wheel:")
79
+ print(" uv pip install iv8 # 若报 no matching distribution 即无 aarch64 轮")
80
+ print(" 若确无 aarch64 wheel,则当前架构暂无本地安装路径。")
81
+ return False
82
+ _fail("Linux 未知架构 machine={},无对应 wheel。".format(machine))
83
+
84
+ # ---- macOS ----
85
+ if system == "Darwin":
86
+ if machine != "arm64":
87
+ _fail("macOS 仅支持 Apple Silicon(arm64) 实验版;当前 machine={}(Intel Mac 不支持)。".format(machine))
88
+ if not (3, 11) <= (py.major, py.minor) <= (3, 14):
89
+ _fail("macOS 实验版仅支持 Python 3.11–3.14(且需 macOS 14+);当前 {}.{} 不支持。".format(
90
+ py.major, py.minor))
91
+ tag = _py_tag()
92
+ wheel = "iv8-<ver>-{tag}-{tag}-macosx_14_0_arm64.whl".format(tag=tag)
93
+ print("[preflight] macOS Apple Silicon 实验版(不上 PyPI):")
94
+ print(" 1) 去 GitHub Releases 下载对应 wheel:{}".format(GH_RELEASES))
95
+ print(" 文件名形如(<ver> 用实际版本替换,勿写死):{}".format(wheel))
96
+ print(" 2) 用 uv 安装:uv pip install ./{}".format(wheel))
97
+ return False # 是否已装取决于用户是否下载过,冒烟测试会给出真实结论
98
+
99
+ _fail("未识别的操作系统 system={}。".format(system))
100
+
101
+
102
+ def _smoke():
103
+ """import iv8 冒烟:ctx.eval('1+1')==2 且 navigator.webdriver==False,并打印版本号。"""
104
+ try:
105
+ import iv8
106
+ except Exception as e: # noqa: BLE001 —— 需要把任何导入失败都转成清晰指引
107
+ _fail("import iv8 失败:{}\n"
108
+ " 说明 iv8 尚未安装或安装的 wheel 与当前平台/Python 不匹配。\n"
109
+ " 按上方安装指引用 uv 安装对应 wheel 后重跑本脚本。".format(e))
110
+
111
+ version = getattr(iv8, "__version__", "<未知>")
112
+
113
+ try:
114
+ with iv8.JSContext() as ctx:
115
+ one_plus_one = ctx.eval("1 + 1")
116
+ webdriver = ctx.eval("navigator.webdriver")
117
+ except Exception as e: # noqa: BLE001
118
+ _fail("iv8 已导入但 JSContext 冒烟失败:{}".format(e))
119
+
120
+ if one_plus_one != 2:
121
+ _fail("冒烟异常:ctx.eval('1 + 1') 返回 {!r}(应为 2)。".format(one_plus_one))
122
+ if webdriver is not False:
123
+ _fail("冒烟异常:navigator.webdriver 返回 {!r}(应为 False)。".format(webdriver))
124
+
125
+ # ★ 单一真相源:把实测版本号打印出来,供 version-gotchas 门控消费。
126
+ print("\n[preflight][通过] iv8 冒烟成功。")
127
+ print("[preflight] iv8.__version__ = {}".format(version))
128
+ print("[preflight] ↑ 该版本号是版本门控唯一真相;references/version-gotchas.md")
129
+ print(" 按此判断 E1(btoa)/E2(MessageChannel)/E4(WASM) 等坑是否已修,勿凭记忆。")
130
+ return version
131
+
132
+
133
+ def main():
134
+ print("=" * 64)
135
+ print("iv8-env-runtime · P0 preflight(环境就绪硬前置门)")
136
+ print("=" * 64)
137
+ _guide_install()
138
+ _smoke()
139
+ print("\n[preflight] P0 通过,可进入 P1(找入口)。")
140
+ return 0
141
+
142
+
143
+ if __name__ == "__main__":
144
+ sys.exit(main())
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """reproduce_stub_error.py —— P2 定位 stub 空壳窟窿:跑目标直到抛 TypeError,压缩打印异常栈。
4
+
5
+ 作用(对应 SKILL.md 的 P2「TypeError 栈=stub 窟窿」):
6
+ iv8 对很多浏览器 API 给了「接口级 stub」——存在但内部为空壳(典型:
7
+ MessageChannel 构造出来 port1/port2 为 null)。目标 JS 一旦真去用它(如
8
+ core-js 的 microtask 降级链会 new MessageChannel() 再取 port.postMessage),
9
+ 就在运行时抛 TypeError。本脚本分步 eval 目标(load → init → 触发),
10
+ 第一处抛错即捕获,并把冗长的混淆源码行压掉,只留「异常类型 + 位置摘要」,
11
+ 再打印一个「用 wrapNative 替换 stub」的提示模板。
12
+
13
+ 这是「三态」里的中间态:stub 空壳(替换)——区别于「真实现(别动)」与
14
+ 「陷阱缺失(绝不补)」。stub 的判定证据就是这里的 TypeError 栈。
15
+
16
+ 关系与边界:
17
+ - 上游:scripts/monitor_env.py 第⑥类「疑似缺失 API」提示哪里可能有窟窿;
18
+ 本脚本用「真跑抛错」坐实是不是 stub 空壳(缺失=没有该 API;stub=有但为空壳)。
19
+ - 下游:确认是 stub → 按 references/patching-principles.md 的 iv8 原生补丁契约,
20
+ 用 __iv8__.wrapNative 写一个有真机证据的最小替身。
21
+ 本脚本只复现 MessageChannel / Worker 的 core-js 降级链与 iv8 调度问题。
22
+ - MessageChannel/Worker null port 属已知坑 E2,版本门控见 references/version-gotchas.md。
23
+ - 权威 API 契约见 references/iv8-api-contract.md。
24
+
25
+ 用法:
26
+ python reproduce_stub_error.py <目标JS路径> [--init <init表达式文件>] [--trigger <触发表达式文件>]
27
+ [--env <environment JSON文件>] [--patch <预置替身JS文件>]
28
+
29
+ - 不给 --patch:复现原始 TypeError(先看窟窿在哪)
30
+ - 给 --patch:把替身 JS 先注入再跑(验证替换后是否跑通),
31
+ --patch 文件内应是一段用 __iv8__.wrapNative 写的替身(示例见文末提示模板)。
32
+ """
33
+
34
+ import argparse
35
+ import json
36
+ import os
37
+ import re
38
+ import sys
39
+
40
+ try:
41
+ import iv8
42
+ except ImportError:
43
+ sys.exit("未找到 iv8。先跑 scripts/preflight.py 确认安装(安装见 references/cross-platform-install.md)。")
44
+
45
+
46
+ # wrapNative 替换 stub 的提示模板(以 MessageChannel 为例,别照抄值,按目标改)
47
+ WRAPNATIVE_HINT = """\
48
+ [提示] 若确认是 stub 空壳(如 MessageChannel port=null),用 __iv8__.wrapNative 替换:
49
+
50
+ window.MessageChannel = __iv8__.wrapNative(function() {
51
+ var p1 = { onmessage: null }, p2 = { onmessage: null };
52
+ p1.postMessage = function(d) {
53
+ if (p2.onmessage) setTimeout(function(){ p2.onmessage({ data: d }); }, 0);
54
+ };
55
+ p2.postMessage = function(d) {
56
+ if (p1.onmessage) setTimeout(function(){ p1.onmessage({ data: d }); }, 0);
57
+ };
58
+ return { port1: p1, port2: p2 };
59
+ }, 'MessageChannel');
60
+
61
+ 要点:
62
+ - wrapNative 让替身 toString() 显示 [native code],降低可观测差异。
63
+ - 触发后需 __iv8__.eventLoop.advance(...) / drain() 排空 setTimeout 回调(微任务降级链)。
64
+ - 三态:stub=替换 / 真实现=别动 / 陷阱缺失=绝不补(见 references/patching-principles.md)。
65
+ - 完整替身必须按目标证据最小实现,并按 references/patching-principles.md 补后对账。
66
+ """
67
+
68
+
69
+ def summarize_exception(exc, limit=1200):
70
+ """压缩 iv8 异常字符串:混淆目标的源码行可能是整份几十 KB bundle,这里裁掉只留位置。"""
71
+ text = str(exc) or repr(exc)
72
+ text = re.sub(r"\s+", " ", text).strip()
73
+ # iv8 异常串常形如 "... ( @ <line> : <col> ) -> <整行源码>",裁掉 -> 之后
74
+ m = re.match(r"^(.*?\( @ \d+ : \d+ \))\s*->", text)
75
+ if m:
76
+ return m.group(1)
77
+ if len(text) > limit:
78
+ return text[:limit] + " ...<truncated>"
79
+ return text
80
+
81
+
82
+ def run_step(ctx, label, source):
83
+ """执行一步,成功返回 (True, value),抛错则打印压缩摘要返回 (False, None)。"""
84
+ print(f"\n== {label} ==")
85
+ try:
86
+ value = ctx.eval(source, name=label, to_py=True)
87
+ except Exception as exc: # noqa: BLE001 —— 就是要捕获任意运行时异常
88
+ print("FAILED")
89
+ print(" exception type :", type(exc).__name__)
90
+ print(" exception summary:", summarize_exception(exc))
91
+ return False, None
92
+ print("OK")
93
+ return True, value
94
+
95
+
96
+ def main():
97
+ ap = argparse.ArgumentParser(description="跑目标直到抛 TypeError,压缩打印,定位 stub 空壳窟窿")
98
+ ap.add_argument("js_path", help="目标 JS 文件路径")
99
+ ap.add_argument("--init", default="", help="加载后的初始化表达式文件(如 xxx.init({...}))")
100
+ ap.add_argument("--trigger", default="", help="触发签名/取数的表达式文件")
101
+ ap.add_argument("--env", default="", help="environment 画像 JSON 文件路径")
102
+ ap.add_argument("--patch", default="", help="预置替身 JS 文件(先注入再跑,验证替换是否跑通)")
103
+ args = ap.parse_args()
104
+
105
+ if not os.path.isfile(args.js_path):
106
+ sys.exit(f"目标 JS 不存在: {args.js_path}")
107
+
108
+ env = None
109
+ if args.env:
110
+ with open(args.env, "r", encoding="utf-8") as f:
111
+ env = json.load(f)
112
+
113
+ with open(args.js_path, "r", encoding="utf-8") as f:
114
+ js = f.read()
115
+
116
+ def read_opt(path):
117
+ if not path:
118
+ return ""
119
+ with open(path, "r", encoding="utf-8") as fh:
120
+ return fh.read()
121
+
122
+ patch_src = read_opt(args.patch)
123
+ init_src = read_opt(args.init)
124
+ trigger_src = read_opt(args.trigger) or "window.__iv8__.eventLoop.drain();"
125
+
126
+ print("目标 JS :", args.js_path)
127
+ print("JS 字节 :", len(js.encode("utf-8")))
128
+ print("预置替身 :", "有(--patch)" if patch_src else "无(复现原始报错)")
129
+
130
+ # prod 模式即可复现(不需要 debug 监控开销)
131
+ with iv8.JSContext(environment=env) as ctx:
132
+ if patch_src:
133
+ ok, _ = run_step(ctx, "inject patch (wrapNative 替身)", patch_src)
134
+ if not ok:
135
+ print("\n替身注入本身就抛错,先修替身。")
136
+ print(WRAPNATIVE_HINT)
137
+ return
138
+
139
+ ok, _ = run_step(ctx, "eval target", js)
140
+ if not ok:
141
+ print(WRAPNATIVE_HINT)
142
+ return
143
+
144
+ if init_src:
145
+ ok, _ = run_step(ctx, "init", init_src)
146
+ if not ok:
147
+ print(WRAPNATIVE_HINT)
148
+ return
149
+
150
+ ok, val = run_step(ctx, "trigger + drain", trigger_src)
151
+ if not ok:
152
+ print(WRAPNATIVE_HINT)
153
+ return
154
+
155
+ print("\n全部步骤跑通,未复现 stub 报错。")
156
+ if patch_src:
157
+ print("→ 替身有效:该 stub 窟窿已补上。")
158
+ else:
159
+ print("→ 目标此路径未触发 stub 窟窿(或缺口在别处)。")
160
+ if isinstance(val, list):
161
+ print(f"trigger 返回条目数: {len(val)}")
162
+
163
+
164
+ if __name__ == "__main__":
165
+ main()