dsh-reverse-plugin 0.0.0-stage → 0.3.1

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/reverse.patch.yml +189 -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,211 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ consistency_lint.py — environment / config 静态拒错器(阶段 P2/P3 护栏)
5
+
6
+ 用途:
7
+ 在把 environment / config 交给 iv8.JSContext 之前做静态体检,
8
+ 在「补环境跑起来」之前就拦掉四类会导致翻车却难查的错误:
9
+ 1) config 里出现数组值 —— iv8 的 config 只接标量(引擎行为,如 timezone/
10
+ permissions.*),画像类字段(可数组、JS 可观测)必须放 environment。
11
+ 2) 画像字段(navigator/screen/webgl/canvas...)被误塞进 config。
12
+ 3) 一致性红线不自洽:UA 里的平台/OS ↔ navigator.platform ↔
13
+ userAgentData.platform ↔ 语言 ↔ 时区 互相矛盾(反爬最常查的交叉项)。
14
+ 4) 检测到 POW/时间敏感特征线索,却没把 time_mode 设成 'system'(给告警)。
15
+
16
+ 本脚本只做静态判定,不会创建 JSContext,因此不需要装 iv8 即可运行。
17
+
18
+ 用法(库调用,推荐):
19
+ from consistency_lint import lint
20
+ problems = lint(environment, config, time_mode="logical")
21
+ # problems 为字符串列表,空列表=通过
22
+
23
+ 用法(命令行):
24
+ python3 scripts/consistency_lint.py env.json config.json [time_mode]
25
+ 退出码 0 = 无问题;非 0 = 有问题(逐条打印到 stderr)。
26
+
27
+ 本文件属于 iv8-env-runtime skill。
28
+ 交叉引用:environment/config 的字段归属与默认值见
29
+ references/config-defaults-cheatsheet.md;
30
+ 一致性红线的完整清单见 references/iv8-api-contract.md。
31
+ """
32
+
33
+ import json
34
+ import sys
35
+
36
+ # environment(画像)专属的顶层键;出现在 config 里即为错放。
37
+ _PROFILE_KEYS = {
38
+ "navigator", "screen", "location", "webgl", "canvas",
39
+ "document", "window", "history", "performance", "plugins",
40
+ "userAgentData", "audio", "fonts",
41
+ }
42
+
43
+
44
+ def _is_array(v):
45
+ return isinstance(v, (list, tuple))
46
+
47
+
48
+ def _walk_config_for_arrays(node, path, problems):
49
+ """递归查 config 中的任何数组值。config 只接标量。"""
50
+ if isinstance(node, dict):
51
+ for k, v in node.items():
52
+ _walk_config_for_arrays(v, "{}.{}".format(path, k) if path else str(k), problems)
53
+ elif _is_array(node):
54
+ problems.append(
55
+ "[config-数组] config['{}'] 是数组,但 config 只接标量引擎行为值;"
56
+ "画像/可数组字段请移到 environment。".format(path))
57
+
58
+
59
+ def _check_config_shape(config, problems):
60
+ if not config:
61
+ return
62
+ if not isinstance(config, dict):
63
+ problems.append("[config-类型] config 必须是 dict(当前 {})。".format(type(config).__name__))
64
+ return
65
+ # 2) 画像字段误塞进 config
66
+ for k in config:
67
+ if k in _PROFILE_KEYS:
68
+ problems.append(
69
+ "[画像错放] config 里出现画像字段 '{}',它属于 environment(JS 可观测);"
70
+ "config 只放引擎行为(timezone/permissions.* 等标量)。".format(k))
71
+ # 1) config 数组值
72
+ _walk_config_for_arrays(config, "", problems)
73
+
74
+
75
+ def _ua_platform_hint(ua):
76
+ """从 UA 字符串粗判操作系统家族,返回 'windows'/'mac'/'linux'/'android'/None。"""
77
+ if not ua:
78
+ return None
79
+ low = ua.lower()
80
+ if "windows" in low or "win64" in low or "win32" in low:
81
+ return "windows"
82
+ if "android" in low: # android 要先于 linux 判(UA 里两者都含 linux)
83
+ return "android"
84
+ if "mac os x" in low or "macintosh" in low:
85
+ return "mac"
86
+ if "linux" in low or "x11" in low:
87
+ return "linux"
88
+ return None
89
+
90
+
91
+ def _navigator_platform_family(platform_str):
92
+ """navigator.platform -> OS 家族。"""
93
+ if not platform_str:
94
+ return None
95
+ low = platform_str.lower()
96
+ if "win" in low:
97
+ return "windows"
98
+ if "mac" in low:
99
+ return "mac"
100
+ if "linux" in low or "x11" in low:
101
+ return "linux"
102
+ if "android" in low or "arm" in low:
103
+ return "android"
104
+ return None
105
+
106
+
107
+ def _check_consistency_redline(env, problems):
108
+ """一致性红线:UA↔platform↔userAgentData.platform↔语言↔时区 自洽。"""
109
+ if not isinstance(env, dict):
110
+ problems.append("[env-类型] environment 必须是 dict(当前 {})。".format(type(env).__name__))
111
+ return
112
+
113
+ nav = env.get("navigator", {}) or {}
114
+ ua = nav.get("userAgent")
115
+ nav_platform = nav.get("platform")
116
+ uad = nav.get("userAgentData", {}) or {}
117
+ uad_platform = uad.get("platform") # 形如 "Windows" / "macOS" / "Linux"
118
+
119
+ ua_fam = _ua_platform_hint(ua)
120
+ nav_fam = _navigator_platform_family(nav_platform)
121
+
122
+ # UA 家族 vs navigator.platform 家族
123
+ if ua_fam and nav_fam and ua_fam != nav_fam:
124
+ problems.append(
125
+ "[红线-OS] navigator.userAgent 指向 {},但 navigator.platform='{}' 指向 {},不自洽。"
126
+ .format(ua_fam, nav_platform, nav_fam))
127
+
128
+ # UA 家族 vs userAgentData.platform
129
+ if ua_fam and uad_platform:
130
+ uad_low = uad_platform.lower()
131
+ uad_fam = ("windows" if "win" in uad_low else
132
+ "mac" if "mac" in uad_low else
133
+ "linux" if "linux" in uad_low else
134
+ "android" if "android" in uad_low else None)
135
+ if uad_fam and uad_fam != ua_fam:
136
+ problems.append(
137
+ "[红线-OS] userAgent 指向 {},但 userAgentData.platform='{}' 指向 {},不自洽。"
138
+ .format(ua_fam, uad_platform, uad_fam))
139
+
140
+ # 语言:navigator.language 应是 navigator.languages 的首项
141
+ language = nav.get("language")
142
+ languages = nav.get("languages")
143
+ if language and _is_array(languages) and languages:
144
+ if languages[0] != language:
145
+ problems.append(
146
+ "[红线-语言] navigator.language='{}' 与 navigator.languages[0]='{}' 不一致。"
147
+ .format(language, languages[0]))
148
+
149
+ # 时区:environment 侧无标准时区字段,时区归 config.timezone。
150
+ # 若 environment 里出现类时区键,提示挪到 config。
151
+ for k in env:
152
+ if "timezone" in str(k).lower():
153
+ problems.append(
154
+ "[红线-时区] environment 里出现 '{}';时区属于 config.timezone(引擎行为),"
155
+ "请挪到 config,并确保与语言/UA 地区自洽。".format(k))
156
+
157
+
158
+ def _detect_time_sensitive(env, config):
159
+ """粗测是否有 POW/时间差校验线索。返回命中的线索列表。"""
160
+ hints = []
161
+ blob = json.dumps({"env": env, "config": config}, ensure_ascii=False).lower()
162
+ for kw in ("pow", "proof_of_work", "proofofwork", "hashcash", "nonce", "difficulty"):
163
+ if kw in blob:
164
+ hints.append(kw)
165
+ return hints
166
+
167
+
168
+ def lint(environment, config=None, time_mode="logical"):
169
+ """静态体检,返回问题字符串列表(空=通过)。不创建 JSContext。"""
170
+ problems = []
171
+ _check_config_shape(config, problems)
172
+ _check_consistency_redline(environment or {}, problems)
173
+
174
+ # 4) 时间敏感却未用 system 时间 —— 告警(不算硬错,但要提示)。
175
+ hints = _detect_time_sensitive(environment or {}, config or {})
176
+ if hints and time_mode != "system":
177
+ problems.append(
178
+ "[告警-时间] 检测到疑似 POW/时间差线索 {},但 time_mode='{}'。"
179
+ "POW/时间差校验应改用 time_mode='system'(否则 Date.now 不反映真实耗时)。"
180
+ .format(hints, time_mode))
181
+
182
+ return problems
183
+
184
+
185
+ def _load_json(path):
186
+ if not path:
187
+ return {}
188
+ with open(path, "r", encoding="utf-8") as f:
189
+ return json.load(f)
190
+
191
+
192
+ def main(argv):
193
+ if len(argv) < 2:
194
+ print("用法:python3 consistency_lint.py env.json [config.json] [time_mode]", file=sys.stderr)
195
+ return 2
196
+ env = _load_json(argv[1])
197
+ config = _load_json(argv[2]) if len(argv) >= 3 else {}
198
+ time_mode = argv[3] if len(argv) >= 4 else "logical"
199
+
200
+ problems = lint(env, config, time_mode=time_mode)
201
+ if not problems:
202
+ print("[consistency_lint][通过] environment/config 静态体检无问题。")
203
+ return 0
204
+ print("[consistency_lint][不通过] 发现 {} 个问题:".format(len(problems)), file=sys.stderr)
205
+ for p in problems:
206
+ print(" - " + p, file=sys.stderr)
207
+ return 1
208
+
209
+
210
+ if __name__ == "__main__":
211
+ sys.exit(main(sys.argv))
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """defaults_audit.py —— P2/P3 桥梁:审计 iv8 的 environment/config 默认值,算出「真正要配的清单」。
4
+
5
+ 作用(对应 SKILL.md 的 P2「monitor∩defaults 交集=要配的清单」):
6
+ 调 iv8.JSContext.get_defaults()(返回全部支持路径及默认值),做两件事:
7
+ 1) 按前缀分组(location / canvas / navigator / screen / webgl / window / document …)
8
+ 打印,并「标出空/占位默认」(''、about:blank、0.0 等)——这些是最可能需要覆盖的必配候选。
9
+ 2) 若给了「目标读过的字段清单」(monitor_env.py 第①类 getter 的输出),
10
+ 与 defaults 求交集 = 目标真正读到、且 iv8 有默认可覆盖的字段 = 真正要配的清单。
11
+
12
+ 典型默认坑(务必核对,见 references/config-defaults-cheatsheet.md):
13
+ - location.href 默认 'about:blank' —— 几乎必配(目标常读 origin/host/href 做校验)
14
+ - canvas.fingerprint.toDataURL.png 默认 '' —— canvas 指纹站必配
15
+ - navigator.* 已有 200+ 默认 —— 通常只需覆盖 userAgent(及联动字段)
16
+
17
+ environment(画像,JS 可观测,可含数组)与 config(引擎行为,仅标量,无数组)是两条独立通道;
18
+ 本审计只帮定位「哪些默认是空壳需要填」,具体填什么值 / 一致性红线(UA↔platform↔时区↔语言↔webgl)
19
+ 见 references/config-defaults-cheatsheet.md 与 references/patching-principles.md。
20
+
21
+ 关系与边界:
22
+ - 上游:scripts/monitor_env.py 的①类 getter 清单是本脚本 --read-fields 的输入。
23
+ - 下游:交集清单 → 填进 assets/env_starter.py 的 environment/config。
24
+ - 一致性静态校验(填错值自动拒)见 scripts/consistency_lint.py。
25
+ - 权威 API 契约见 references/iv8-api-contract.md。
26
+
27
+ 用法:
28
+ python defaults_audit.py # 全量分组 + 标空默认
29
+ python defaults_audit.py --group navigator # 只看某前缀
30
+ python defaults_audit.py --empty-only # 只列空/占位默认(必配候选)
31
+ python defaults_audit.py --read-fields fields.txt # 与目标读过的字段求交集
32
+ fields.txt:每行一个字段路径,如 navigator.userAgent / location.href
33
+ (可直接从 monitor_env.py 第①类输出里摘)
34
+ """
35
+
36
+ import argparse
37
+ import sys
38
+
39
+ try:
40
+ import iv8
41
+ except ImportError:
42
+ sys.exit("未找到 iv8。先跑 scripts/preflight.py 确认安装(安装见 references/cross-platform-install.md)。")
43
+
44
+
45
+ # 视为「空/占位」的默认值 —— 命中即列为必配候选
46
+ _EMPTY_LITERALS = ("", "about:blank", "about://blank")
47
+
48
+
49
+ def is_empty_default(value):
50
+ """判断一个默认值是否为空/占位(很可能需要覆盖)。"""
51
+ if value is None:
52
+ return True
53
+ if isinstance(value, str):
54
+ return value.strip() in _EMPTY_LITERALS
55
+ return False
56
+
57
+
58
+ def group_of(path):
59
+ """取路径的一级前缀作为分组名。"""
60
+ return path.split(".", 1)[0] if "." in path else path
61
+
62
+
63
+ def load_read_fields(path):
64
+ """读取目标读过的字段清单(每行一个路径,# 起始为注释)。"""
65
+ fields = set()
66
+ with open(path, "r", encoding="utf-8") as f:
67
+ for line in f:
68
+ s = line.strip()
69
+ if not s or s.startswith("#"):
70
+ continue
71
+ # 容忍 monitor 输出里带计数前缀,如 " 42 navigator.userAgent"
72
+ token = s.split()[-1]
73
+ fields.add(token)
74
+ return fields
75
+
76
+
77
+ def main():
78
+ ap = argparse.ArgumentParser(description="审计 iv8 默认值,定位必配候选 / 与目标读过字段求交集")
79
+ ap.add_argument("--group", default="", help="只显示该一级前缀(如 navigator / webgl)")
80
+ ap.add_argument("--empty-only", action="store_true", help="只列空/占位默认(必配候选)")
81
+ ap.add_argument("--read-fields", default="", help="目标读过的字段清单文件,求交集")
82
+ args = ap.parse_args()
83
+
84
+ defaults = iv8.JSContext.get_defaults()
85
+ print(f"iv8 get_defaults(): 共 {len(defaults)} 条支持路径\n")
86
+
87
+ # ---- 分组 ----
88
+ groups = {}
89
+ for path in sorted(defaults):
90
+ groups.setdefault(group_of(path), []).append(path)
91
+
92
+ def emit(path):
93
+ val = defaults[path]
94
+ flag = " ⚠必配候选(空/占位)" if is_empty_default(val) else ""
95
+ print(f" {path} = {val!r}{flag}")
96
+
97
+ for gname in sorted(groups):
98
+ if args.group and gname != args.group:
99
+ continue
100
+ rows = groups[gname]
101
+ if args.empty_only:
102
+ rows = [p for p in rows if is_empty_default(defaults[p])]
103
+ if not rows:
104
+ continue
105
+ print(f"[{gname}] ({len(rows)} 条)")
106
+ for path in rows:
107
+ emit(path)
108
+ print()
109
+
110
+ # ---- 与目标读过的字段求交集 ----
111
+ if args.read_fields:
112
+ read = load_read_fields(args.read_fields)
113
+ default_paths = set(defaults)
114
+ # 直接命中 + 前缀命中(目标读 navigator.userAgent,defaults 有该路径)
115
+ hit = sorted(read & default_paths)
116
+ # 目标读了但 defaults 里没有的路径 → 可能是缺失 API / 陷阱,走 trap 纪律
117
+ miss = sorted(read - default_paths)
118
+
119
+ print("=" * 72)
120
+ print("交集(monitor∩defaults)= 目标读到且 iv8 有默认可覆盖 = 真正要配的清单")
121
+ print("=" * 72)
122
+ for path in hit:
123
+ emit(path)
124
+ if not hit:
125
+ print(" (无交集:目标读的字段都不在 defaults 里,见下方 miss)")
126
+
127
+ if miss:
128
+ print("\n" + "-" * 72)
129
+ print("⚠ 目标读了、但 defaults 无此路径 —— 可能是缺失 API / 反爬陷阱:")
130
+ print(" 默认按陷阱处理,除非真机核对确有值。见 references/trap-blacklist.md")
131
+ print("-" * 72)
132
+ for path in miss:
133
+ print(f" {path}")
134
+
135
+ print(
136
+ "\n[下一步] 交集清单填进 assets/env_starter.py 的 environment/config;\n"
137
+ " 填的值做一致性静态校验 → scripts/consistency_lint.py;\n"
138
+ " 值怎么填 / 一致性红线见 references/config-defaults-cheatsheet.md。"
139
+ )
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """monitor_env.py —— P2 发现阶段核心工具:跑一遍目标 JS,抓 iv8 C++ 层监控日志分六类。
4
+
5
+ 作用(对应 SKILL.md 的 P2「起手跑 + 发现缺口」):
6
+ 用 iv8 mode='debug' 加载目标 JS 并触发一次签名/取数,把引擎在 C++ 层记录的
7
+ 「浏览器 API 访问链路 + JS 内置反射路径」实时打到 stdout(fd1)/stderr(fd2),
8
+ 本脚本用 fd 重定向把它落盘再正则解析,按六类打印:
9
+ ① 属性读 getter —— 目标读了哪些指纹字段(配 environment 的清单来源)
10
+ ② 属性写 setter —— 目标改/挂了什么(常见是 XHR.open / fetch 的 hook)
11
+ ③ 方法调用 call
12
+ ④ 存在性探测 query(typeof / in,反爬最爱)
13
+ ⑤ 反射层 —— Object.keys / getOwnPropertyDescriptor / toString / JSON.* 等探测
14
+ ⑥ ⚠ 疑似缺失 API —— 目标摸了但 iv8 未实现(单列,见下方处置纪律)
15
+
16
+ 第⑥类「疑似缺失 API」的处置纪律(贯穿本 skill 的三态原则):
17
+ 默认按「陷阱」处理 —— 绝不无脑补。process / _phantom / __webdriver_script_fn /
18
+ StyleMedia / Float16Array 之类是反爬故意探测的不存在物,补了反而暴露。
19
+ 只有在真机(真实 Chrome)核对确认「真实浏览器里此 API 确有值」时,才配置/补它。
20
+ 详见 references/trap-blacklist.md 与 references/patching-principles.md。
21
+
22
+ 关系与边界:
23
+ - 本脚本只做「发现」:告诉你目标读了什么、探测了什么、摸了哪些缺失物。
24
+ - 「读了什么」→ 拿去 environment 配值,交集算法见 scripts/defaults_audit.py。
25
+ - 抛 TypeError 的 stub 窟窿(如 MessageChannel port=null)→ scripts/reproduce_stub_error.py。
26
+ - stub 替换按 references/patching-principles.md 的 iv8 原生补丁契约执行。
27
+ - 权威 API 契约见 references/iv8-api-contract.md;坑位版本门控见 references/version-gotchas.md。
28
+
29
+ 用法:
30
+ python monitor_env.py <目标JS路径> [--url <触发URL>] [--trigger <触发JS表达式文件>]
31
+ [--env <environment JSON文件>] [--log <日志落盘路径>]
32
+
33
+ 最小用法(零配跑,观察默认环境下都缺什么):
34
+ python monitor_env.py ./target.js
35
+ 带触发(脚本加载后还需调一次才产签名):
36
+ python monitor_env.py ./target.js --trigger ./trigger.js
37
+ trigger.js 内是一段 JS(示例):
38
+ var x = new XMLHttpRequest(); x.open('GET','https://api.example.com/d'); x.send();
39
+ window.__iv8__.eventLoop.drain(); window.__iv8__.netLog.entries;
40
+
41
+ 注意:社区版无真实网络栈,--url 只用于把 URL 拼进默认触发表达式;真请求/响应注入见
42
+ scripts/network_bridge.py 与 references/network-and-eventloop.md。
43
+ """
44
+
45
+ import argparse
46
+ import json
47
+ import os
48
+ import re
49
+ import sys
50
+ from collections import Counter
51
+
52
+ try:
53
+ import iv8
54
+ except ImportError:
55
+ sys.exit("未找到 iv8。先跑 scripts/preflight.py 确认安装(安装见 references/cross-platform-install.md)。")
56
+
57
+
58
+ # ---- 日志正则:匹配 iv8 debug 模式在 C++ 层打印的监控行 ----
59
+ ANSI = re.compile(r"\x1b\[[0-9;]*m")
60
+ RE_INST = re.compile(r"实例访问 - (.+?) -> (getter|setter|call|query)")
61
+ RE_REFL = re.compile(r"反射层 - (.+?) - 目标:([^\[\-]+)")
62
+ RE_MISS = re.compile(r"疑似缺失API - (\S+)")
63
+
64
+
65
+ def build_default_trigger(url):
66
+ """没给 --trigger 时的兜底触发:发一次 XHR + drain + 读 netLog。
67
+
68
+ drain 是「drain-before-read」纪律:社区版异步 XHR 回调不排空就读不到结果。
69
+ 完整事件循环推进语义见 references/network-and-eventloop.md。
70
+ """
71
+ if not url:
72
+ # 纯加载即产签名的目标:不触发,只 drain 一轮微任务
73
+ return "window.__iv8__.eventLoop.drain();"
74
+ safe_url = json.dumps(url)
75
+ return (
76
+ "var __x = new XMLHttpRequest();"
77
+ "__x.open('GET', %s, true);"
78
+ "try { __x.send(null); } catch (e) {}"
79
+ "window.__iv8__.eventLoop.drain();"
80
+ "window.__iv8__.netLog.entries;" % safe_url
81
+ )
82
+
83
+
84
+ def run_and_capture(js_path, trigger_src, env, log_path):
85
+ """在 debug 模式下加载目标并触发一次,把 C++ 监控日志重定向到 log_path。"""
86
+ with open(js_path, "r", encoding="utf-8") as f:
87
+ js = f.read()
88
+
89
+ # fd1 + fd2 重定向到文件,捕获引擎层 debug 输出(Python print 也会进同一文件)
90
+ saved_out, saved_err = os.dup(1), os.dup(2)
91
+ fd = os.open(log_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
92
+ os.dup2(fd, 1)
93
+ os.dup2(fd, 2)
94
+ os.close(fd)
95
+ try:
96
+ # mode='debug' 打开 API 监控;environment 只放 JS 可观测画像(可含数组)
97
+ with iv8.JSContext(environment=env, mode="debug") as ctx:
98
+ ctx.eval(js, name=os.path.basename(js_path))
99
+ if trigger_src:
100
+ ctx.eval(trigger_src, name="__trigger__")
101
+ finally:
102
+ os.dup2(saved_out, 1)
103
+ os.dup2(saved_err, 2)
104
+ os.close(saved_out)
105
+ os.close(saved_err)
106
+
107
+
108
+ def parse_log(log_path):
109
+ """解析监控日志,返回六个 Counter。"""
110
+ reads, writes, calls, queries, refl, missing = (Counter() for _ in range(6))
111
+ total = 0
112
+ with open(log_path, "r", encoding="utf-8", errors="replace") as fh:
113
+ for raw in fh:
114
+ line = ANSI.sub("", raw)
115
+ total += 1
116
+ m = RE_INST.search(line)
117
+ if m:
118
+ api, kind = m.group(1).strip(), m.group(2)
119
+ if "__iv8__" in api: # 工具对象自身不算目标行为
120
+ continue
121
+ {"getter": reads, "setter": writes,
122
+ "call": calls, "query": queries}[kind][api] += 1
123
+ continue
124
+ m = RE_REFL.search(line)
125
+ if m:
126
+ refl[f"{m.group(1).strip()} → {m.group(2).strip()}"] += 1
127
+ continue
128
+ m = RE_MISS.search(line)
129
+ if m:
130
+ missing[m.group(1)] += 1
131
+ return total, reads, writes, calls, queries, refl, missing
132
+
133
+
134
+ def show(title, counter, top):
135
+ print(f"\n{'=' * 72}\n{title}\n 去重 {len(counter)} / 命中 {sum(counter.values())}\n{'=' * 72}")
136
+ for k, v in counter.most_common(top):
137
+ print(f" {v:6d} {k}")
138
+
139
+
140
+ def main():
141
+ ap = argparse.ArgumentParser(description="iv8 debug 监控:跑目标 JS,六类打印 API 访问链路")
142
+ ap.add_argument("js_path", help="目标 JS 文件路径")
143
+ ap.add_argument("--url", default="", help="触发用 URL(拼进默认 XHR 触发表达式)")
144
+ ap.add_argument("--trigger", default="", help="触发 JS 表达式文件路径(覆盖默认触发)")
145
+ ap.add_argument("--env", default="", help="environment 画像 JSON 文件路径(省略=零配跑)")
146
+ ap.add_argument("--log", default="", help="监控日志落盘路径(默认 <js>.monitor.log)")
147
+ args = ap.parse_args()
148
+
149
+ if not os.path.isfile(args.js_path):
150
+ sys.exit(f"目标 JS 不存在: {args.js_path}")
151
+
152
+ env = None
153
+ if args.env:
154
+ with open(args.env, "r", encoding="utf-8") as f:
155
+ env = json.load(f)
156
+
157
+ if args.trigger:
158
+ with open(args.trigger, "r", encoding="utf-8") as f:
159
+ trigger_src = f.read()
160
+ else:
161
+ trigger_src = build_default_trigger(args.url)
162
+
163
+ log_path = args.log or (args.js_path + ".monitor.log")
164
+
165
+ run_and_capture(args.js_path, trigger_src, env, log_path)
166
+ total, reads, writes, calls, queries, refl, missing = parse_log(log_path)
167
+
168
+ print(f"\n日志总行数: {total} (原始: {log_path})")
169
+ show("① 属性读 getter —— 目标读了哪些字段(→ environment 配值清单来源)", reads, 60)
170
+ show("② 属性写 setter —— 目标改/挂了什么(常见 XHR.open / fetch hook)", writes, 30)
171
+ show("③ 方法调用 call —— 目标调了哪些 API", calls, 40)
172
+ show("④ 存在性探测 query(typeof / in,反爬最爱)", queries, 40)
173
+ show("⑤ 反射层 —— Object.keys / getOwnPropertyDescriptor / toString / JSON.*", refl, 30)
174
+ show("⑥ ⚠ 疑似缺失 API(目标摸了但 iv8 未实现)", missing, 80)
175
+ print(
176
+ "\n[⑥ 处置纪律] 默认按陷阱处理,除非真机核对确有值。\n"
177
+ " 绝不无脑补的探测物(process/_phantom/__webdriver_script_fn/StyleMedia/Float16Array 等)\n"
178
+ " 见 references/trap-blacklist.md;三态与补漏原则见 references/patching-principles.md。\n"
179
+ "[下一步] ① 读到的字段 → scripts/defaults_audit.py 求交集算真正要配的;\n"
180
+ " 抛 TypeError 的 stub 窟窿 → scripts/reproduce_stub_error.py。"
181
+ )
182
+
183
+
184
+ if __name__ == "__main__":
185
+ main()