@liang-hz/agent-in-chrome 0.55.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 (112) hide show
  1. package/.ext-id.txt +4 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/PRIVACY.md +86 -0
  5. package/README.en.md +419 -0
  6. package/README.md +406 -0
  7. package/bin/agent-in-chrome.mjs +97 -0
  8. package/commands/agent-in-chrome.md +18 -0
  9. package/commands/install-agent-in-chrome.md +22 -0
  10. package/docs/AGENTS.md +94 -0
  11. package/docs/CLI.md +297 -0
  12. package/docs/client-compat.json +23 -0
  13. package/extension/about-toc.js +25 -0
  14. package/extension/about.html +240 -0
  15. package/extension/about.js +44 -0
  16. package/extension/agent-window.html +100 -0
  17. package/extension/icons/icon-128.png +0 -0
  18. package/extension/icons/icon-16.png +0 -0
  19. package/extension/icons/icon-24.png +0 -0
  20. package/extension/icons/icon-32.png +0 -0
  21. package/extension/icons/icon-48.png +0 -0
  22. package/extension/icons/icon-64.png +0 -0
  23. package/extension/icons/icon-attention-128.png +0 -0
  24. package/extension/icons/icon-attention-16.png +0 -0
  25. package/extension/icons/icon-attention-24.png +0 -0
  26. package/extension/icons/icon-attention-32.png +0 -0
  27. package/extension/icons/icon-attention-48.png +0 -0
  28. package/extension/icons/icon-attention-64.png +0 -0
  29. package/extension/icons/icon-attention.svg +18 -0
  30. package/extension/icons/icon-failed-128.png +0 -0
  31. package/extension/icons/icon-failed-16.png +0 -0
  32. package/extension/icons/icon-failed-24.png +0 -0
  33. package/extension/icons/icon-failed-32.png +0 -0
  34. package/extension/icons/icon-failed-48.png +0 -0
  35. package/extension/icons/icon-failed-64.png +0 -0
  36. package/extension/icons/icon-failed.svg +18 -0
  37. package/extension/icons/icon-idle-128.png +0 -0
  38. package/extension/icons/icon-idle-16.png +0 -0
  39. package/extension/icons/icon-idle-24.png +0 -0
  40. package/extension/icons/icon-idle-32.png +0 -0
  41. package/extension/icons/icon-idle-48.png +0 -0
  42. package/extension/icons/icon-idle-64.png +0 -0
  43. package/extension/icons/icon-idle.svg +18 -0
  44. package/extension/icons/icon-mark.svg +10 -0
  45. package/extension/icons/icon-running-128.png +0 -0
  46. package/extension/icons/icon-running-16.png +0 -0
  47. package/extension/icons/icon-running-24.png +0 -0
  48. package/extension/icons/icon-running-32.png +0 -0
  49. package/extension/icons/icon-running-48.png +0 -0
  50. package/extension/icons/icon-running-64.png +0 -0
  51. package/extension/icons/icon-running.svg +18 -0
  52. package/extension/icons/icon.svg +18 -0
  53. package/extension/manifest.json +44 -0
  54. package/extension/popup-ui.js +38 -0
  55. package/extension/popup.html +350 -0
  56. package/extension/popup.js +741 -0
  57. package/extension/sw.js +11127 -0
  58. package/extension/update-check.js +66 -0
  59. package/extension/welcome.html +110 -0
  60. package/extension/welcome.js +18 -0
  61. package/mcp/agent-identity.mjs +1007 -0
  62. package/mcp/cdp/bridge.mjs +239 -0
  63. package/mcp/cdp/browser-launch.mjs +1127 -0
  64. package/mcp/cdp/chrome-shim.mjs +1124 -0
  65. package/mcp/cdp/client.mjs +443 -0
  66. package/mcp/cli-invocation.mjs +67 -0
  67. package/mcp/config.mjs +191 -0
  68. package/mcp/foreground-guard.mjs +295 -0
  69. package/mcp/proc-win.mjs +112 -0
  70. package/mcp/secret-shape.mjs +155 -0
  71. package/mcp/server.mjs +3437 -0
  72. package/mcp/session-id.mjs +281 -0
  73. package/mcp/token.mjs +260 -0
  74. package/mcp/tool-tiers.mjs +84 -0
  75. package/mcp/trace.mjs +528 -0
  76. package/mcp/update-cli.mjs +163 -0
  77. package/mcp/update-notice.mjs +194 -0
  78. package/native-host/host.mjs +356 -0
  79. package/native-host/mac-foreground/aic-fg.swift +114 -0
  80. package/native-host/mac-foreground/build.mjs +43 -0
  81. package/package.json +46 -0
  82. package/scripts/agents.mjs +921 -0
  83. package/scripts/borrow-login.mjs +935 -0
  84. package/scripts/cli-browser.mjs +148 -0
  85. package/scripts/e2e-sweep.mjs +192 -0
  86. package/scripts/e2e.mjs +3911 -0
  87. package/scripts/fixture-server.mjs +1419 -0
  88. package/scripts/guard-publish.mjs +175 -0
  89. package/scripts/install.mjs +1383 -0
  90. package/scripts/launcher-provenance.mjs +74 -0
  91. package/scripts/pack-crx.mjs +82 -0
  92. package/scripts/pick.mjs +114 -0
  93. package/scripts/test-agents.mjs +968 -0
  94. package/scripts/test-borrow.mjs +289 -0
  95. package/scripts/test-config.mjs +618 -0
  96. package/scripts/test-e2e-sweep.mjs +251 -0
  97. package/scripts/test-foreground-guard.mjs +383 -0
  98. package/scripts/test-identity.mjs +1141 -0
  99. package/scripts/test-install-skill.mjs +378 -0
  100. package/scripts/test-protocol.mjs +712 -0
  101. package/scripts/test-security.mjs +1360 -0
  102. package/scripts/test-sw.mjs +14526 -0
  103. package/scripts/test-update.mjs +301 -0
  104. package/skills/agent-in-chrome/SKILL.md +60 -0
  105. package/skills/agent-in-chrome/references/actions-and-waits.md +136 -0
  106. package/skills/agent-in-chrome/references/amap-dir-dropdown.md +66 -0
  107. package/skills/agent-in-chrome/references/geetest-click-captcha.md +55 -0
  108. package/skills/agent-in-chrome/references/network-debugging.md +20 -0
  109. package/skills/agent-in-chrome/references/reading-pages.md +30 -0
  110. package/skills/agent-in-chrome/references/recovery.md +25 -0
  111. package/skills/agent-in-chrome/references/tabs-and-sessions.md +34 -0
  112. package/skills/install-agent-in-chrome/SKILL.md +252 -0
@@ -0,0 +1,1419 @@
1
+ #!/usr/bin/env node
2
+
3
+ import http from "node:http";
4
+ import crypto from "node:crypto";
5
+
6
+ const PORT = Number(process.argv[2] || 0);
7
+ const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
8
+
9
+ const FORM_SUBMITS = [];
10
+
11
+ function encodeFrame(payload, opcode = 1) {
12
+ const data = Buffer.from(payload, "utf8");
13
+ const len = data.length;
14
+ let header;
15
+ if (len < 126) {
16
+ header = Buffer.from([0x80 | opcode, len]);
17
+ } else if (len < 65536) {
18
+ header = Buffer.alloc(4);
19
+ header[0] = 0x80 | opcode;
20
+ header[1] = 126;
21
+ header.writeUInt16BE(len, 2);
22
+ } else {
23
+ header = Buffer.alloc(10);
24
+ header[0] = 0x80 | opcode;
25
+ header[1] = 127;
26
+ header.writeBigUInt64BE(BigInt(len), 2);
27
+ }
28
+ return Buffer.concat([header, data]);
29
+ }
30
+
31
+ function decodeFrames(buf) {
32
+ const out = [];
33
+ let off = 0;
34
+ while (off + 2 <= buf.length) {
35
+ const b0 = buf[off];
36
+ const b1 = buf[off + 1];
37
+ const opcode = b0 & 0x0f;
38
+ const masked = (b1 & 0x80) !== 0;
39
+ let len = b1 & 0x7f;
40
+ let p = off + 2;
41
+ if (len === 126) {
42
+ if (p + 2 > buf.length) break;
43
+ len = buf.readUInt16BE(p);
44
+ p += 2;
45
+ } else if (len === 127) {
46
+ if (p + 8 > buf.length) break;
47
+ len = Number(buf.readBigUInt64BE(p));
48
+ p += 8;
49
+ }
50
+ let mask = null;
51
+ if (masked) {
52
+ if (p + 4 > buf.length) break;
53
+ mask = buf.subarray(p, p + 4);
54
+ p += 4;
55
+ }
56
+ if (p + len > buf.length) break;
57
+ const payload = Buffer.from(buf.subarray(p, p + len));
58
+ if (mask) for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4];
59
+ out.push({ opcode, payload: payload.toString("utf8") });
60
+ off = p + len;
61
+ }
62
+ return { frames: out, rest: buf.subarray(off) };
63
+ }
64
+
65
+ function framePage(id, nest, nestSandbox, autopost) {
66
+ const inner = nest
67
+ ? `<iframe id="inner"${nestSandbox ? ' sandbox="allow-scripts"' : ""} src="${nest}" style="width:96%;height:110px;border:1px dotted #999"></iframe>`
68
+ : "";
69
+ return (
70
+ `<!doctype html><meta charset="utf-8"><body style="font:14px sans-serif;margin:6px">` +
71
+ `<p id="frame-text">我在 iframe 里(${id})</p>` +
72
+ `<button id="frame-btn">iframe 内的按钮 ${id}</button>` +
73
+ `<input id="frame-file" type="file">` +
74
+ `<input id="frame-input" placeholder="帧内文本框 ${id}">` +
75
+ `<button id="frame-upload">帧内提交 ${id}</button>` +
76
+ `<div id="frame-log">未点击</div>` +
77
+ `<div id="frame-file-log">未选择</div>${inner}` +
78
+ `<script>
79
+ var ID=${JSON.stringify(id)};
80
+ var up=function(v){ try{ parent.postMessage({aicUpload:ID+':'+v},'*'); }catch(e){} };
81
+ document.getElementById('frame-btn').onclick=function(){
82
+ document.getElementById('frame-log').textContent='frame-clicked';
83
+ try{ parent.postMessage({aicClick:ID},'*'); }catch(e){}
84
+ };
85
+ document.getElementById('frame-file').onchange=function(e){
86
+ var names=[].map.call(e.target.files,function(f){return f.name+'@'+f.size}).join(',');
87
+ document.getElementById('frame-file-log').textContent='frame-file:'+names;
88
+ up('change:'+names);
89
+ // autopost=1 的帧收到文件就自己发出去。
90
+ // 为什么要这条路:端到端断言(服务端收到的字节 == 本机文件)只该依赖
91
+ // 「文件真进了这个帧」,不该顺带依赖「合成点击能不能打进这个帧」——
92
+ // 后者是另一层的事,在隔离测试浏览器里本来就不稳。
93
+ if (${autopost ? "true" : "false"}) document.getElementById('frame-upload').click();
94
+ };
95
+ document.getElementById('frame-upload').onclick=function(){
96
+ var i=document.getElementById('frame-file');
97
+ if(!i.files.length){ up('nofile'); return; }
98
+ var fd=new FormData();
99
+ for(var k=0;k<i.files.length;k++) fd.append('frame-'+ID, i.files[k], i.files[k].name);
100
+ fetch('/upload',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){
101
+ document.getElementById('frame-log').textContent='frame-uploaded:'+d.count;
102
+ up('posted:'+d.files.map(function(f){return f.filename+'@'+f.size}).join(','));
103
+ }).catch(function(err){ up('post-error:'+err.message); });
104
+ };
105
+ // 内层帧的消息往上传,最终到顶层页面
106
+ addEventListener('message',function(e){
107
+ if(e.data&&(e.data.aicClick||e.data.aicUpload)&&parent!==window){ try{ parent.postMessage(e.data,'*'); }catch(err){} }
108
+ });
109
+ <\/script>`
110
+ );
111
+ }
112
+
113
+ const HARD_FRAMES = `<!doctype html>
114
+ <meta charset="utf-8">
115
+ <title>跨帧寻址测试页</title>
116
+ <style>
117
+ body { font: 14px/1.5 -apple-system, "PingFang SC", sans-serif; margin: 16px; }
118
+ iframe { width: 320px; height: 84px; border: 1px solid #ccc; vertical-align: top; }
119
+ .cell { display: inline-block; margin: 6px; }
120
+ </style>
121
+ <h1>跨帧寻址</h1>
122
+ <div id="report">无</div>
123
+ <div id="upload-report">无</div>
124
+ <div class="cell"><iframe id="dupA" src="__ALT__/frame?id=dup"></iframe></div>
125
+ <div class="cell"><iframe id="dupB" src="__ALT__/frame?id=dup"></iframe></div>
126
+ <div class="cell"><iframe id="nav" src="__ALT__/frame?id=nav-before"></iframe></div>
127
+ <div class="cell"><iframe id="sd" srcdoc="&lt;body style='margin:4px;font:13px sans-serif'&gt;&lt;button id='b'&gt;srcdoc 按钮&lt;/button&gt;&lt;script&gt;document.getElementById('b').onclick=function(){parent.postMessage({aicClick:'srcdoc'},'*')}&lt;/scr&#105;pt&gt;"></iframe></div>
128
+ <div class="cell"><iframe id="sbx" sandbox="allow-scripts" srcdoc="&lt;body style='margin:4px;font:13px sans-serif'&gt;&lt;button id='b'&gt;sandbox 按钮&lt;/button&gt;&lt;script&gt;document.getElementById('b').onclick=function(){parent.postMessage({aicClick:'sandbox'},'*')}&lt;/scr&#105;pt&gt;"></iframe></div>
129
+ <div class="cell"><iframe id="blank"></iframe></div>
130
+ <div class="cell" style="width:340px"><iframe id="deepx" src="__ALT__/frame?id=xouter&amp;nest=__SELF__/frame%3Fid%3Ddeep-inner" style="height:150px"></iframe></div>
131
+ <div class="cell" style="position:relative">
132
+ <iframe id="covered" src="__ALT__/frame?id=covered"></iframe>
133
+ <div id="cover" style="position:absolute;inset:0;background:rgba(255,0,0,.25)"></div>
134
+ </div>
135
+ <!-- sandbox 不带 allow-same-origin ⇒ 不透明源 ⇒ Chrome 把它放进独立进程(OOPIF)。
136
+ 真实站点上的第三方嵌入(YouTube / Stripe / reCAPTCHA)都是这个形态,
137
+ 而本地「换个端口」造出来的跨源帧**不是** —— 端口不同但仍是同一个 site,同进程。
138
+ OOPIF 才是真正难啃的:CDP 的 Page.getFrameTree 看不见它,
139
+ DOM.getNodeForLocation 也穿不进去(命中的是承载它的 <iframe> 元素本身)。 -->
140
+ <div class="cell" style="position:relative">
141
+ <iframe id="oopif" sandbox="allow-scripts" src="__ALT__/frame?id=oopif"></iframe>
142
+ </div>
143
+ <!-- 收到文件就自己 POST 的 OOPIF:端到端断言不必依赖合成点击能不能打进跨进程帧 -->
144
+ <div class="cell"><iframe id="oopifpost" sandbox="allow-scripts" src="__ALT__/frame?id=oopif-post&amp;autopost=1"></iframe></div>
145
+ <!-- OOPIF 里再套一个 sandbox 帧:跨进程会话里还嵌着帧,
146
+ 只在最外层会话的主框架里找元素是找不到它的。上传要覆盖这条路。 -->
147
+ <div class="cell" style="width:340px;height:230px">
148
+ <iframe id="oopif2" sandbox="allow-scripts"
149
+ src="__ALT__/frame?id=oopif-outer&amp;nest=__SELF__/frame%3Fid%3Doopif-inner&amp;nestsbx=1"
150
+ style="height:220px"></iframe>
151
+ </div>
152
+ <div class="cell" style="position:relative">
153
+ <iframe id="coveredx" sandbox="allow-scripts" src="__ALT__/frame?id=coveredx"></iframe>
154
+ <div id="coverx" style="position:absolute;inset:0;background:rgba(0,0,255,.25)"></div>
155
+ </div>
156
+ <div class="cell" style="width:340px;height:120px"><iframe id="rot" src="__ALT__/frame?id=rot" style="transform:rotate(12deg)"></iframe></div>
157
+ <div class="cell" style="width:340px;height:120px"><iframe id="scaled" src="__ALT__/frame?id=scaled" style="transform:scale(.5);transform-origin:top left"></iframe></div>
158
+ <iframe id="hiddenf" src="__ALT__/frame?id=hiddenf" style="display:none"></iframe>
159
+ <script>
160
+ const sources = [];
161
+ addEventListener('message', (e) => {
162
+ // 帧内上传的回报(change 跑了 / 文件 POST 出去了)。OOPIF 的 contentDocument
163
+ // 顶层读不到,只有这条消息通道能证明「文件真进了那个帧」
164
+ if (e.data && e.data.aicUpload) {
165
+ const u = document.getElementById('upload-report');
166
+ u.textContent = u.textContent === '无' ? e.data.aicUpload : u.textContent + ',' + e.data.aicUpload;
167
+ return;
168
+ }
169
+ if (!e.data || !e.data.aicClick) return;
170
+ let who = e.data.aicClick;
171
+ // 两个 dup 帧内容一模一样,报上来的 id 也一样,只能靠 window 引用认人
172
+ if (who === 'dup') {
173
+ who = e.source === document.getElementById('dupA').contentWindow ? 'dupA'
174
+ : e.source === document.getElementById('dupB').contentWindow ? 'dupB'
175
+ : 'dup-unknown';
176
+ }
177
+ const el = document.getElementById('report');
178
+ el.textContent = el.textContent === '无' ? who : el.textContent + ',' + who;
179
+ });
180
+ window.aicReset = () => {
181
+ document.getElementById('report').textContent = '无';
182
+ document.getElementById('upload-report').textContent = '无';
183
+ return 'reset';
184
+ };
185
+ for (const id of ['cover', 'coverx']) {
186
+ document.getElementById(id).onclick = () => {
187
+ const el = document.getElementById('report');
188
+ el.textContent = el.textContent === '无' ? id : el.textContent + ',' + id;
189
+ };
190
+ }
191
+ // about:blank 帧:内容由 JS 写进去,没有任何 URL 可供配对
192
+ {
193
+ const d = document.getElementById('blank').contentDocument;
194
+ d.body.style.cssText = 'margin:4px;font:13px sans-serif';
195
+ const b = d.createElement('button');
196
+ b.textContent = 'about:blank 按钮';
197
+ b.onclick = () => parent.postMessage({ aicClick: 'blank' }, '*');
198
+ d.body.appendChild(b);
199
+ }
200
+ // 加载完成后自己跳到另一个地址:此后 src 属性与实际地址永久对不上
201
+ document.getElementById('nav').onload = function () {
202
+ if (this.dataset.done) return;
203
+ this.dataset.done = '1';
204
+ this.contentWindow.location.replace('__ALT__/frame?id=nav-after');
205
+ };
206
+ <\/script>
207
+ `;
208
+
209
+ const FORMS = `<!doctype html>
210
+ <meta charset="utf-8">
211
+ <title>表单大全</title>
212
+ <style>
213
+ body { font: 14px/1.7 -apple-system, "PingFang SC", sans-serif; margin: 16px; max-width: 900px; }
214
+ label { display: block; margin: 6px 0; }
215
+ .row { display: flex; gap: 8px; align-items: center; }
216
+ fieldset { margin: 10px 0; }
217
+ #result { white-space: pre-wrap; background: #f6f6f6; padding: 8px; }
218
+ .floating { position: relative; }
219
+ .floating span { position: absolute; top: -8px; left: 6px; background: #fff; font-size: 11px; }
220
+ </style>
221
+ <h1>表单大全</h1>
222
+ <!-- browser_cdp 直发 Input.* 的靶子。放在 <form> 外面(免得点击顺带提交表单)、
223
+ 放在页面最上面(直发的坐标是视口坐标,靶子滚出视口就打不到)。
224
+ 计数器由页面自己记:断言要断「页面真的收到了事件」,不是断工具的返回值 -->
225
+ <p><button type="button" id="rawtarget" style="padding:8px 24px">直发点击靶子</button>
226
+ <span id="rawcount">0</span></p>
227
+ <script>
228
+ document.getElementById("rawtarget").addEventListener("click", () => {
229
+ const n = document.getElementById("rawcount");
230
+ n.textContent = String(Number(n.textContent) + 1);
231
+ });
232
+ </script>
233
+ <form id="f" action="/form-submit" method="post">
234
+ <fieldset><legend>文本类</legend>
235
+ <label>姓名 <input name="name" id="name"></label>
236
+ <label>邮箱 <input type="email" name="email" id="email"></label>
237
+ <label>密码 <input type="password" name="password" id="password" autocomplete="new-password"></label>
238
+ <label>数字 <input type="number" name="qty" id="qty" min="1" max="99" step="1"></label>
239
+ <label>电话 <input type="tel" name="tel" id="tel"></label>
240
+ <label>网址 <input type="url" name="site" id="site"></label>
241
+ <label>搜索 <input type="search" name="q" id="q"></label>
242
+ <label>备注 <textarea name="memo" id="memo" rows="2"></textarea></label>
243
+ <label>带 datalist <input name="fruit" id="fruit" list="fruits"></label>
244
+ <datalist id="fruits"><option value="苹果"><option value="香蕉"></datalist>
245
+ <div class="floating"><span>浮动标签</span><input name="floating" id="floating" placeholder=" "></div>
246
+ <label>只读 <input name="ro" id="ro" value="改不动" readonly></label>
247
+ <label>禁用 <input name="off" id="off" value="禁用的" disabled></label>
248
+ </fieldset>
249
+
250
+ <fieldset><legend>特殊输入</legend>
251
+ <label>日期 <input type="date" name="date" id="date"></label>
252
+ <label>时间 <input type="time" name="time" id="time"></label>
253
+ <label>日期时间 <input type="datetime-local" name="dt" id="dt"></label>
254
+ <label>月份 <input type="month" name="month" id="month"></label>
255
+ <label>周 <input type="week" name="week" id="week"></label>
256
+ <label>颜色 <input type="color" name="color" id="color" value="#000000"></label>
257
+ <label>滑块 <input type="range" name="level" id="level" min="0" max="10" step="1" value="0"></label>
258
+ </fieldset>
259
+
260
+ <fieldset><legend>选择类</legend>
261
+ <label>城市
262
+ <select name="city" id="city">
263
+ <option value="">请选择</option>
264
+ <option value="bj">北京</option>
265
+ <option value="sh">上海</option>
266
+ <option value="gz" disabled>广州(暂不可选)</option>
267
+ </select>
268
+ </label>
269
+ <label>分组下拉
270
+ <select name="grouped" id="grouped">
271
+ <optgroup label="华北"><option value="bj2">北京市</option></optgroup>
272
+ <optgroup label="华东"><option value="sh2">上海市</option><option value="hz2">杭州市</option></optgroup>
273
+ </select>
274
+ </label>
275
+ <label>多选
276
+ <select name="tags" id="tags" multiple size="3">
277
+ <option value="a">甲</option><option value="b">乙</option><option value="c">丙</option>
278
+ </select>
279
+ </label>
280
+ <label class="row"><input type="checkbox" name="agree" id="agree" value="yes"> 同意条款</label>
281
+ <label class="row"><input type="checkbox" name="news" id="news" value="on" checked> 订阅(默认已勾)</label>
282
+ <fieldset><legend>套餐</legend>
283
+ <label class="row"><input type="radio" name="plan" id="plan-free" value="free"> 免费版</label>
284
+ <label class="row"><input type="radio" name="plan" id="plan-pro" value="pro"> 专业版</label>
285
+ </fieldset>
286
+ <label class="row"><span id="switch" role="switch" aria-checked="false" tabindex="0"
287
+ onclick="this.setAttribute('aria-checked', this.getAttribute('aria-checked')==='true'?'false':'true');document.getElementById('switchVal').value=this.getAttribute('aria-checked')">开关(role=switch)</span></label>
288
+ <input type="hidden" name="switchVal" id="switchVal" value="false">
289
+ </fieldset>
290
+
291
+ <fieldset><legend>富文本 / 影子 / 帧</legend>
292
+ <label>可编辑区
293
+ <div id="rich" contenteditable="true" style="border:1px solid #ccc;min-height:32px;padding:4px"></div>
294
+ </label>
295
+ <input type="hidden" name="rich" id="richVal">
296
+ <!-- 裸 contenteditable(不写值):HTML 允许,真实站点上很常见,而 read_page 的
297
+ 候选选择器以前只认 ="true",于是这类编辑区一个都读不到。占位文字用
298
+ data-placeholder(Quill / ProseMirror 一类编辑器的惯例),顺带钉住
299
+ 「可访问名为空时退回 data-placeholder」那条 -->
300
+ <label>裸可编辑区
301
+ <div id="bare" contenteditable data-placeholder="备注(裸 contenteditable)"
302
+ style="border:1px solid #ccc;min-height:32px;padding:4px"></div>
303
+ </label>
304
+ <input type="hidden" name="bare" id="bareVal">
305
+ <!-- 反面:contenteditable="false" 不该进元素表。它和上面那个只差一个属性值,
306
+ 收得太宽(比如按 el.isContentEditable 收)就会把它一起捞进来 -->
307
+ <div id="noedit" contenteditable="false" style="border:1px dashed #ccc;padding:4px">这块不可编辑</div>
308
+ <div id="sd-host"></div>
309
+ <input type="hidden" name="shadow" id="shadowVal">
310
+ </fieldset>
311
+
312
+ <button type="submit" id="submit">提交表单</button>
313
+ </form>
314
+ <div id="result">未提交</div>
315
+ <script>
316
+ // shadow DOM 里也放一个输入框:跨 shadow 边界填表是很常见的一类(设计系统组件)
317
+ const host = document.getElementById("sd-host").attachShadow({ mode: "open" });
318
+ host.innerHTML = '<label>影子里的输入框 <input id="shadow-input"></label>';
319
+ host.getElementById("shadow-input").addEventListener("input", (e) => {
320
+ document.getElementById("shadowVal").value = e.target.value;
321
+ });
322
+ document.getElementById("rich").addEventListener("input", (e) => {
323
+ document.getElementById("richVal").value = e.target.textContent;
324
+ });
325
+ document.getElementById("bare").addEventListener("input", (e) => {
326
+ document.getElementById("bareVal").value = e.target.textContent;
327
+ });
328
+ // 用 fetch 提交,好把服务端**真正收到的**东西显示出来
329
+ document.getElementById("f").addEventListener("submit", async (e) => {
330
+ e.preventDefault();
331
+ const fd = new FormData(e.target);
332
+ const res = await fetch("/form-submit", { method: "POST", body: new URLSearchParams(fd) });
333
+ document.getElementById("result").textContent = await res.text();
334
+ });
335
+ </script>
336
+ `;
337
+
338
+ const ADOPT = `<!doctype html>
339
+ <meta charset="utf-8">
340
+ <title>能力采纳测试页</title>
341
+ <style>
342
+ body { font: 14px/1.6 -apple-system, "PingFang SC", sans-serif; margin: 16px; }
343
+ /* 纯 CSS 驱动的下拉:合成 mouseover 打不开它,只有真的移过去才行 */
344
+ #menu-host { display: inline-block; position: relative; }
345
+ #menu-panel { display: none; position: absolute; top: 24px; left: 0; background: #fff; border: 1px solid #333; padding: 8px; }
346
+ #menu-host:hover #menu-panel { display: block; }
347
+ .row { margin: 2px 0; }
348
+ </style>
349
+ <h1 id="adopt-title">能力采纳</h1>
350
+
351
+ <div id="shadow-host"></div>
352
+ <script>
353
+ // 页面顶部就放一个 shadow root:窗口再矮也够得着,
354
+ // 「CDP 能不能穿 shadow DOM」这条断言才不会被窗口高度左右
355
+ const sh = document.getElementById("shadow-host").attachShadow({ mode: "open" });
356
+ sh.innerHTML = '<button id="in-shadow">影子里的确认</button>';
357
+ </script>
358
+
359
+ <div id="menu-host"><span id="menu-trigger">更多操作</span>
360
+ <div id="menu-panel"><button id="hidden-action">悬停才出现的删除</button></div>
361
+ </div>
362
+
363
+ <form id="f" onsubmit="return false">
364
+ <input id="who" placeholder="姓名">
365
+ <input id="tel" placeholder="手机号">
366
+ <input id="card" placeholder="卡号" autocomplete="cc-number" value="4111111111111111">
367
+ <input id="cvv" placeholder="安全码" autocomplete="cc-csc" value="321">
368
+ <input id="pw" type="password" placeholder="密码" value="hunter2">
369
+ <input id="addr" placeholder="地址" autocomplete="street-address" value="北京市朝阳区">
370
+ <button id="submitBtn" type="button" onclick="document.getElementById('done').textContent='提交成功 ' + document.getElementById('who').value + '/' + document.getElementById('tel').value">提交表单</button>
371
+ </form>
372
+ <div id="done">未提交</div>
373
+
374
+ <button id="hitApi" onclick="fetch('/api/user').then(r=>r.json()).then(j=>{document.getElementById('apiOut').textContent=j.marker})">调接口</button>
375
+ <div id="apiOut">未调用</div>
376
+
377
+ <div id="rows"></div>
378
+ <button id="deep-target">深处的应用筛选</button>
379
+ <script>
380
+ // 300 个可交互元素排在目标前面:read_page 默认上限 200,目标必然拿不到 ref
381
+ const rows = document.getElementById("rows");
382
+ for (let i = 0; i < 300; i++) {
383
+ const b = document.createElement("button");
384
+ b.className = "row";
385
+ b.textContent = "列表行 " + i;
386
+ rows.appendChild(b);
387
+ }
388
+ </script>
389
+ `;
390
+
391
+ const MODALS_OOPIF = `<!doctype html>
392
+ <meta charset="utf-8">
393
+ <title>跨进程浮层测试页</title>
394
+ <style>
395
+ body { font: 14px/1.6 -apple-system, "PingFang SC", sans-serif; margin: 16px; }
396
+ button { font: inherit; padding: 5px 10px; }
397
+ iframe { border: 0; }
398
+ /* 铺满视口:真实的跨站同意平台就是拿一个满屏 iframe 盖住整页 */
399
+ #consent { position: fixed; inset: 0; width: 100%; height: 100%; }
400
+ #widget { position: fixed; right: 12px; bottom: 12px; width: 200px; height: 120px; }
401
+ #veiled { position: absolute; left: 20px; top: 300px; width: 260px; height: 140px; }
402
+ #veil { position: absolute; left: 20px; top: 300px; width: 260px; height: 140px; background: rgba(255,0,0,.25); }
403
+ .pad { height: 900px; }
404
+ </style>
405
+ <h1 id="oopif-title">跨进程浮层</h1>
406
+ <div id="modal-log">未触发</div>
407
+ <button id="under">浮层底下的按钮</button>
408
+ <div class="pad"></div>
409
+
410
+ <iframe id="veiled" sandbox="allow-scripts" src="__ALT__/modal-oopif-frame?id=veiled"></iframe>
411
+ <div id="veil"></div>
412
+ <iframe id="widget" sandbox="allow-scripts" src="__ALT__/modal-oopif-frame?id=widget"></iframe>
413
+ <iframe id="consent" sandbox="allow-scripts" src="__ALT__/modal-oopif-frame?id=consent"></iframe>
414
+ <script>
415
+ // 帧是不透明源,读不到它的 contentDocument——断言只能靠它自己 postMessage 上来的这条。
416
+ // 这也正是「拿页面自己记下来的状态做断言」在跨进程场景下的唯一形态
417
+ addEventListener('message', function (e) {
418
+ if (!e.data || !e.data.aicModal) return;
419
+ var el = document.getElementById('modal-log');
420
+ el.textContent = el.textContent === '未触发' ? e.data.aicModal : el.textContent + ',' + e.data.aicModal;
421
+ });
422
+ document.getElementById('under').onclick = function () {
423
+ var el = document.getElementById('modal-log');
424
+ el.textContent = el.textContent === '未触发' ? 'under-clicked' : el.textContent + ',under-clicked';
425
+ };
426
+ <\/script>
427
+ `;
428
+
429
+ function modalOopifFrame(id) {
430
+ return (
431
+ `<!doctype html><meta charset="utf-8"><title>oopif-${id}</title>` +
432
+ `<style>html,body{margin:0;font:13px sans-serif}` +
433
+ `#d{position:fixed;inset:0;background:#eef;padding:8px}</style>` +
434
+ `<div id="d" role="dialog" aria-modal="true"><h2>跨进程的${
435
+ id === "consent" ? "同意浮层" : id === "widget" ? "客服浮窗" : "遮住的浮层"
436
+ }</h2>` +
437
+ `<button id="ok">${id}-确认</button></div>` +
438
+ `<script>
439
+ document.getElementById('ok').onclick=function(){
440
+ document.title='${id}-ok-clicked';
441
+ try{ parent.postMessage({aicModal:'${id}-ok-clicked'},'*'); }catch(e){}
442
+ };
443
+ <\/script>`
444
+ );
445
+ }
446
+
447
+ const MODALS = `<!doctype html>
448
+ <meta charset="utf-8">
449
+ <title>模态浮层测试页</title>
450
+ <style>
451
+ body { font: 14px/1.6 -apple-system, "PingFang SC", sans-serif; margin: 16px; }
452
+ button { font: inherit; padding: 5px 10px; margin: 3px 5px 3px 0; }
453
+ /* 刻意不写 z-index:整条祖先链都靠 DOM 顺序堆叠。
454
+ 实测悉尼大学那个弹窗就是这样(容器 position:fixed 但 z-index:auto),
455
+ 任何靠 z-index 判模态的逻辑都会漏掉它 */
456
+ #sheet-wrap { position: fixed; inset: 0; background: rgba(0,0,0,.45); display: none; }
457
+ #sheet-wrap.on { display: block; }
458
+ /* 刻意**不给它 id**:真实站点的浮层壳子多半没有稳定 id(悉尼大学那个就没有),
459
+ activeDialog.container 只能从 ARIA 属性推出来,那条分支才被测到 */
460
+ .sheet { background: #fff; margin: 40px auto; padding: 16px; max-width: 420px; }
461
+ #banner { position: fixed; left: 0; right: 0; bottom: 0; background: #ffe; border-top: 1px solid #cc9; padding: 6px 10px; }
462
+ #banner.off { display: none; }
463
+ /* 一直藏着的那个:不能被报出来 */
464
+ #ghost { display: none; }
465
+ .pad { height: 900px; background: linear-gradient(#fff,#eee); }
466
+ </style>
467
+ <h1 id="modals-title">模态浮层</h1>
468
+ <div id="modal-log">未触发</div>
469
+
470
+ <button id="open-sheet">打开满屏浮层</button>
471
+ <button id="open-native">打开原生 dialog</button>
472
+ <button id="open-shadow">打开影子里的浮层</button>
473
+ <button id="plain">什么都不开的普通按钮</button>
474
+ <button id="under-sheet">浮层底下的按钮</button>
475
+
476
+ <!-- ① cookie 横幅:一开始就在,role=dialog 但 aria-modal="false" -->
477
+ <div id="banner" role="dialog" aria-modal="false" aria-label="Cookie 偏好">
478
+ <span>我们使用 Cookie。</span>
479
+ <button id="banner-ok">同意</button>
480
+ <button id="banner-close">关闭横幅</button>
481
+ </div>
482
+
483
+ <!-- ② 满屏浮层。role=dialog + aria-modal=true,标题在 <h2> 里(不是 aria-label),
484
+ 这样才能验证「标题取的是标题,不是整段正文糊成一团」 -->
485
+ <div id="sheet-wrap"><div class="sheet" role="dialog" aria-modal="true">
486
+ <h2>请选择你的偏好</h2>
487
+ <p>这一段是浮层正文,故意排在标题后面,好证明标题不是拿 innerText 前几十字凑的。</p>
488
+ <button id="sheet-a">本地学生</button>
489
+ <button id="sheet-b">国际学生</button>
490
+ <button id="sheet-c">2026 年入学</button>
491
+ <button id="sheet-d">2027 年入学</button>
492
+ <button id="sheet-ok">确认偏好</button>
493
+ <button id="sheet-cancel">取消</button>
494
+ </div></div>
495
+
496
+ <!-- ③ 原生 dialog:showModal() 开的,:modal 认得出来 -->
497
+ <dialog id="native"><h3>原生对话框</h3><button id="native-ok">原生确认</button><button id="native-close">关掉</button></dialog>
498
+
499
+ <!-- ④ shadow DOM 里的浮层 -->
500
+ <div id="shadow-modal-host"></div>
501
+
502
+ <!-- ⑤ 永远藏着的浮层壳子 -->
503
+ <div id="ghost" role="dialog" aria-modal="true" aria-label="不该被看见的浮层"><button id="ghost-btn">幽灵按钮</button></div>
504
+
505
+ <!-- ⑥ iframe 里的浮层:cookie 同意平台、支付确认、客服窗口十有八九都是这形态。
506
+ 判定必须逐帧跑(read_page 本来就是 inAllFrames),ref 要带 @fN。
507
+ 它盖满自己那个小帧,所以 coverage 是 100——正因如此,跨帧排序里
508
+ **顶层帧要优先**,不然一个 300×160 的帧就能盖过真正拦住整页的那个 -->
509
+ <iframe id="dlgframe" src="/modal-frame" style="width:320px;height:160px;border:1px dashed #99f"></iframe>
510
+
511
+ <div class="pad">这一大块只为让页面可以滚动,好验证浮层打开时整页滚动被锁住</div>
512
+
513
+ <script>
514
+ const mlog = (s) => { document.getElementById('modal-log').textContent = s; };
515
+ for (const id of ['plain','under-sheet','banner-ok','sheet-a','sheet-b','sheet-c','sheet-d','ghost-btn']) {
516
+ document.getElementById(id).onclick = () => mlog(id + '-clicked');
517
+ }
518
+ document.getElementById('banner-close').onclick = () => {
519
+ document.getElementById('banner').classList.add('off');
520
+ mlog('banner-closed');
521
+ };
522
+ // 打开浮层顺手把整页滚动锁住——真实站点几乎都这么做,也是「模态开着」的通用旁证
523
+ document.getElementById('open-sheet').onclick = () => {
524
+ document.getElementById('sheet-wrap').classList.add('on');
525
+ document.body.style.position = 'fixed';
526
+ document.body.style.overflow = 'hidden';
527
+ mlog('sheet-opened');
528
+ };
529
+ const closeSheet = (why) => {
530
+ document.getElementById('sheet-wrap').classList.remove('on');
531
+ document.body.style.position = '';
532
+ document.body.style.overflow = '';
533
+ mlog(why);
534
+ };
535
+ document.getElementById('sheet-ok').onclick = () => closeSheet('sheet-confirmed');
536
+ document.getElementById('sheet-cancel').onclick = () => closeSheet('sheet-cancelled');
537
+
538
+ const nat = document.getElementById('native');
539
+ document.getElementById('open-native').onclick = () => { nat.showModal(); mlog('native-opened'); };
540
+ document.getElementById('native-ok').onclick = () => mlog('native-ok-clicked');
541
+ document.getElementById('native-close').onclick = () => { nat.close(); mlog('native-closed'); };
542
+
543
+ // shadow root 里的浮层:判定要穿得进去,但 container 选择器进不去
544
+ const smRoot = document.getElementById('shadow-modal-host').attachShadow({ mode: 'open' });
545
+ smRoot.innerHTML =
546
+ '<div id="sm" role="dialog" aria-modal="true" style="display:none;position:fixed;inset:0;background:#fff">' +
547
+ '<h2>影子里的浮层</h2><button id="sm-ok">影子里的确认</button></div>';
548
+ smRoot.getElementById('sm-ok').onclick = () => mlog('shadow-modal-ok-clicked');
549
+ document.getElementById('open-shadow').onclick = () => {
550
+ smRoot.getElementById('sm').style.display = 'block';
551
+ mlog('shadow-modal-opened');
552
+ };
553
+ <\/script>
554
+ `;
555
+
556
+ const KEYS_PAGE = `<!doctype html>
557
+ <meta charset="utf-8">
558
+ <title>按键目标测试页</title>
559
+ <style>
560
+ body { font: 14px/1.6 -apple-system, "PingFang SC", sans-serif; margin: 16px; }
561
+ input { display: block; margin: 8px 0; width: 260px; padding: 4px; }
562
+ </style>
563
+ <h1 id="keys-title">按键落到了谁身上</h1>
564
+ <input id="k1" type="text" aria-label="第一个按键靶子">
565
+ <input id="k2" type="text" aria-label="第二个按键靶子">
566
+ <div id="keylog">空</div>
567
+ <script>
568
+ window.__keys = [];
569
+ // 捕获阶段挂在 document 上:输入框自己把事件吃掉也照样记得到;焦点在 body 上时
570
+ // target 就是 BODY,正好把「键打歪了」这件事记成一条可断言的证据
571
+ document.addEventListener('keydown', function (e) {
572
+ var t = e.target || document.body;
573
+ var tag = String(t.tagName || '').toUpperCase();
574
+ window.__keys.push(tag + (t.id ? '#' + t.id : '') + ':' + e.key);
575
+ document.getElementById('keylog').textContent = window.__keys.join(' | ');
576
+ }, true);
577
+ window.__keysReset = function () {
578
+ window.__keys = [];
579
+ document.getElementById('k1').value = '';
580
+ document.getElementById('k2').value = '';
581
+ document.getElementById('keylog').textContent = '空';
582
+ document.activeElement && document.activeElement.blur && document.activeElement.blur();
583
+ return true;
584
+ };
585
+ <\/script>
586
+ `;
587
+
588
+ const SPAWN = `<!doctype html>
589
+ <meta charset="utf-8">
590
+ <title>新页接管测试页</title>
591
+ <style>
592
+ body { font: 14px/1.6 -apple-system, "PingFang SC", sans-serif; margin: 16px; }
593
+ a, button { display: block; margin: 10px 0; font-size: 15px; }
594
+ </style>
595
+ <h1 id="spawn-title">页面自开的新页</h1>
596
+ <a id="a-blank" href="/spawn-child?via=blank" target="_blank">target=_blank 链接</a>
597
+ <a id="a-noopener" href="/spawn-child?via=noopener" target="_blank" rel="noopener">target=_blank rel=noopener 链接</a>
598
+ <button id="b-open" onclick="window.open('/spawn-child?via=open')">window.open(url)</button>
599
+ <button id="b-popup" onclick="window.open('/spawn-child?via=popup', '_blank', 'width=400,height=300')">window.open 独立小窗</button>
600
+ <button id="b-delayed" onclick="setTimeout(function(){ window.open('/spawn-child?via=delayed'); }, 300)">延迟 300ms 后 window.open</button>
601
+ <!-- 表单的 target=_blank:又一种「页面自开新页」的入口,和链接/window.open 走的不是同一条 JS 路 -->
602
+ <form id="f-blank" action="/spawn-child" method="get" target="_blank">
603
+ <input type="hidden" name="via" value="form">
604
+ <button id="b-form">表单 target=_blank 提交</button>
605
+ </form>
606
+ <!-- 中键 / Cmd+左键专用的两条链接。这条路上浏览器不发 Page.windowOpen、也不设 opener,
607
+ 认领只能靠 browser_click 自己记的那笔意图 -->
608
+ <a id="a-mid" href="/spawn-child?via=mid" target="_blank">中键点它</a>
609
+ <a id="a-cmd" href="/spawn-child?via=cmd" target="_blank">Cmd+左键点它</a>
610
+ `;
611
+
612
+ const SPAWN_CHILD = (via) => `<!doctype html>
613
+ <meta charset="utf-8">
614
+ <title>子页 ${via}</title>
615
+ <body>
616
+ <h1 id="child-title">我是子页</h1>
617
+ <p id="child-via">${via}</p>
618
+ <input id="child-input" aria-label="子页输入框">
619
+ <script>
620
+ // 接管遮蔽(光晕宿主 + 输入护盾)是不是**在这一页出生的第一时间**就装上了,
621
+ // 只有页面自己记得——事后拿 browser_eval 去问,那次调用本身就会把它装上,
622
+ // 断言等于自证。所以这里由页面自己盯着,把第一次看见宿主的时刻记下来。
623
+ window.__aicHostSeenAt = null;
624
+ (function () {
625
+ var t0 = performance.now();
626
+ var iv = setInterval(function () {
627
+ if (document.getElementById('__aic_cursor__')) {
628
+ window.__aicHostSeenAt = performance.now() - t0;
629
+ clearInterval(iv);
630
+ } else if (performance.now() - t0 > 20000) {
631
+ clearInterval(iv);
632
+ }
633
+ }, 20);
634
+ })();
635
+ <\/script>
636
+ `;
637
+
638
+ const ERGO = `<!doctype html>
639
+ <meta charset="utf-8">
640
+ <title>交互人体工学测试页</title>
641
+ <style>
642
+ html { scroll-behavior: smooth; } /* 关键:整页平滑滚动 */
643
+ body { font: 14px/1.6 -apple-system, "PingFang SC", sans-serif; margin: 16px; }
644
+ .pad { height: 1600px; background: linear-gradient(#fff, #eee); }
645
+ .cage { width: 260px; height: 60px; border: 2px solid #999; margin: 8px 0; }
646
+ #clipcage { overflow: clip; }
647
+ #scrollcage { overflow: auto; }
648
+ #virtcage { overflow: hidden; position: relative; }
649
+ #virtinner { position: absolute; top: 0; left: 0; }
650
+ .inpad { height: 400px; }
651
+ #drawer { position: fixed; left: -600px; top: 200px; }
652
+ </style>
653
+ <h1 id="ergo-title">交互人体工学</h1>
654
+ <div id="log">未触发</div>
655
+ <div id="grow">短</div>
656
+ <button id="more">See more</button>
657
+ <button id="racer">开始长距离平滑滚动</button>
658
+ <button id="addlate">3 秒后追加一个按钮</button>
659
+ <button id="addfirst">往最前面插一个按钮</button>
660
+ <div id="late-slot"></div>
661
+
662
+ <div class="cage" id="clipcage"><div class="inpad">裁剪容器的垫片</div><button id="btn-clip">被裁掉的按钮</button></div>
663
+ <div class="cage" id="scrollcage"><div class="inpad">滚动容器的垫片</div><button id="btn-scroll">容器里的按钮</button></div>
664
+ <div class="cage" id="virtcage"><div id="virtinner"><div class="inpad">虚拟滚动的垫片</div><button id="btn-virt">虚拟滚动里的按钮</button></div></div>
665
+ <button id="drawer">抽屉里的按钮</button>
666
+
667
+ <div class="pad">这一大块只为把下面的按钮挤出视口</div>
668
+ <button id="btn-deep">平滑滚动页面深处的按钮</button>
669
+ <div class="pad">再来一块</div>
670
+ <button id="btn-deeper">更深处的按钮</button>
671
+
672
+ <script>
673
+ const mark = (s) => { document.getElementById('log').textContent = s; };
674
+ for (const id of ['btn-clip','btn-scroll','btn-virt','drawer','btn-deep','btn-deeper']) {
675
+ document.getElementById(id).onclick = () => mark(id + '-clicked');
676
+ }
677
+ document.getElementById('racer').onclick = () => {
678
+ scrollTo(0, 0);
679
+ // 先回到顶部再往下滚一大段,制造一段持续数百毫秒的平滑滚动
680
+ setTimeout(() => scrollTo(0, 4000), 30);
681
+ mark('racer-started');
682
+ };
683
+ // 文案会变的按钮:selector/文本/URL 三条都等不住「文案从 A 变成 B」
684
+ document.getElementById('more').onclick = function () {
685
+ if (this.textContent === 'See more') {
686
+ document.getElementById('grow').textContent = '展开后的长正文。'.repeat(90);
687
+ this.textContent = 'See less';
688
+ } else {
689
+ document.getElementById('grow').textContent = '短';
690
+ this.textContent = 'See more';
691
+ }
692
+ };
693
+ document.getElementById('addlate').onclick = () => {
694
+ setTimeout(() => {
695
+ const b = document.createElement('button');
696
+ b.id = 'late-btn';
697
+ b.textContent = '迟到的按钮';
698
+ b.onclick = () => mark('late-clicked');
699
+ document.getElementById('late-slot').appendChild(b);
700
+ }, 1500);
701
+ mark('late-scheduled');
702
+ };
703
+ document.getElementById('addfirst').onclick = () => {
704
+ if (document.getElementById('intruder')) return;
705
+ const b = document.createElement('button');
706
+ b.id = 'intruder';
707
+ b.textContent = '插队的按钮';
708
+ b.onclick = () => mark('intruder-clicked');
709
+ document.body.insertBefore(b, document.body.firstChild);
710
+ mark('intruder-added');
711
+ };
712
+ window.aicReset = () => {
713
+ mark('未触发');
714
+ document.documentElement.style.scrollBehavior = 'auto';
715
+ scrollTo(0, 0);
716
+ document.getElementById('scrollcage').scrollTop = 0;
717
+ document.documentElement.style.scrollBehavior = '';
718
+ // 折叠区块也复位:它是个 toggle,状态一旦被前面某一步搞乱,
719
+ // 后面等文案变化的用例就会莫名超时,报错指向的地方跟真正的病灶差着十万八千里
720
+ document.getElementById('more').textContent = 'See more';
721
+ document.getElementById('grow').textContent = '短';
722
+ return 'reset';
723
+ };
724
+ // 造一段指定长度的字符串,用来量「eval 返回值到底在哪一档被截断」
725
+ window.aicBigString = (n) => '零一二三四五六七八九'.repeat(Math.ceil(n / 10)).slice(0, n);
726
+ <\/script>
727
+ `;
728
+
729
+ function heavyPage(n, depth) {
730
+ const rows = [];
731
+ for (let i = 0; i < n; i++) {
732
+ rows.push(
733
+ `<div class="r"><span class="t">条目 ${i}</span>` +
734
+ `<a href="/api/user?i=${i}">链接 ${i}</a>` +
735
+ `<button class="b">按钮 ${i}</button>` +
736
+ `<input type="text" value="v${i}" aria-label="输入 ${i}">` +
737
+ `<span class="x">${"文本填充 ".repeat(3)}${i}</span></div>`
738
+ );
739
+ }
740
+ const hidden = [];
741
+ for (let i = 0; i < Math.floor(n / 2); i++) {
742
+ hidden.push(`<div><button>隐藏按钮 ${i}</button><a href="#h${i}">隐藏链接 ${i}</a><span>隐藏文本 ${i}</span></div>`);
743
+ }
744
+ let nest = `<button id="deep-btn">最深处的按钮</button>`;
745
+ for (let i = 0; i < depth; i++) nest = `<div class="d${i}">${nest}</div>`;
746
+ return (
747
+ `<!doctype html><meta charset="utf-8"><title>重页面 ${n}</title>` +
748
+ `<style>body{font:13px sans-serif;margin:8px}.r{padding:2px}.hid{display:none}</style>` +
749
+ `<h1>重页面</h1><div id="rows">${rows.join("")}</div>` +
750
+ `<div class="hid" id="hidden-block">${hidden.join("")}</div>` +
751
+ `<div id="nest">${nest}</div>` +
752
+ `<script>document.getElementById('deep-btn').onclick=function(){document.title='deep-clicked'}<\/script>`
753
+ );
754
+ }
755
+
756
+ const PAGE = `<!doctype html>
757
+ <meta charset="utf-8">
758
+ <title>agent-in-chrome 测试台</title>
759
+ <style>
760
+ body { font: 15px/1.6 -apple-system, "PingFang SC", sans-serif; max-width: 760px; margin: 40px auto; padding: 0 20px; }
761
+ button { font: inherit; padding: 6px 12px; margin: 4px 6px 4px 0; }
762
+ #log { background: #f4f4f5; padding: 10px; border-radius: 6px; min-height: 60px; white-space: pre-wrap; }
763
+ .box { border: 1px solid #ddd; border-radius: 8px; padding: 14px; margin: 14px 0; }
764
+ </style>
765
+ <h1 id="title">测试台</h1>
766
+ <p id="intro">这个页面只为端到端测试存在,所有行为都是确定的。</p>
767
+
768
+ <div class="box">
769
+ <h2>接口</h2>
770
+ <button id="btn-get">GET 用户</button>
771
+ <button id="btn-post">POST 订单</button>
772
+ <button id="btn-slow">慢接口 (1.2s)</button>
773
+ <button id="btn-500">失败接口 (500)</button>
774
+ </div>
775
+
776
+ <div class="box">
777
+ <h2>表单</h2>
778
+ <label>关键词 <input id="kw" type="text" placeholder="输入关键词"></label>
779
+ <label><input id="agree" type="checkbox"> 我同意</label>
780
+ <button id="btn-submit">提交搜索</button>
781
+ <div id="result">尚未搜索</div>
782
+ </div>
783
+
784
+ <div class="box">
785
+ <h2>WebSocket</h2>
786
+ <button id="btn-ws-connect">连接</button>
787
+ <button id="btn-ws-send">发一条消息</button>
788
+ <button id="btn-ws-close">断开</button>
789
+ <div id="ws-state">未连接</div>
790
+ </div>
791
+
792
+ <div class="box">
793
+ <h2>控制台</h2>
794
+ <button id="btn-log">打一条 log</button>
795
+ <button id="btn-error">抛一个异常</button>
796
+ </div>
797
+
798
+ <div class="box">
799
+ <h2>对话框</h2>
800
+ <button id="btn-alert">弹 alert</button>
801
+ <button id="btn-confirm">confirm 后删除</button>
802
+ <button id="btn-prompt">prompt 取名</button>
803
+ <span id="confirm-result"></span>
804
+ </div>
805
+
806
+ <div class="box">
807
+ <h2>难啃的结构</h2>
808
+ <p>下面这些是判断「能不能真做测试」的分水岭。</p>
809
+ <iframe id="frame" src="/frame?id=frame1&amp;nest=/frame%3Fid%3Dframe1-inner" style="width:100%;height:190px;border:1px dashed #bbb"></iframe>
810
+ <iframe id="xframe" src="__ALT__/frame?id=xframe&amp;autopost=1" style="width:100%;height:90px;border:1px dashed #f90"></iframe>
811
+ <div id="host"></div>
812
+ <div id="host-nested"></div>
813
+ <div id="host-closed"></div>
814
+ <!-- aria-disabled="true" 的输入框:ARIA 只是给辅助技术看的提示,元素本身照样收输入。
815
+ 可操作性检查会(正确地)拦下它,而这正是 force:true 存在的意义——
816
+ 用它验证 browser_type 的 force 是真能强行下发并且**文字真的落进去**,
817
+ 不是只对 click 有效。 -->
818
+ <input id="force-input" aria-disabled="true" placeholder="伪禁用输入框">
819
+ <div id="force-log">未输入</div>
820
+ <div style="position:relative;display:inline-block">
821
+ <button id="btn-covered">被遮住的按钮</button>
822
+ <div id="overlay" style="position:absolute;inset:0;background:rgba(255,0,0,.25)"></div>
823
+ </div>
824
+ <button id="btn-disabled" disabled>禁用的按钮</button>
825
+ <button id="btn-aria" aria-disabled="true">aria 禁用的按钮</button>
826
+ <button id="btn-pe" style="pointer-events:none">穿透的按钮</button>
827
+ <span style="position:relative;display:inline-block">
828
+ <button id="btn-dyn">会被动态遮罩盖住的按钮</button>
829
+ </span>
830
+ <button id="btn-hide-me">会被藏起来的按钮</button>
831
+ <input id="file" type="file">
832
+ <div id="hard-log">未触发</div>
833
+ <div id="frame-report">无</div>
834
+ <div id="frame-upload-report">无</div>
835
+ </div>
836
+
837
+ <div class="box">
838
+ <h2>要滚动才看得见</h2>
839
+ <div style="height:1800px;background:linear-gradient(#fff,#eee)">中间这一大块只为把下面那个按钮挤出视口</div>
840
+ <button id="btn-far">滚动后才可见的按钮</button>
841
+ </div>
842
+
843
+ <div class="box">
844
+ <h2>文件上传</h2>
845
+ <p>上面那个 #file 是单选的。这里补齐多选、隐藏、以及真正发出去的一条链路。</p>
846
+ <label>多选 <input id="file-multi" type="file" multiple></label>
847
+ <div id="multi-log">未选择</div>
848
+ <!-- 真实站点最常见的形态:input 藏起来,露在外面的是个好看的按钮。
849
+ 按坐标点它没用(弹出的是系统文件框),只能靠 setFileInputFiles。 -->
850
+ <input id="file-hidden" type="file" style="display:none">
851
+ <button id="btn-pick">选择文件…(外观按钮,点了会弹系统框)</button>
852
+ <div id="hidden-log">未选择</div>
853
+ <input id="file-disabled" type="file" disabled>
854
+ <!-- 把第一次 change 吞掉的输入框:真实站点上有页面在捕获阶段 stopImmediatePropagation。
855
+ 这时 Chrome 原生派发的 change 我们收不到(changeFired=false),工具必须补发一次,
856
+ 否则「文件放进去了但页面不知道」——最难查的一类故障。
857
+ 第二次就放行,好让测试能断言「补发之后页面处理函数真的跑了」。 -->
858
+ <input id="file-swallow" type="file">
859
+ <div id="swallow-log">未选择</div>
860
+ <div id="shadow-file-log">未选择</div>
861
+ <button id="btn-upload">上传到服务端</button>
862
+ <div id="upload-log">未上传</div>
863
+ </div>
864
+
865
+ <!-- 会真的跳转的链接。点击校验必须能分清「点中了、然后页面跳走了」和「点歪了」——
866
+ 这两件事在「事后再量一次几何」的验法里长得一模一样(目标都不在原地了)。 -->
867
+ <div class="box">
868
+ <h2>跳转链接</h2>
869
+ <a id="go-forms" href="/forms">去表单页</a>
870
+ </div>
871
+
872
+ <!-- 操作光标的靶子。要求:一整块纯色、不含文字、不动、尺寸固定。
873
+ 截图断言靠「同一块区域截两张、逐字节比」来判断光标有没有进图,
874
+ 区域里但凡有一点非确定性(动画、字体回退、光标闪烁)这条断言就会自己红。 -->
875
+ <div class="box">
876
+ <!-- 标题带 id:ref 元素截图的断言要按 find 拿到它、再改它的样式,
877
+ 从而验证「滚动之后 ref 截的确实是那个元素」 -->
878
+ <h2 id="cursor-pad-title">光标靶</h2>
879
+ <div id="cursor-pad" style="width:240px;height:140px;background:#dcdcdc"></div>
880
+ </div>
881
+
882
+ <div id="log">就绪</div>
883
+
884
+ <script>
885
+ const log = (s) => { document.getElementById('log').textContent = s; };
886
+ document.getElementById('btn-get').onclick = () =>
887
+ fetch('/api/user').then(r => r.json()).then(d => log('GET → ' + JSON.stringify(d)));
888
+ document.getElementById('btn-post').onclick = () =>
889
+ fetch('/api/order', {
890
+ method: 'POST',
891
+ headers: { 'content-type': 'application/json', 'x-test-token': 'tok_secret_value_12345' },
892
+ body: JSON.stringify({ sku: 'A-1', qty: 3 }),
893
+ }).then(r => r.json()).then(d => log('POST → ' + JSON.stringify(d)));
894
+ document.getElementById('btn-slow').onclick = () =>
895
+ fetch('/api/slow').then(r => r.json()).then(d => log('慢接口 → ' + JSON.stringify(d)));
896
+ document.getElementById('btn-500').onclick = () =>
897
+ fetch('/api/boom').then(r => log('失败接口 → HTTP ' + r.status));
898
+
899
+ document.getElementById('btn-submit').onclick = () => {
900
+ const kw = document.getElementById('kw').value;
901
+ document.getElementById('result').textContent = '搜索结果:' + kw;
902
+ };
903
+
904
+ let ws = null;
905
+ document.getElementById('btn-ws-connect').onclick = () => {
906
+ ws = new WebSocket('ws://' + location.host + '/ws');
907
+ ws.onopen = () => { document.getElementById('ws-state').textContent = '已连接'; };
908
+ ws.onmessage = (e) => { document.getElementById('ws-state').textContent = '收到:' + e.data; };
909
+ ws.onclose = () => { document.getElementById('ws-state').textContent = '已断开'; };
910
+ };
911
+ document.getElementById('btn-ws-send').onclick = () => {
912
+ if (ws && ws.readyState === 1) ws.send(JSON.stringify({ hello: '来自测试页', n: 42 }));
913
+ };
914
+ document.getElementById('btn-ws-close').onclick = () => ws && ws.close();
915
+
916
+ const hard = (s) => { document.getElementById('hard-log').textContent = s; };
917
+
918
+ // Shadow DOM 里的按钮:普通 querySelectorAll 穿不进去
919
+ const host = document.getElementById('host');
920
+ const root = host.attachShadow({ mode: 'open' });
921
+ // shadow 里既放按钮(测穿透)也放 file input(web component 做的上传控件就是这形态)
922
+ root.innerHTML = '<button id="shadow-btn">影子按钮</button><input id="shadow-file" type="file">';
923
+ root.getElementById('shadow-btn').onclick = () => hard('shadow-clicked');
924
+ root.getElementById('shadow-file').onchange = (e) => {
925
+ document.getElementById('shadow-file-log').textContent = 'shadow-file:' + (e.target.files[0]?.name || '');
926
+ };
927
+
928
+ // closed shadow root:host.shadowRoot 是 null,页面自己的脚本都拿不到。
929
+ // 只有扩展的 chrome.dom.openOrClosedShadowRoot 看得见——这条路以前只有 mock 覆盖过。
930
+ const hostC = document.getElementById('host-closed');
931
+ const rootC = hostC.attachShadow({ mode: 'closed' });
932
+ rootC.innerHTML = '<button id="closed-btn">封闭影子按钮</button>';
933
+ rootC.getElementById('closed-btn').onclick = () => hard('closed-shadow-clicked');
934
+ window.aicClosedShadowIsClosed = () => hostC.shadowRoot === null;
935
+
936
+ document.getElementById('force-input').oninput = (e) => {
937
+ document.getElementById('force-log').textContent = 'force-input:' + e.target.value;
938
+ };
939
+
940
+ // 嵌套 shadow root:shadow 里再挂一个 shadow,递归穿不到底就找不到它
941
+ const hostN = document.getElementById('host-nested');
942
+ const rootN = hostN.attachShadow({ mode: 'open' });
943
+ const midHost = document.createElement('div');
944
+ rootN.appendChild(midHost);
945
+ const rootN2 = midHost.attachShadow({ mode: 'open' });
946
+ rootN2.innerHTML = '<button id="deep-btn">深层影子按钮</button>';
947
+ rootN2.getElementById('deep-btn').onclick = () => hard('deep-shadow-clicked');
948
+
949
+ document.getElementById('btn-covered').onclick = () => hard('covered-clicked');
950
+ document.getElementById('overlay').onclick = () => hard('overlay-clicked');
951
+ document.getElementById('btn-disabled').onclick = () => hard('disabled-clicked');
952
+ document.getElementById('btn-aria').onclick = () => hard('aria-clicked');
953
+ document.getElementById('btn-pe').onclick = () => hard('pe-clicked');
954
+ document.getElementById('btn-dyn').onclick = () => hard('dyn-clicked');
955
+ document.getElementById('btn-hide-me').onclick = () => hard('hidden-clicked');
956
+ document.getElementById('btn-far').onclick = () => hard('far-clicked');
957
+ document.getElementById('file').onchange = (e) => {
958
+ hard('file:' + (e.target.files[0]?.name || ''));
959
+ };
960
+
961
+ // 测试用的钩子:读页面之后再改页面,模拟「拿到 ref 之后页面变了」
962
+ window.aicReset = () => {
963
+ hard('未触发');
964
+ document.getElementById('frame-report').textContent = '无';
965
+ document.getElementById('frame-upload-report').textContent = '无';
966
+ const o = document.getElementById('dyn-overlay');
967
+ if (o) o.remove();
968
+ document.getElementById('btn-hide-me').style.display = '';
969
+ return 'reset';
970
+ };
971
+ window.aicAddOverlay = () => {
972
+ const btn = document.getElementById('btn-dyn');
973
+ if (document.getElementById('dyn-overlay')) return 'exists';
974
+ const o = document.createElement('div');
975
+ o.id = 'dyn-overlay';
976
+ o.style.cssText = 'position:absolute;inset:0;background:rgba(0,0,255,.2)';
977
+ o.onclick = () => hard('dyn-overlay-clicked');
978
+ btn.parentNode.appendChild(o);
979
+ return 'added';
980
+ };
981
+ window.aicResetForceInput = () => {
982
+ document.getElementById('force-input').value = '';
983
+ document.getElementById('force-log').textContent = '未输入';
984
+ return 'reset';
985
+ };
986
+ window.aicHideBtn = () => {
987
+ document.getElementById('btn-hide-me').style.display = 'none';
988
+ return 'hidden';
989
+ };
990
+
991
+ document.getElementById('file-multi').onchange = (e) => {
992
+ document.getElementById('multi-log').textContent =
993
+ 'multi:' + e.target.files.length + ':' + [...e.target.files].map(f => f.name).join(',');
994
+ };
995
+ {
996
+ let swallowed = false;
997
+ const sw = document.getElementById('file-swallow');
998
+ sw.addEventListener('change', (e) => {
999
+ if (!swallowed) { swallowed = true; e.stopImmediatePropagation(); }
1000
+ }, true);
1001
+ sw.addEventListener('change', (e) => {
1002
+ document.getElementById('swallow-log').textContent = 'swallow:' + (e.target.files[0]?.name || '');
1003
+ });
1004
+ }
1005
+ document.getElementById('file-hidden').onchange = (e) => {
1006
+ document.getElementById('hidden-log').textContent = 'hidden:' + (e.target.files[0]?.name || '');
1007
+ };
1008
+ // 外观按钮:点它等于 input.click(),浏览器会弹出系统文件选择框。
1009
+ // 测试里断言「不要走这条路」,工具应该直接设置 input。
1010
+ document.getElementById('btn-pick').onclick = () => document.getElementById('file-hidden').click();
1011
+
1012
+ // 真正把选中的文件发出去,用于验证「字节确实到了服务端」
1013
+ document.getElementById('btn-upload').onclick = () => {
1014
+ const fd = new FormData();
1015
+ const one = document.getElementById('file').files[0];
1016
+ if (one) fd.append('single', one, one.name);
1017
+ for (const f of document.getElementById('file-multi').files) fd.append('many', f, f.name);
1018
+ const h = document.getElementById('file-hidden').files[0];
1019
+ if (h) fd.append('hidden', h, h.name);
1020
+ document.getElementById('upload-log').textContent = '上传中…';
1021
+ fetch('/upload', { method: 'POST', body: fd })
1022
+ .then(r => r.json())
1023
+ .then(d => {
1024
+ document.getElementById('upload-log').textContent =
1025
+ 'uploaded:' + d.count + ':' + d.files.map(f => f.filename + '@' + f.size).join(',');
1026
+ })
1027
+ .catch(e => { document.getElementById('upload-log').textContent = 'upload-error:' + e.message; });
1028
+ };
1029
+
1030
+ // 各层 iframe 的点击一路冒泡到这里,跨源帧也走这条路
1031
+ addEventListener('message', (e) => {
1032
+ const v = e.data && (e.data.aicClick || e.data.aicUpload);
1033
+ if (!v) return;
1034
+ // 上传相关的消息单独记一格:跨源 iframe 的 contentDocument 从顶层读不到,
1035
+ // 「帧内 change 真的跑了 / 帧内真把文件 POST 出去了」只能靠这条通道断言
1036
+ const id = e.data.aicUpload ? 'frame-upload-report' : 'frame-report';
1037
+ const el = document.getElementById(id);
1038
+ el.textContent = el.textContent === '无' ? v : el.textContent + ',' + v;
1039
+ });
1040
+
1041
+ document.getElementById('btn-log').onclick = () => console.log('测试日志 marker-abc');
1042
+ document.getElementById('btn-error').onclick = () => { throw new Error('测试异常 marker-boom'); };
1043
+ document.getElementById('btn-alert').onclick = () => { alert('这是一个 alert'); };
1044
+ // confirm 的取消/接受要能从页面状态看出来:审计 6.1 的核心场景就是
1045
+ // 「confirm 被静默取消而 click 报成功」——结果元素让测试能验「到底删没删」
1046
+ document.getElementById('btn-confirm').onclick = () => {
1047
+ document.getElementById('confirm-result').textContent = confirm('确定删除吗') ? '已删除' : '没删';
1048
+ };
1049
+ document.getElementById('btn-prompt').onclick = () => {
1050
+ const name = prompt('取个名字', '默认名');
1051
+ document.getElementById('confirm-result').textContent = name === null ? '取消了' : '名字:' + name;
1052
+ };
1053
+ </script>
1054
+ `;
1055
+
1056
+ function parseMultipart(buf, boundary) {
1057
+ const parts = [];
1058
+ const delim = Buffer.from(`--${boundary}`);
1059
+ let idx = buf.indexOf(delim);
1060
+ while (idx !== -1) {
1061
+ const start = idx + delim.length;
1062
+ if (buf.subarray(start, start + 2).toString("latin1") === "--") break;
1063
+ const headerEnd = buf.indexOf("\r\n\r\n", start);
1064
+ if (headerEnd === -1) break;
1065
+ const headers = buf.subarray(start + 2, headerEnd).toString("utf8");
1066
+ const next = buf.indexOf(delim, headerEnd);
1067
+ if (next === -1) break;
1068
+ parts.push({ headers, body: Buffer.from(buf.subarray(headerEnd + 4, next - 2)) });
1069
+ idx = next;
1070
+ }
1071
+ return parts;
1072
+ }
1073
+
1074
+ let lastUpload = null;
1075
+ const AUTH_SESSIONS = new Map();
1076
+
1077
+ let ALT_BASE = "";
1078
+ let SELF_BASE = "";
1079
+
1080
+ const handler = async (req, res) => {
1081
+ const url = new URL(req.url, "http://x");
1082
+ const json = (obj, code = 200) => {
1083
+ const body = JSON.stringify(obj);
1084
+ res.writeHead(code, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
1085
+ res.end(body);
1086
+ };
1087
+
1088
+ if (url.pathname === "/") {
1089
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1090
+ return res.end(PAGE.replace(/__ALT__/g, ALT_BASE));
1091
+ }
1092
+ if (url.pathname === "/emulate") {
1093
+ const meta = url.searchParams.get("nometa") ? "" : `<meta name="viewport" content="width=device-width, initial-scale=1">`;
1094
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1095
+ return res.end(
1096
+ `<!doctype html><meta charset="utf-8">${meta}<title>仿真验证页</title>` +
1097
+ `<style>body{margin:0;font:14px sans-serif;background:#ffffff;color:#111111}` +
1098
+ `@media (prefers-color-scheme: dark){body{background:#101010;color:#eeeeee}}` +
1099
+ `@media (max-width: 600px){#bp{outline:2px solid red}}</style>` +
1100
+ `<h1 id="t">仿真验证页</h1><div id="bp">断点靶子</div><pre id="log"></pre>` +
1101
+ `<script>
1102
+ window.__emuProbe = function () {
1103
+ return {
1104
+ innerWidth: window.innerWidth,
1105
+ innerHeight: window.innerHeight,
1106
+ dpr: window.devicePixelRatio,
1107
+ dark: matchMedia('(prefers-color-scheme: dark)').matches,
1108
+ bg: getComputedStyle(document.body).backgroundColor,
1109
+ narrow: matchMedia('(max-width: 600px)').matches,
1110
+ hasViewportMeta: !!document.querySelector('meta[name=viewport]')
1111
+ };
1112
+ };
1113
+ window.__emuGeo = function () {
1114
+ return new Promise(function (r) {
1115
+ if (!navigator.geolocation) return r({ ok: false, msg: 'no geolocation api' });
1116
+ navigator.geolocation.getCurrentPosition(
1117
+ function (p) { r({ ok: true, lat: p.coords.latitude, lon: p.coords.longitude, acc: p.coords.accuracy }); },
1118
+ function (e) { r({ ok: false, code: e.code, msg: e.message }); },
1119
+ { timeout: 8000, maximumAge: 0 }
1120
+ );
1121
+ });
1122
+ };
1123
+ window.__emuPermission = function () {
1124
+ return navigator.permissions.query({ name: 'geolocation' }).then(function (p) { return p.state; }).catch(function () { return 'error'; });
1125
+ };
1126
+ window.__emuFetch = function (bytes) {
1127
+ var t = Date.now();
1128
+ return fetch('/big?n=' + bytes).then(function (r) { return r.text(); }).then(function (s) { return { bytes: s.length, ms: Date.now() - t }; })
1129
+ .catch(function (e) { return { error: String(e) }; });
1130
+ };
1131
+ <\/script>`
1132
+ );
1133
+ }
1134
+ if (url.pathname === "/frames-hard") {
1135
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1136
+ return res.end(HARD_FRAMES.replace(/__ALT__/g, ALT_BASE).replace(/__SELF__/g, SELF_BASE));
1137
+ }
1138
+ if (url.pathname === "/forms") {
1139
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1140
+ return res.end(FORMS);
1141
+ }
1142
+ if (url.pathname === "/form-submits") {
1143
+ const out = FORM_SUBMITS.slice();
1144
+ if (url.searchParams.get("clear") === "1") FORM_SUBMITS.length = 0;
1145
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
1146
+ return res.end(JSON.stringify({ count: out.length, submits: out }));
1147
+ }
1148
+ if (url.pathname === "/form-submit" && req.method === "POST") {
1149
+ let body = "";
1150
+ for await (const c of req) body += c;
1151
+ const got = {};
1152
+ for (const [k, v] of new URLSearchParams(body)) {
1153
+ if (k in got) got[k] = [].concat(got[k], v);
1154
+ else got[k] = v;
1155
+ }
1156
+ FORM_SUBMITS.push({
1157
+ at: new Date().toISOString(),
1158
+ ua: req.headers["user-agent"] || null,
1159
+ referer: req.headers["referer"] || null,
1160
+ origin: req.headers["origin"] || null,
1161
+ contentType: req.headers["content-type"] || null,
1162
+ remote: `${req.socket.remoteAddress}:${req.socket.remotePort}`,
1163
+ rawBody: body,
1164
+ rawBytes: Buffer.byteLength(body),
1165
+ fieldCount: Object.keys(got).length,
1166
+ received: got,
1167
+ });
1168
+ if (FORM_SUBMITS.length > 50) FORM_SUBMITS.shift();
1169
+ res.writeHead(200, {
1170
+ "content-type": "application/json; charset=utf-8",
1171
+ "set-cookie": "e2e_raw_hdr=1; Path=/; SameSite=Lax",
1172
+ });
1173
+ return res.end(JSON.stringify({ ok: true, received: got, marker: "form-submit-marker" }));
1174
+ }
1175
+ if (url.pathname === "/adopt") {
1176
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1177
+ return res.end(ADOPT);
1178
+ }
1179
+ if (url.pathname === "/spawn") {
1180
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1181
+ return res.end(SPAWN);
1182
+ }
1183
+ if (url.pathname === "/spawn-child") {
1184
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1185
+ return res.end(SPAWN_CHILD(url.searchParams.get("via") || "?"));
1186
+ }
1187
+ if (url.pathname === "/trusted-types") {
1188
+ const names = !!url.searchParams.get("names");
1189
+ res.writeHead(200, {
1190
+ "content-type": "text/html; charset=utf-8",
1191
+ "content-security-policy": "require-trusted-types-for 'script'" + (names ? "; trusted-types page-policy" : ""),
1192
+ });
1193
+ return res.end(
1194
+ `<!doctype html><meta charset="utf-8"><title>Trusted Types 页</title>` +
1195
+ `<h1 id="t">Trusted Types 页</h1><pre id="log"></pre>` +
1196
+ `<script>
1197
+ // 断言这一页真的在强制执行。没有这两笔的话,哪天 Chrome 改了行为、CSP 头写错了、
1198
+ // 或者夹具被人顺手改坏,遮蔽测试会静静地变成一条什么都没测的绿线。
1199
+ window.__ttEnforced = (function () {
1200
+ try { document.createElement('div').innerHTML = '<b>x</b>'; return false; } catch (e) { return true; }
1201
+ })();
1202
+ // 策略路通不通(?names=1 的那一页应当是 false:连 'default' 都建不出来)
1203
+ window.__ttPolicyOk = (function () {
1204
+ try { window.trustedTypes.createPolicy('default', { createHTML: function (s) { return s; } }); return true; }
1205
+ catch (e) { return false; }
1206
+ })();
1207
+ document.getElementById('log').textContent = 'enforced=' + window.__ttEnforced + ' policyOk=' + window.__ttPolicyOk;
1208
+ </script>`,
1209
+ );
1210
+ }
1211
+ if (url.pathname === "/ergo") {
1212
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1213
+ return res.end(ERGO);
1214
+ }
1215
+ if (url.pathname === "/keys") {
1216
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1217
+ return res.end(KEYS_PAGE);
1218
+ }
1219
+ if (url.pathname === "/modals") {
1220
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1221
+ return res.end(MODALS);
1222
+ }
1223
+ if (url.pathname === "/modals-oopif") {
1224
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1225
+ return res.end(MODALS_OOPIF.replace(/__ALT__/g, ALT_BASE));
1226
+ }
1227
+ if (url.pathname === "/modal-oopif-frame") {
1228
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1229
+ return res.end(modalOopifFrame(url.searchParams.get("id") || "consent"));
1230
+ }
1231
+ if (url.pathname === "/modal-frame") {
1232
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1233
+ return res.end(
1234
+ `<!doctype html><meta charset="utf-8"><title>帧内浮层</title>` +
1235
+ `<style>html,body{margin:0;font:13px sans-serif}` +
1236
+ `#fd{position:fixed;inset:0;background:#eef;padding:8px}</style>` +
1237
+ `<div id="fd" role="dialog" aria-modal="true"><h2>帧内的浮层</h2>` +
1238
+ `<button id="fd-ok">帧内确认</button><button id="fd-close">帧内关掉</button></div>` +
1239
+ `<script>document.getElementById('fd-ok').onclick=function(){document.title='frame-dialog-ok'};` +
1240
+ `document.getElementById('fd-close').onclick=function(){document.getElementById('fd').style.display='none';document.title='frame-dialog-closed'}<\/script>`
1241
+ );
1242
+ }
1243
+ if (url.pathname === "/big") {
1244
+ const n = Math.min(Number(url.searchParams.get("n") || 1000), 40_000_000);
1245
+ const body = "0123456789".repeat(Math.ceil(n / 10)).slice(0, n);
1246
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "content-length": Buffer.byteLength(body) });
1247
+ return res.end(body);
1248
+ }
1249
+ if (url.pathname === "/text-pager" || url.pathname === "/text-pager-frame") {
1250
+ const inFrame = url.pathname === "/text-pager-frame";
1251
+ const seed = inFrame ? 97 : 65;
1252
+ const mark = (url.searchParams.get("mark") || "").replace(/[^A-Za-z]/g, "").slice(0, 20);
1253
+ const n = Math.min(Number(url.searchParams.get("n") || 3000), 200_000);
1254
+ let body = mark;
1255
+ for (let i = 0; body.length < n; i++) {
1256
+ body += String.fromCharCode(seed + (i % 20)).repeat(10);
1257
+ }
1258
+ body = body.slice(0, n);
1259
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1260
+ return res.end(
1261
+ `<!doctype html><meta charset="utf-8"><title>text-pager${inFrame ? "-frame" : ""}</title>` +
1262
+ `<body style="margin:0"><div id="t" style="word-break:break-all">${body}</div>` +
1263
+ (inFrame
1264
+ ? ""
1265
+ : `<iframe id="vis" src="/text-pager-frame?n=3000&mark=VISIBLEFRAMEMARK" style="width:300px;height:120px"></iframe>` +
1266
+ `<iframe id="inv" src="/text-pager-frame?n=600&mark=HIDDENFRAMEMARK" style="display:none"></iframe>` +
1267
+ `<button id="longname" aria-label="${"甲乙丙丁戊己庚辛壬癸".repeat(30)}">x</button>` +
1268
+ `<button id="byid" aria-labelledby="lbl">y</button>` +
1269
+ `<span id="lbl" style="position:absolute;left:-9999px">${"子丑寅卯辰巳午未申酉".repeat(30)}</span>`) +
1270
+ `</body>`
1271
+ );
1272
+ }
1273
+ if (url.pathname === "/heavy") {
1274
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1275
+ return res.end(heavyPage(Number(url.searchParams.get("n") || 1500), Number(url.searchParams.get("depth") || 30)));
1276
+ }
1277
+ if (url.pathname === "/frame") {
1278
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1279
+ return res.end(
1280
+ framePage(
1281
+ url.searchParams.get("id") || "frame",
1282
+ url.searchParams.get("nest"),
1283
+ url.searchParams.get("nestsbx") === "1",
1284
+ url.searchParams.get("autopost") === "1"
1285
+ )
1286
+ );
1287
+ }
1288
+ if (url.pathname === "/api/user") {
1289
+ return json({ id: 7, name: "测试用户", roles: ["admin", "dev"], marker: "user-payload-marker" });
1290
+ }
1291
+ if (url.pathname === "/needs-cookie") {
1292
+ const cookie = String(req.headers.cookie || "");
1293
+ if (!/\be2e_raw_hdr=1\b/.test(cookie)) {
1294
+ return json({ error: "未登录", need: "e2e_raw_hdr", marker: "needs-cookie-401" }, 401);
1295
+ }
1296
+ return json({ ok: true, who: "cookie 认过了", marker: "needs-cookie-200" });
1297
+ }
1298
+ if (url.pathname === "/auth/login") {
1299
+ const sid = "S" + Math.random().toString(36).slice(2, 12);
1300
+ AUTH_SESSIONS.set(sid, { user: "alice", at: Date.now() });
1301
+ res.writeHead(200, {
1302
+ "content-type": "application/json; charset=utf-8",
1303
+ "set-cookie": `zc_sid=${sid}; Path=/; HttpOnly; SameSite=Lax`,
1304
+ });
1305
+ return res.end(JSON.stringify({ ok: true, user: "alice", marker: "auth-login" }));
1306
+ }
1307
+ if (url.pathname === "/auth/me") {
1308
+ const sid = (String(req.headers.cookie || "").match(/\bzc_sid=([^;]+)/) || [])[1];
1309
+ const s = sid && AUTH_SESSIONS.get(sid);
1310
+ if (!s) return json({ ok: false, reason: "未登录", marker: "auth-401" }, 401);
1311
+ return json({ ok: true, user: s.user, sid, marker: "auth-200" });
1312
+ }
1313
+ if (url.pathname === "/api/order" && req.method === "POST") {
1314
+ let body = "";
1315
+ for await (const c of req) body += c;
1316
+ return json({ ok: true, echo: JSON.parse(body || "{}"), orderId: "ord_9527", marker: "order-payload-marker" });
1317
+ }
1318
+ if (url.pathname === "/api/slow") {
1319
+ await new Promise((r) => setTimeout(r, 1200));
1320
+ return json({ slow: true, marker: "slow-payload-marker" });
1321
+ }
1322
+ if (url.pathname === "/api/boom") {
1323
+ return json({ error: "内部错误", marker: "boom-marker" }, 500);
1324
+ }
1325
+ if (url.pathname === "/upload" && req.method === "POST") {
1326
+ res.setHeader("access-control-allow-origin", "*");
1327
+ const ct = req.headers["content-type"] || "";
1328
+ const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(ct);
1329
+ if (!m) return json({ error: "不是 multipart 请求", contentType: ct }, 400);
1330
+ const chunks = [];
1331
+ for await (const c of req) chunks.push(c);
1332
+ const parts = parseMultipart(Buffer.concat(chunks), (m[1] || m[2]).trim());
1333
+ const files = [];
1334
+ for (const p of parts) {
1335
+ const cd = /content-disposition:.*/i.exec(p.headers)?.[0] || "";
1336
+ const field = /name="([^"]*)"/i.exec(cd)?.[1] ?? "";
1337
+ const filename = /filename="([^"]*)"/i.exec(cd)?.[1];
1338
+ if (filename === undefined) continue;
1339
+ files.push({
1340
+ field,
1341
+ filename,
1342
+ contentType: /content-type:\s*(\S+)/i.exec(p.headers)?.[1] || "",
1343
+ size: p.body.length,
1344
+ sha256: crypto.createHash("sha256").update(p.body).digest("hex"),
1345
+ preview: p.body.length <= 2048 ? p.body.toString("utf8") : undefined,
1346
+ });
1347
+ }
1348
+ lastUpload = { at: Date.now(), count: files.length, files, marker: "upload-marker" };
1349
+ return json({ ok: true, count: files.length, files, marker: "upload-marker" });
1350
+ }
1351
+ if (url.pathname === "/upload/last") {
1352
+ return json(lastUpload || { count: 0, files: [], empty: true });
1353
+ }
1354
+ res.writeHead(404, { "content-type": "text/plain" });
1355
+ res.end("not found");
1356
+ };
1357
+
1358
+ const guarded = (req, res) => {
1359
+ Promise.resolve()
1360
+ .then(() => handler(req, res))
1361
+ .catch((err) => {
1362
+ const gone = err?.code === "ECONNRESET" || /aborted/i.test(String(err?.message)) || !req.complete || res.destroyed;
1363
+ if (gone) return;
1364
+ process.stderr.write(`[fixture] ${req.method} ${req.url} 处理失败:${err?.stack || err}\n`);
1365
+ try {
1366
+ if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
1367
+ res.end("fixture handler error");
1368
+ } catch {}
1369
+ });
1370
+ };
1371
+
1372
+ const server = http.createServer(guarded);
1373
+ const altServer = http.createServer(guarded);
1374
+
1375
+ process.on("uncaughtException", (err) => {
1376
+ process.stderr.write(`[fixture] 未捕获异常(已忽略,站点继续跑):${err?.stack || err}\n`);
1377
+ });
1378
+ process.on("unhandledRejection", (err) => {
1379
+ process.stderr.write(`[fixture] 未处理拒绝(已忽略,站点继续跑):${err?.stack || err}\n`);
1380
+ });
1381
+
1382
+ server.on("upgrade", (req, socket) => {
1383
+ const key = req.headers["sec-websocket-key"];
1384
+ if (!key) return socket.destroy();
1385
+ const accept = crypto.createHash("sha1").update(key + WS_GUID).digest("base64");
1386
+ socket.write(
1387
+ "HTTP/1.1 101 Switching Protocols\r\n" +
1388
+ "Upgrade: websocket\r\n" +
1389
+ "Connection: Upgrade\r\n" +
1390
+ `Sec-WebSocket-Accept: ${accept}\r\n\r\n`
1391
+ );
1392
+ setTimeout(() => socket.writable && socket.write(encodeFrame(JSON.stringify({ push: "服务端主动推送", marker: "ws-push-marker" }))), 100);
1393
+
1394
+ let buf = Buffer.alloc(0);
1395
+ socket.on("data", (chunk) => {
1396
+ buf = Buffer.concat([buf, chunk]);
1397
+ const { frames, rest } = decodeFrames(buf);
1398
+ buf = rest;
1399
+ for (const f of frames) {
1400
+ if (f.opcode === 8) return socket.end();
1401
+ if (f.opcode === 1) {
1402
+ socket.write(encodeFrame(JSON.stringify({ echo: f.payload, marker: "ws-echo-marker" })));
1403
+ }
1404
+ }
1405
+ });
1406
+ socket.on("error", () => socket.destroy());
1407
+ });
1408
+
1409
+ altServer.listen(0, "127.0.0.1", () => {
1410
+ ALT_BASE = `http://127.0.0.1:${altServer.address().port}`;
1411
+ server.listen(PORT, "127.0.0.1", () => {
1412
+ const p = server.address().port;
1413
+ SELF_BASE = `http://127.0.0.1:${p}`;
1414
+ console.log(`FIXTURE_READY http://127.0.0.1:${p}`);
1415
+ console.log(`FIXTURE_ALT ${ALT_BASE}`);
1416
+ });
1417
+ });
1418
+
1419
+ for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => process.exit(0));