@xbrowser/cli 1.10.0 → 1.12.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 (42) hide show
  1. package/dist/{anti-bot-DR56Y63V.js → anti-bot-GTTYNEFB.js} +1 -1
  2. package/dist/{browser-WQZ3D6AE.js → browser-3HQKDZQ6.js} +4 -2
  3. package/dist/{browser-T3V3JWVH.js → browser-ILXTEWH4.js} +1 -1
  4. package/dist/{browser-HBL72GPZ.js → browser-XPDMY2NX.js} +3 -3
  5. package/dist/{cdp-driver-J3YQ4LJV.js → cdp-driver-ESH3PDE6.js} +2 -1
  6. package/dist/cdp-driver-N2E2ZNSC.js +4644 -0
  7. package/dist/cdp-driver-YIKR4BUX.js +49 -0
  8. package/dist/chunk-3FWLW7FS.js +106 -0
  9. package/dist/chunk-A6LPGFAL.js +437 -0
  10. package/dist/{chunk-RRBXV7KE.js → chunk-DKM2JOZL.js} +633 -63
  11. package/dist/{chunk-ABXMBNQ6.js → chunk-H2A5JUK5.js} +37 -466
  12. package/dist/{chunk-5UGR6MUK.js → chunk-HBHOKZPN.js} +51 -16
  13. package/dist/{chunk-BNO7OKO4.js → chunk-HBMEFSTB.js} +39 -0
  14. package/dist/{chunk-INTQPBYF.js → chunk-JKVUFP3G.js} +6 -2
  15. package/dist/chunk-KJTABK3Z.js +1255 -0
  16. package/dist/{chunk-DWDXEGVK.js → chunk-NKW4A74J.js} +9 -3
  17. package/dist/{chunk-4452SPFI.js → chunk-NODRQGOK.js} +51 -16
  18. package/dist/{chunk-SQHSZENE.js → chunk-OMU63E6J.js} +3 -22
  19. package/dist/{chunk-NITFVWWS.js → chunk-OVW2UEWN.js} +981 -407
  20. package/dist/{chunk-WSCP7QCJ.js → chunk-R6IJ6PIV.js} +14 -11
  21. package/dist/{chunk-YMUSHPU4.js → chunk-SH6OTPXN.js} +46 -16
  22. package/dist/{chunk-MWFHZUIY.js → chunk-TEXCXIBW.js} +1 -1
  23. package/dist/{cdp-driver-2T4P4ZE2.js → chunk-Z6CUR3VG.js} +1542 -134
  24. package/dist/{chunk-IIM5GOD7.js → chunk-ZTHE5RBZ.js} +7 -1
  25. package/dist/cli.js +1136 -584
  26. package/dist/{daemon-client-GKEPT4NY.js → daemon-client-7D6EZNOE.js} +46 -16
  27. package/dist/{daemon-client-O6BYVRXV.js → daemon-client-HEGAXWGK.js} +1 -1
  28. package/dist/daemon-main.js +1031 -522
  29. package/dist/{human-interaction-5AO42MBA.js → human-interaction-4YR2N6R6.js} +2 -2
  30. package/dist/{human-interaction-C5OEGXGO.js → human-interaction-Y5IDH6LD.js} +1 -1
  31. package/dist/{human-interaction-ISXZTAYY.js → human-interaction-ZUTR5AC2.js} +2 -2
  32. package/dist/index.d.ts +10 -0
  33. package/dist/index.js +1147 -593
  34. package/dist/{proxy-C6CK3UH5.js → proxy-LUR4U5YF.js} +2 -1
  35. package/dist/{recovery-J2ISVGUL.js → recovery-FTZGV6VY.js} +2 -2
  36. package/dist/{recovery-ZJVVHP7N.js → recovery-L5GLDX4O.js} +1 -1
  37. package/dist/{recovery-EF33LKRJ.js → recovery-Z3RDZENA.js} +2 -2
  38. package/dist/{session-recorder-H3KEYU26.js → session-recorder-3BEVWHOK.js} +1 -1
  39. package/dist/{session-recorder-QRZMKFVL.js → session-recorder-SLDBENVF.js} +1 -1
  40. package/dist/{session-replayer-LJUC4TI7.js → session-replayer-K4A6OI4M.js} +90 -2
  41. package/package.json +1 -1
  42. package/dist/chunk-BAHSRZIX.js +0 -2191
@@ -1,14 +1,17 @@
1
+ import {
2
+ queryAllJS,
3
+ queryJS
4
+ } from "./chunk-3FWLW7FS.js";
1
5
  import {
2
6
  connectToCDP,
3
- errMsg,
4
- findChrome,
5
- getCDPTargets,
6
- killChrome,
7
7
  launchChrome
8
- } from "./chunk-AMI64BSD.js";
8
+ } from "./chunk-TNEN6VQ2.js";
9
+ import {
10
+ errMsg
11
+ } from "./chunk-GDKLH7ZY.js";
9
12
  import {
10
13
  __require
11
- } from "./chunk-3RG5ZIWI.js";
14
+ } from "./chunk-KFQGP6VL.js";
12
15
 
13
16
  // src/cdp-driver/browser.ts
14
17
  import { EventEmitter as EventEmitter3 } from "events";
@@ -19,6 +22,285 @@ import { EventEmitter as EventEmitter2 } from "events";
19
22
  // src/cdp-driver/page.ts
20
23
  import { EventEmitter } from "events";
21
24
 
25
+ // src/cdp-driver/stealth.ts
26
+ var DEFAULT_STEALTH_CONFIG = {
27
+ bezierCurvature: [0.35, 0.6],
28
+ noiseAmplitude: 5.5,
29
+ overshootRange: [6, 14],
30
+ aimPause: [150, 400],
31
+ pressDuration: [60, 140],
32
+ releaseDrift: [0.8, 2.5],
33
+ landingOffsetSmall: [0.3, 2.5],
34
+ landingOffsetLarge: [1.5, 7],
35
+ smallElementThreshold: 30,
36
+ typingRhythm: {
37
+ fastProb: 0.22,
38
+ fastRange: [25, 60],
39
+ normalRange: [50, 350],
40
+ pauseProb: 0.18,
41
+ pauseRange: [400, 1200]
42
+ },
43
+ keyPressDuration: [50, 110],
44
+ typoProbability: 0.06,
45
+ wheelPeak: 180,
46
+ wheelDecayRate: 0.4
47
+ };
48
+ function rand(min, max) {
49
+ return min + Math.random() * (max - min);
50
+ }
51
+ function cosineEase(t) {
52
+ return 0.5 - 0.5 * Math.cos(Math.PI * t);
53
+ }
54
+ function bezierTrajectory(x0, y0, x1, y1, config = DEFAULT_STEALTH_CONFIG) {
55
+ const dist = Math.hypot(x1 - x0, y1 - y0);
56
+ const n = Math.max(10, Math.min(28, Math.round(dist / 15)));
57
+ const shortMove = dist < 120;
58
+ const curvature = shortMove ? rand(2, 6) : Math.max(dist * rand(...config.bezierCurvature), rand(18, 35));
59
+ const dir = Math.random() < 0.5 ? 1 : -1;
60
+ const d = dist || 1;
61
+ const dx = x1 - x0, dy = y1 - y0;
62
+ const c1x = x0 + dx * 0.3 - dy / d * curvature * 0.5 * dir;
63
+ const c1y = y0 + dy * 0.3 + dx / d * curvature * 0.5 * dir;
64
+ const c2x = x0 + dx * 0.7 - dy / d * curvature * 0.8 * dir;
65
+ const c2y = y0 + dy * 0.7 + dx / d * curvature * 0.8 * dir;
66
+ const points = [];
67
+ for (let i = 1; i <= n; i++) {
68
+ const t = cosineEase(i / n);
69
+ const mt = 1 - t;
70
+ let px = mt ** 3 * x0 + 3 * mt ** 2 * t * c1x + 3 * mt * t ** 2 * c2x + t ** 3 * x1;
71
+ let py = mt ** 3 * y0 + 3 * mt ** 2 * t * c1y + 3 * mt * t ** 2 * c2y + t ** 3 * y1;
72
+ const amp = shortMove ? Math.min(2, config.noiseAmplitude) : config.noiseAmplitude;
73
+ px += rand(-amp, amp);
74
+ py += rand(-amp, amp);
75
+ points.push({ x: px, y: py, delay: rand(9, 16) });
76
+ }
77
+ if (!shortMove) {
78
+ const over = rand(...config.overshootRange);
79
+ const ox = x1 + dx / d * over + rand(-2, 2);
80
+ const oy = y1 + dy / d * over + rand(-2, 2);
81
+ points.push({ x: ox, y: oy, delay: rand(14, 30) });
82
+ points.push({
83
+ x: x1 + dx / d * over * 0.4,
84
+ y: y1 + dy / d * over * 0.4,
85
+ delay: rand(14, 30)
86
+ });
87
+ }
88
+ points.push({ x: x1 + rand(-1, 1), y: y1 + rand(-1, 1), delay: rand(14, 30) });
89
+ return points;
90
+ }
91
+ function landingOffset(width, height, config = DEFAULT_STEALTH_CONFIG) {
92
+ const isSmall = Math.min(width, height) < config.smallElementThreshold;
93
+ const range = isSmall ? config.landingOffsetSmall : config.landingOffsetLarge;
94
+ const dx = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
95
+ const dy = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
96
+ return { dx, dy };
97
+ }
98
+ var KEY_MAP = {};
99
+ for (let i = 97; i <= 122; i++) {
100
+ const ch = String.fromCharCode(i);
101
+ KEY_MAP[ch] = { key: ch, code: "Key" + ch.toUpperCase(), vk: i - 32 };
102
+ }
103
+ for (let i = 65; i <= 90; i++) {
104
+ const ch = String.fromCharCode(i);
105
+ KEY_MAP[ch] = { key: ch, code: "Key" + ch, vk: i, shift: true };
106
+ }
107
+ for (let i = 48; i <= 57; i++) {
108
+ const ch = String.fromCharCode(i);
109
+ KEY_MAP[ch] = { key: ch, code: "Digit" + ch, vk: i };
110
+ }
111
+ Object.assign(KEY_MAP, {
112
+ " ": { key: " ", code: "Space", vk: 32 },
113
+ ".": { key: ".", code: "Period", vk: 190 },
114
+ "-": { key: "-", code: "Minus", vk: 189 },
115
+ "@": { key: "@", code: "Digit2", vk: 50, shift: true },
116
+ "_": { key: "_", code: "Minus", vk: 189, shift: true }
117
+ });
118
+ function buildStealthInitScript() {
119
+ return [
120
+ "(function(){",
121
+ // 1. AEL event proxy
122
+ " var o=EventTarget.prototype.addEventListener;",
123
+ " var fc=new InputDeviceCapabilities({firesTouchEvents:false});",
124
+ " var _ael=function(t,f){",
125
+ " var op=arguments[2];",
126
+ ' if(typeof f!=="function")return o.call(this,t,f,op);',
127
+ " var w=function(e){",
128
+ " if(!e||e.constructor===FocusEvent||e.constructor===KeyboardEvent)return f.call(this,e);",
129
+ " return f.call(this,new Proxy(e,{get:function(k,p){",
130
+ ' if(p==="sourceCapabilities")return fc;',
131
+ ' if(p==="isTrusted")return k.isTrusted;',
132
+ ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])&&k.isTrusted===true){',
133
+ " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;",
134
+ " return k[p]+_f;",
135
+ " }",
136
+ ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
137
+ " }}));",
138
+ " };",
139
+ " return o.call(this,t,w,op);",
140
+ " };",
141
+ " EventTarget.prototype.addEventListener=_ael;",
142
+ // 2. Screen override (prototype-level, not instance-level)
143
+ " var _gw=function(){return 1728};",
144
+ " var _gh=function(){return 1117};",
145
+ " var _gah=function(){return 1092};",
146
+ ' Object.defineProperty(Screen.prototype,"width",{get:_gw,configurable:true});',
147
+ ' Object.defineProperty(Screen.prototype,"height",{get:_gh,configurable:true});',
148
+ ' Object.defineProperty(Screen.prototype,"availWidth",{get:_gw,configurable:true});',
149
+ ' Object.defineProperty(Screen.prototype,"availHeight",{get:_gah,configurable:true});',
150
+ " document.hasFocus=function(){return true};",
151
+ // 4. Canvas/WebGL fingerprint: per-session stable noise (d20).
152
+ // Headless software raster differs subtly from Chrome GPU raster —
153
+ // toDataURL hashes fingerprint the rasterizer. Inject a stable
154
+ // (per-page-load) subpixel shift into fillText so hashes look like a
155
+ // distinct-but-consistent real GPU, and hide the HEADLESS tell in
156
+ // WebGL renderer strings.
157
+ " var _seed=Math.floor(Math.random()*2147483647);",
158
+ " var _prng=function(){_seed=(_seed*48271)%2147483647;return _seed/2147483647;};",
159
+ " var _dx=(_prng()*0.4-0.2).toFixed(3)*1, _dy=(_prng()*0.4-0.2).toFixed(3)*1;",
160
+ " var _fillText=CanvasRenderingContext2D.prototype.fillText;",
161
+ " CanvasRenderingContext2D.prototype.fillText=function(t,x,y,m){",
162
+ " return _fillText.call(this,t,x+_dx,y+_dy,m);",
163
+ " };",
164
+ " var _toDataURL=HTMLCanvasElement.prototype.toDataURL;",
165
+ " HTMLCanvasElement.prototype.toDataURL=function(){",
166
+ ' var ctx=this.getContext("2d");',
167
+ " if(ctx){var d=ctx.getImageData(0,0,Math.min(this.width,2),Math.min(this.height,2));",
168
+ " for(var i=0;i<d.data.length;i+=4){if(d.data[i+3]>0){d.data[i]^=1;break;}}",
169
+ " ctx.putImageData(d,0,0);}",
170
+ " return _toDataURL.apply(this,arguments);",
171
+ " };",
172
+ " try{",
173
+ " var _gl=HTMLCanvasElement.prototype.getContext;",
174
+ " HTMLCanvasElement.prototype.getContext=function(t,o){",
175
+ " var c=_gl.call(this,t,o);",
176
+ ' if(c&&(t==="webgl"||t==="experimental-webgl")&&c.getParameter){',
177
+ " var _gp=c.getParameter.bind(c);",
178
+ " c.getParameter=function(p){",
179
+ " var v=_gp(p);",
180
+ ' if(typeof v==="string"&&/SwiftShader|Software|Rasterizer|Headless/i.test(v))',
181
+ ' return "ANGLE (Apple, ANGLE Metal Renderer: Apple M2 Max, Unspecified Version)";',
182
+ " return v;};}",
183
+ " return c;};",
184
+ " }catch(e){}",
185
+ // 5. AudioContext fingerprint: per-load stable micro-noise on channel
186
+ // data (d21). DSP sum differences between headless software audio and
187
+ // real hardware audio are a classic fingerprint — add ±1e-7 level
188
+ // noise (inaudible, changes the sum hash).
189
+ " try{",
190
+ " var _gcd=AudioBuffer.prototype.getChannelData;",
191
+ " AudioBuffer.prototype.getChannelData=function(ch){",
192
+ " var d=_gcd.call(this,ch);",
193
+ ' var key="__xb_audio_"+ch;',
194
+ " if(!this[key]){",
195
+ " this[key]=true;",
196
+ " for(var i=0;i<d.length;i+=997){d[i]=d[i]+(_prng()-0.5)*2e-7;}",
197
+ " }",
198
+ " return d;",
199
+ " };",
200
+ " var _gffd=AnalyserNode.prototype.getFloatFrequencyData;",
201
+ " AnalyserNode.prototype.getFloatFrequencyData=function(arr){",
202
+ " _gffd.call(this,arr);",
203
+ " for(var i=0;i<arr.length;i+=31){arr[i]=arr[i]+(_prng()-0.5)*0.01;}",
204
+ " };",
205
+ " var _gfbd=AnalyserNode.prototype.getByteFrequencyData;",
206
+ " AnalyserNode.prototype.getByteFrequencyData=function(arr){",
207
+ " _gfbd.call(this,arr);",
208
+ " for(var i=0;i<arr.length;i+=31){arr[i]=(arr[i]+((_prng()*3)|0))&255;}",
209
+ " };",
210
+ " }catch(e){}",
211
+ // 3b. Font metrics + speechSynthesis + battery (d22): headless tells
212
+ " try{",
213
+ " var _mt=CanvasRenderingContext2D.prototype.measureText;",
214
+ ' var _tmw=Object.getOwnPropertyDescriptor(TextMetrics.prototype,"width");',
215
+ " CanvasRenderingContext2D.prototype.measureText=function(t){",
216
+ " var m=_mt.call(this,t);",
217
+ ' try{Object.defineProperty(m,"width",{get:function(){return _tmw.get.call(m)+_dx*0.01;},configurable:true});}catch(e){}',
218
+ " return m;",
219
+ " };",
220
+ " }catch(e){}",
221
+ " try{",
222
+ ' var _fakeVoices=["Alex","Daniel","Karen","Moira","Ralph","Samantha","Ting-Ting","Mei-Jia","Sinji","Yunda"];',
223
+ " var _sv=speechSynthesis.getVoices.bind(speechSynthesis);",
224
+ " speechSynthesis.getVoices=function(){",
225
+ " var real=_sv();",
226
+ " if(real&&real.length)return real;",
227
+ ' return _fakeVoices.map(function(n,i){return {name:n,lang:i<2?"en-US":i<6?"en-GB":"zh-TW",localService:true,default:i===0,voiceURI:n};});',
228
+ " };",
229
+ " }catch(e){}",
230
+ " try{",
231
+ " var _gb=navigator.getBattery.bind(navigator);",
232
+ " navigator.getBattery=function(){",
233
+ " return _gb().then(function(b){",
234
+ ' Object.defineProperty(b,"charging",{get:function(){return true;},configurable:true});',
235
+ " return b;});",
236
+ " };",
237
+ " }catch(e){}",
238
+ // 3c. WebRTC local IP leak guard (d23): headless STUN candidates can
239
+ // expose host IPs; mDNS-only candidates are the modern Chrome default.
240
+ " try{",
241
+ " var _oc=RTCPeerConnection.prototype.createOffer;",
242
+ " RTCPeerConnection.prototype.createOffer=function(){",
243
+ " var p=_oc.apply(this,arguments);",
244
+ " var self=this;",
245
+ " return p.then(function(offer){",
246
+ ' offer.sdp=offer.sdp.split(String.fromCharCode(10)).filter(function(l){return l.indexOf("typ host")<0}).join(String.fromCharCode(10));',
247
+ " return offer;});",
248
+ " };",
249
+ " }catch(e){}",
250
+ // 3d. Chrome object depth (d24): automation fakes usually only set
251
+ // window.chrome = {}; deep checks hit app.run/runtime/csi/loadTimes.
252
+ " try{",
253
+ " if(window.chrome){",
254
+ ' if(!window.chrome.app||!window.chrome.app.run)window.chrome.app={run:function(){},load:function(){},getDetails:function(){return null},InstallState:{DISABLED:"disabled",INSTALLED:"installed",NOT_INSTALLED:"not_installed"},RunningState:{CANNOT_RUN:"cannot_run",READY_TO_RUN:"ready_to_run",RUNNING:"running"}};',
255
+ ' if(!window.chrome.runtime)window.chrome.runtime={OnInstalledReason:{CHROME_UPDATE:"chrome_update",INSTALL:"install",UPDATE:"update"},PlatformOs:{ANDROID:"android",CROS:"cros",LINUX:"linux",MAC:"mac",OPENBSD:"openbsd",WIN:"win"},connect:function(){},sendMessage:function(){},id:undefined};',
256
+ " if(!window.chrome.csi)window.chrome.csi=function(){return{};}",
257
+ " if(!window.chrome.loadTimes)window.chrome.loadTimes=function(){return{};}",
258
+ " }",
259
+ " }catch(e){}",
260
+ // 3e. Font availability patch (d25): headless Chromium misses some system
261
+ // fonts (e.g. Menlo on macOS) that real Chrome has. Register a FontFace
262
+ // aliasing the missing font to a local() equivalent so offsetWidth-based
263
+ // font probing sees the same availability as the faked environment.
264
+ " try{",
265
+ ' var _fontAliases=[["Menlo","Courier New"],["SF Mono","Menlo"],["Segoe UI","Helvetica"]];',
266
+ " _fontAliases.forEach(function(pa){",
267
+ ' try{var ff=new FontFace(pa[0],"local("+JSON.stringify(pa[1])+")");',
268
+ " document.fonts.add(ff);ff.load();}catch(e2){}",
269
+ " });",
270
+ " }catch(e){}",
271
+ // 3. toString disguise (name-list based)
272
+ " var _ts=Function.prototype.toString;",
273
+ " var _hf=document.hasFocus;",
274
+ " Function.prototype.toString=function(){",
275
+ ' if(this===_ael)return"function addEventListener(type, callback) { [native code] }";',
276
+ ' if(this===_hf)return"function hasFocus() { [native code] }";',
277
+ ' if(this===_gw)return"function get width() { [native code] }";',
278
+ ' if(this===_gh)return"function get height() { [native code] }";',
279
+ ' if(this===_gah)return"function get availHeight() { [native code] }";',
280
+ ' if(this===CanvasRenderingContext2D.prototype.fillText)return"function fillText() { [native code] }";',
281
+ ' if(this===HTMLCanvasElement.prototype.toDataURL)return"function toDataURL() { [native code] }";',
282
+ ' if(this===AnalyserNode.prototype.getFloatFrequencyData)return"function getFloatFrequencyData() { [native code] }";',
283
+ ' if(this===AudioBuffer.prototype.getChannelData)return"function getChannelData() { [native code] }";',
284
+ " return _ts.call(this);",
285
+ " };",
286
+ // 4. onclick prototype hijack (dual-stream consistency)
287
+ " var _ba=function(k,p){",
288
+ ' if(p==="isTrusted")return k.isTrusted;',
289
+ ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])&&k.isTrusted===true){',
290
+ " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;return k[p]+_f;",
291
+ " }",
292
+ ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
293
+ " };",
294
+ ' Object.defineProperty(Document.prototype,"onclick",{',
295
+ " configurable:true,",
296
+ " get:function(){var raw=this.__ocRaw||null;if(!raw)return null;var self=this;",
297
+ " return function(e){return raw.call(self,new Proxy(e,{get:function(k,p){return _ba(k,p)}}))}},",
298
+ " set:function(fn){this.__ocRaw=fn}",
299
+ " });",
300
+ "})()"
301
+ ].join("\n");
302
+ }
303
+
22
304
  // src/cdp-driver/mouse.ts
23
305
  var XBMouseImpl = class {
24
306
  conn;
@@ -40,18 +322,46 @@ var XBMouseImpl = class {
40
322
  }
41
323
  async click(x, y, opts = {}) {
42
324
  const button = opts.button ?? "left";
43
- const clickCount = opts.clickCount ?? 1;
44
- const delay = opts.delay ?? 0;
45
- await this.move(x, y);
46
- await this.down({ button });
47
- if (delay > 0) {
48
- await sleep(delay);
325
+ const stealth = opts.stealth ?? process.env.XBROWSER_STEALTH !== "off";
326
+ let tx = x, ty = y;
327
+ if (stealth && opts.elementWidth !== void 0 && opts.elementHeight !== void 0) {
328
+ const off = landingOffset(opts.elementWidth, opts.elementHeight);
329
+ tx += off.dx;
330
+ ty += off.dy;
331
+ }
332
+ if (stealth) {
333
+ const traj = bezierTrajectory(this._x, this._y, tx, ty);
334
+ const _tb = Date.now();
335
+ let _truncated = false;
336
+ for (const p of traj) {
337
+ if (Date.now() - _tb > 5e3) {
338
+ _truncated = true;
339
+ break;
340
+ }
341
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
342
+ this._x = p.x;
343
+ this._y = p.y;
344
+ await sleep(p.delay);
345
+ }
346
+ this._x = tx;
347
+ this._y = ty;
348
+ if (_truncated) {
349
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button });
350
+ }
351
+ await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
352
+ } else {
353
+ await this.move(tx, ty);
49
354
  }
50
- await this.up({ button });
51
- for (let i = 1; i < clickCount; i++) {
52
- if (delay > 0) await sleep(delay);
355
+ await this.down({ button });
356
+ await sleep(stealth ? rand(...DEFAULT_STEALTH_CONFIG.pressDuration) : opts.delay ?? 0);
357
+ const rx = stealth ? this._x + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._x;
358
+ const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
359
+ this._x = rx;
360
+ this._y = ry;
361
+ await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, clickCount: opts.clickCount ?? 1 });
362
+ for (let i = 1; i < (opts.clickCount ?? 1); i++) {
363
+ if (opts.delay) await sleep(opts.delay);
53
364
  await this.down({ button });
54
- if (delay > 0) await sleep(delay);
55
365
  await this.up({ button });
56
366
  }
57
367
  }
@@ -142,12 +452,20 @@ var XBKeyboardImpl = class {
142
452
  }
143
453
  await this.dispatchKeyEvent(downParams);
144
454
  if (mapping.text) {
455
+ if (process.env.XBROWSER_STEALTH !== "off") {
456
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
457
+ }
145
458
  await this.dispatchKeyEvent({
146
459
  type: "char",
147
460
  text: mapping.text
148
461
  });
149
462
  }
150
463
  if (delay > 0) await sleep2(delay);
464
+ else {
465
+ if (process.env.XBROWSER_STEALTH !== "off") {
466
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
467
+ }
468
+ }
151
469
  const upParams = {
152
470
  type: "keyUp",
153
471
  key: mapping.key,
@@ -230,7 +548,7 @@ var XBKeyboardImpl = class {
230
548
  }
231
549
  };
232
550
  function resolveKeyMapping(key) {
233
- if (KEY_MAP[key]) return KEY_MAP[key];
551
+ if (KEY_MAP2[key]) return KEY_MAP2[key];
234
552
  if (key.length === 1) {
235
553
  const lower = key.toLowerCase();
236
554
  if (lower >= "a" && lower <= "z") {
@@ -247,7 +565,7 @@ function resolveKeyMapping(key) {
247
565
  }
248
566
  return { key, code: key };
249
567
  }
250
- var KEY_MAP = {
568
+ var KEY_MAP2 = {
251
569
  Enter: { key: "Enter", code: "Enter", text: "\r", keyCode: 13 },
252
570
  Tab: { key: "Tab", code: "Tab", text: " ", keyCode: 9 },
253
571
  Escape: { key: "Escape", code: "Escape", keyCode: 27 },
@@ -283,96 +601,57 @@ function sleep2(ms) {
283
601
  return new Promise((resolve) => setTimeout(resolve, ms));
284
602
  }
285
603
 
286
- // src/cdp-driver/selector-utils.ts
287
- function queryJS(selector) {
288
- if (selector.startsWith("xpath=")) {
289
- const xpath = JSON.stringify(selector.slice(6));
290
- return `document.evaluate(${xpath}, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue`;
291
- }
292
- if (selector.startsWith("text=")) {
293
- const raw = selector.slice(5);
294
- const exact = raw.startsWith('"') && raw.endsWith('"');
295
- const text = exact ? raw.slice(1, -1) : raw;
296
- return `(() => {
297
- const target = ${JSON.stringify(text)};
298
- const exact = ${exact};
299
- const els = [...document.querySelectorAll('*')].filter(e => {
300
- if (e.children.length > 0) return false;
301
- if (e.offsetParent === null) return false;
302
- const t = (e.textContent || '').trim();
303
- if (!t) return false;
304
- return exact ? t === target : t.toLowerCase().includes(target.toLowerCase());
305
- });
306
- return els[0] || null;
307
- })()`;
308
- }
309
- if (selector.startsWith("popup-text=")) {
310
- const text = selector.slice("popup-text=".length);
311
- return `(() => {
312
- const target = ${JSON.stringify(text)};
313
- const els = [...document.querySelectorAll('*')].filter(e => {
314
- if (e.children.length > 0) return false;
315
- if (e.offsetParent === null) return false;
316
- if ((e.textContent || '').trim() !== target) return false;
317
- return true;
318
- });
319
- return els[0] || null;
320
- })()`;
321
- }
322
- return `document.querySelector(${JSON.stringify(selector)})`;
323
- }
324
- function queryAllJS(selector) {
325
- if (selector.startsWith("xpath=")) {
326
- const xpath = JSON.stringify(selector.slice(6));
327
- return `(() => { const it = document.evaluate(${xpath}, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); const r=[]; for(let i=0;i<it.snapshotLength;i++) r.push(it.snapshotItem(i)); return r; })()`;
328
- }
329
- if (selector.startsWith("text=") || selector.startsWith("popup-text=")) {
330
- return `(() => { const el = ${queryJS(selector)}; return el ? [el] : []; })()`;
331
- }
332
- return `document.querySelectorAll(${JSON.stringify(selector)})`;
333
- }
334
-
335
604
  // src/cdp-driver/actionability.ts
336
605
  async function waitForActionable(page, selector, opts = {}) {
337
606
  const timeout = opts.timeout ?? 3e4;
338
607
  if (opts.force) {
339
- if (selector.startsWith("xpath=")) {
340
- const rect2 = await page.evaluate(`
608
+ const deadline2 = Date.now() + timeout;
609
+ let lastError;
610
+ while (Date.now() < deadline2) {
611
+ const rect = await page.evaluate(`
341
612
  (function() {
342
613
  const el = ${queryJS(selector)};
343
614
  if (!el) return null;
344
615
  const r = el.getBoundingClientRect();
345
- return { x: r.x, y: r.y, width: r.width, height: r.height };
616
+ let x = r.x, y = r.y;
617
+ let doc = el.ownerDocument;
618
+ while (doc !== document) {
619
+ let host = null;
620
+ const scan = (d) => {
621
+ let frames;
622
+ try { frames = d.querySelectorAll('iframe'); } catch (e) { return null; }
623
+ for (const f of frames) {
624
+ let inner = null;
625
+ try { inner = f.contentDocument; } catch (e) { continue; }
626
+ if (!inner) continue;
627
+ if (inner === doc) return f;
628
+ const rr = scan(inner);
629
+ if (rr) return rr;
630
+ }
631
+ return null;
632
+ };
633
+ host = scan(document);
634
+ if (!host) break;
635
+ const hr = host.getBoundingClientRect();
636
+ x += hr.x; y += hr.y;
637
+ doc = host.ownerDocument;
638
+ }
639
+ return { x, y, width: r.width, height: r.height };
346
640
  })()
347
- `);
348
- if (!rect2) throw new Error(`Element not found: ${selector}`);
349
- return { nodeId: 0, rect: rect2 };
350
- }
351
- const deadline2 = Date.now() + timeout;
352
- let lastError;
353
- let nodeId = 0;
354
- let rect = null;
355
- while (Date.now() < deadline2) {
356
- nodeId = await page.querySelector(selector);
357
- if (!nodeId) {
358
- lastError = `Element not found: ${selector}`;
359
- await page.waitForTimeout(200);
360
- continue;
361
- }
362
- rect = await page.getBoxModel(nodeId);
363
- if (rect) break;
364
- lastError = `Element has no box: ${selector}`;
365
- await page.waitForTimeout(500);
641
+ `).catch(() => null);
642
+ if (rect && rect.width > 0 && rect.height > 0) return { nodeId: 0, rect };
643
+ lastError = `Element not visible (zero size): ${selector}`;
644
+ lastError = `Element not found: ${selector}`;
645
+ await page.waitForTimeout(200);
366
646
  }
367
- if (!rect) throw new Error(lastError || `Element has no box: ${selector}`);
368
- return { nodeId, rect };
647
+ throw new Error(lastError || `Element not found: ${selector}`);
369
648
  }
370
649
  const deadline = Date.now() + timeout;
371
650
  while (Date.now() < deadline) {
372
651
  const result = await checkActionable(page, selector);
373
652
  if (result.ok && result.rect) {
374
- const nodeId = await page.querySelector(selector);
375
- if (nodeId) return { nodeId, rect: result.rect };
653
+ const nodeId = await page.querySelector(selector).catch(() => 0) ?? 0;
654
+ return { nodeId, rect: result.rect };
376
655
  }
377
656
  await page.waitForTimeout(50);
378
657
  }
@@ -405,12 +684,25 @@ async function checkActionable(page, selector) {
405
684
  return { ok: false, reason: 'parent_disabled' };
406
685
  }
407
686
 
408
- // Check not covered by another element at center
687
+ // Check not covered by another element at center.
688
+ // elementFromPoint must run in the element's OWN document: for iframe-
689
+ // internal elements the main-document hit-test returns the <iframe>
690
+ // host itself, which falsely reports "covered" (rec-duel d01).
691
+ // For shadow-internal elements the hit-test retargets to the shadow
692
+ // HOST \u2014 walk the host chain before declaring coverage (rec-duel d04).
409
693
  const cx = rect.x + rect.width / 2;
410
694
  const cy = rect.y + rect.height / 2;
411
- const topEl = document.elementFromPoint(cx, cy);
695
+ const topEl = el.ownerDocument.elementFromPoint(cx, cy);
412
696
  if (topEl && topEl !== el && !el.contains(topEl) && !topEl.contains(el)) {
413
- return { ok: false, reason: 'covered', rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height } };
697
+ let hostChain = [];
698
+ let rootNode = el.getRootNode();
699
+ while (rootNode && rootNode.host) {
700
+ hostChain.push(rootNode.host);
701
+ rootNode = rootNode.host.getRootNode();
702
+ }
703
+ if (!hostChain.includes(topEl)) {
704
+ return { ok: false, reason: 'covered', rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height } };
705
+ }
414
706
  }
415
707
 
416
708
  return {
@@ -455,21 +747,48 @@ var XBLocatorImpl = class _XBLocatorImpl {
455
747
  const el = ${this._q(this.selector)};
456
748
  if (!el) return null;
457
749
  const rect = el.getBoundingClientRect();
458
- return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
750
+ let x = rect.x, y = rect.y;
751
+ let doc = el.ownerDocument;
752
+ while (doc !== document) {
753
+ let host = null;
754
+ const scan = (d) => {
755
+ let frames;
756
+ try { frames = d.querySelectorAll('iframe'); } catch (e) { return null; }
757
+ for (const f of frames) {
758
+ let inner = null;
759
+ try { inner = f.contentDocument; } catch (e) { continue; }
760
+ if (!inner) continue;
761
+ if (inner === doc) return f;
762
+ const r = scan(inner);
763
+ if (r) return r;
764
+ }
765
+ return null;
766
+ };
767
+ host = scan(document);
768
+ if (!host) break;
769
+ const hr = host.getBoundingClientRect();
770
+ x += hr.x; y += hr.y;
771
+ doc = host.ownerDocument;
772
+ }
773
+ return { x, y, width: rect.width, height: rect.height };
459
774
  })()
460
775
  `);
461
776
  const finalRect = updatedRect ?? rect;
462
777
  const cx = finalRect.x + finalRect.width / 2;
463
778
  const cy = finalRect.y + finalRect.height / 2;
464
779
  await this.page.mouse.click(cx, cy, {
465
- button: opts.button ?? "left",
466
- clickCount: opts.clickCount ?? 1,
467
- delay: opts.delay
780
+ stealth: true,
781
+ elementWidth: finalRect.width,
782
+ elementHeight: finalRect.height,
783
+ ...{ button: opts.button ?? "left", clickCount: opts.clickCount ?? 1, delay: opts.delay }
468
784
  });
469
785
  }
470
786
  async fill(value, opts = {}) {
471
787
  await waitForActionable(this.page, this.selector, opts);
472
788
  await scrollIntoView(this.page, this.selector);
789
+ await this.click({ ...opts });
790
+ await this.page.keyboard.type(value, { stealth: true });
791
+ return;
473
792
  await this.page.evaluate(`
474
793
  (function() {
475
794
  const el = ${this._q(this.selector)};
@@ -1179,6 +1498,8 @@ var XBPageImpl = class _XBPageImpl {
1179
1498
  await this.conn.send("Page.enable", void 0, this.sessionId);
1180
1499
  await this.conn.send("Runtime.enable", void 0, this.sessionId);
1181
1500
  await this.conn.send("Network.enable", void 0, this.sessionId);
1501
+ await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
1502
+ });
1182
1503
  this.setupPageEvents();
1183
1504
  this.setupNetworkEvents();
1184
1505
  this.setupConsoleEvents();
@@ -1191,6 +1512,9 @@ var XBPageImpl = class _XBPageImpl {
1191
1512
  );
1192
1513
  this._url = info.url;
1193
1514
  this._title = info.title;
1515
+ if (info.url && info.url !== "about:blank" && info.url !== "") {
1516
+ this._loadState = { loadFired: true, domContentFired: true, networkIdle: true };
1517
+ }
1194
1518
  } catch {
1195
1519
  }
1196
1520
  }
@@ -1203,6 +1527,16 @@ var XBPageImpl = class _XBPageImpl {
1203
1527
  const waitUntil = opts.waitUntil ?? "load";
1204
1528
  const timeout = opts.timeout ?? 3e4;
1205
1529
  this._loadState = { loadFired: false, domContentFired: false, networkIdle: false };
1530
+ if (process.env.XBROWSER_STEALTH !== "off") {
1531
+ try {
1532
+ await this.conn.send(
1533
+ "Page.addScriptToEvaluateOnNewDocument",
1534
+ { source: buildStealthInitScript() },
1535
+ this.sessionId
1536
+ );
1537
+ } catch {
1538
+ }
1539
+ }
1206
1540
  const result = await this.conn.send(
1207
1541
  "Page.navigate",
1208
1542
  { url, referrer: opts.referer },
@@ -1410,6 +1744,91 @@ Last error: ${lastError.message}` : "";
1410
1744
  }
1411
1745
  return result.result?.value;
1412
1746
  }
1747
+ /**
1748
+ * 在指定 iframe 上下文中执行表达式(攻防 D16 能力建设,2026-08-19)。
1749
+ *
1750
+ * 双路径:
1751
+ * 1. 同进程 iframe —— Runtime.enable 收集 executionContextCreated,
1752
+ * 找到目标 frameId 的 contextId,用 contextId 定向执行;
1753
+ * 2. 跨域 OOPIF(独立 target)—— Target.setAutoAttach(flatten) 监听
1754
+ * attachedToTarget 中 type==='iframe' 的会话,用其 sessionId 执行。
1755
+ *
1756
+ * 这绕过了页面同源策略(那是页面 JS 的约束,CDP 是调试通道)——
1757
+ * 支付窗/验证码/第三方嵌入内容的读写都靠它。
1758
+ */
1759
+ async evaluateInFrame(urlIncludes, expression) {
1760
+ if (this._closed) throw new Error("Page is closed");
1761
+ const evalIn = async (sessionId, contextId) => {
1762
+ const params = { expression, returnByValue: true, awaitPromise: true };
1763
+ if (contextId !== void 0) params.contextId = contextId;
1764
+ const result = await this.conn.send("Runtime.evaluate", params, sessionId);
1765
+ if (result.exceptionDetails) {
1766
+ const detail = result.exceptionDetails.exception?.description ?? result.exceptionDetails.exception?.value ?? result.exceptionDetails.text;
1767
+ throw new Error(`[frame ${urlIncludes}] ${detail}`);
1768
+ }
1769
+ return result.result?.value;
1770
+ };
1771
+ try {
1772
+ const tg = await this.conn.send("Target.getTargets", void 0);
1773
+ const hit2 = (tg.targetInfos || []).find((t) => t.type === "iframe" && (t.url || "").includes(urlIncludes));
1774
+ if (hit2) {
1775
+ const att = await this.conn.send("Target.attachToTarget", { targetId: hit2.targetId, flatten: true });
1776
+ return evalIn(att.sessionId);
1777
+ }
1778
+ } catch {
1779
+ }
1780
+ const tree = await this.conn.send("Page.getFrameTree", void 0, this.sessionId);
1781
+ const all = [];
1782
+ const walk = (node) => {
1783
+ all.push({ id: node.frame.id, url: node.frame.url });
1784
+ for (const child of node.childFrames || []) walk(child);
1785
+ };
1786
+ walk(tree.frameTree);
1787
+ const mainId = tree.frameTree?.frame?.id;
1788
+ const target = all.find((f) => f.id !== mainId && f.url.includes(urlIncludes));
1789
+ if (target) {
1790
+ const contexts = [];
1791
+ const onCtx = (raw) => {
1792
+ const c = raw?.context;
1793
+ if (c?.id && c?.auxData?.frameId) contexts.push({ id: c.id, frameId: c.auxData.frameId });
1794
+ };
1795
+ this.conn.on("Runtime.executionContextCreated", onCtx);
1796
+ try {
1797
+ await this.conn.send("Runtime.enable", void 0, this.sessionId).catch(() => {
1798
+ });
1799
+ await new Promise((r) => setTimeout(r, 400));
1800
+ } finally {
1801
+ this.conn.off("Runtime.executionContextCreated", onCtx);
1802
+ }
1803
+ const ctx = contexts.find((c) => c.frameId === target.id);
1804
+ if (ctx) return evalIn(this.sessionId, ctx.id);
1805
+ }
1806
+ const attached = [];
1807
+ const onAttach = (raw) => {
1808
+ const ev = raw;
1809
+ if (ev?.sessionId && ev.targetInfo?.type === "iframe") {
1810
+ attached.push({ sessionId: ev.sessionId, url: ev.targetInfo.url || "" });
1811
+ }
1812
+ };
1813
+ this.conn.on("Target.attachedToTarget", onAttach);
1814
+ try {
1815
+ await this.conn.send("Target.setAutoAttach", {
1816
+ autoAttach: true,
1817
+ waitForDebuggerOnStart: false,
1818
+ flatten: true
1819
+ }, this.sessionId);
1820
+ await new Promise((r) => setTimeout(r, 600));
1821
+ } finally {
1822
+ this.conn.off("Target.attachedToTarget", onAttach);
1823
+ this.conn.send("Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, this.sessionId).catch(() => {
1824
+ });
1825
+ }
1826
+ const hit = attached.find((a) => a.url.includes(urlIncludes));
1827
+ if (!hit) {
1828
+ throw new Error(`frame not found for "${urlIncludes}"\uFF08OOPIF target\u3001frame \u6811\u3001auto-attach \u4E09\u8DEF\u5747\u672A\u547D\u4E2D\uFF1B\u53EF\u80FD\u4ECD\u5728\u52A0\u8F7D\uFF09`);
1829
+ }
1830
+ return evalIn(hit.sessionId);
1831
+ }
1413
1832
  /** evaluateHandle — evaluates fn and returns a handle for element bounding box */
1414
1833
  async evaluateHandle(fn, ...args) {
1415
1834
  let expression;
@@ -1654,6 +2073,10 @@ Last error: ${lastError.message}` : "";
1654
2073
  this.sessionId
1655
2074
  );
1656
2075
  }
2076
+ /** 覆盖 User-Agent(headless 环境对抗 UA 检测的标配能力) */
2077
+ async setUserAgent(userAgent) {
2078
+ await this._setUserAgent(userAgent);
2079
+ }
1657
2080
  /** Internal: set extra HTTP headers */
1658
2081
  async _setExtraHTTPHeaders(headers) {
1659
2082
  await this.setExtraHTTPHeaders(headers);
@@ -1780,16 +2203,21 @@ Last error: ${lastError.message}` : "";
1780
2203
  }
1781
2204
  return 1;
1782
2205
  }
1783
- const doc = await this.conn.send(
1784
- "DOM.getDocument",
1785
- { depth: 0 },
1786
- this.sessionId
2206
+ const withTimeout = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r(null), ms))]);
2207
+ const doc = await withTimeout(
2208
+ this.conn.send("DOM.getDocument", { depth: 0 }, this.sessionId),
2209
+ 8e3
1787
2210
  );
1788
- const result = await this.conn.send(
1789
- "DOM.querySelector",
1790
- { nodeId: doc.root.nodeId, selector },
1791
- this.sessionId
2211
+ if (!doc) return 0;
2212
+ const result = await withTimeout(
2213
+ this.conn.send(
2214
+ "DOM.querySelector",
2215
+ { nodeId: doc.root.nodeId, selector },
2216
+ this.sessionId
2217
+ ),
2218
+ 8e3
1792
2219
  );
2220
+ if (!result) return 0;
1793
2221
  return result.nodeId;
1794
2222
  }
1795
2223
  /** Query all matching elements, returns array of CDP nodeIds */
@@ -2587,7 +3015,7 @@ var XBBrowserImpl = class {
2587
3015
  this._exitHandler = null;
2588
3016
  }
2589
3017
  if (this.childProcess) {
2590
- const { killChrome: killChrome2 } = await import("./launcher-OZXJQPNG.js");
3018
+ const { killChrome: killChrome2 } = await import("./launcher-L2JNDB2H.js");
2591
3019
  await killChrome2(this.childProcess, this.tmpDir);
2592
3020
  }
2593
3021
  await this.conn.close();
@@ -2722,7 +3150,7 @@ var XBBrowserImpl = class {
2722
3150
  if (pageTargets.length === 0 && httpFallbackUrl) {
2723
3151
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
2724
3152
  try {
2725
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-OZXJQPNG.js");
3153
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-L2JNDB2H.js");
2726
3154
  const httpPages = await getCDPTargets2(httpFallbackUrl);
2727
3155
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
2728
3156
  for (const p of httpPages) {
@@ -2778,9 +3206,971 @@ var XBBrowserImpl = class {
2778
3206
  // src/cdp-driver/connection.ts
2779
3207
  import { EventEmitter as EventEmitter4 } from "events";
2780
3208
  import { WebSocket } from "ws";
2781
- var CDPConnection = class extends EventEmitter4 {
3209
+
3210
+ // src/cdp-interceptor/rules/shared.ts
3211
+ var PLAYWRIGHT_INTERNAL_MARKERS = [
3212
+ "__commonJS",
3213
+ "module.exports",
3214
+ "__require",
3215
+ "__toESM",
3216
+ "inject_utils"
3217
+ ];
3218
+ function isPlaywrightInternal(code) {
3219
+ return PLAYWRIGHT_INTERNAL_MARKERS.some((marker) => code.includes(marker));
3220
+ }
3221
+ function extractUserCode(ctx) {
3222
+ if (ctx.method === "Runtime.evaluate") {
3223
+ const expr = ctx.params.expression;
3224
+ if (typeof expr === "string") {
3225
+ if (isPlaywrightInternal(expr)) return null;
3226
+ return expr;
3227
+ }
3228
+ }
3229
+ if (ctx.method === "Runtime.callFunctionOn") {
3230
+ const decl = ctx.params.functionDeclaration;
3231
+ if (typeof decl === "string" && decl.includes("utilityScript.evaluate")) {
3232
+ return extractAllStrings(ctx.params.arguments);
3233
+ }
3234
+ if (typeof decl === "string") return decl;
3235
+ }
3236
+ return null;
3237
+ }
3238
+ function extractAllStrings(rawArgs) {
3239
+ if (!Array.isArray(rawArgs)) return null;
3240
+ const strings = [];
3241
+ for (const arg of rawArgs) {
3242
+ if (arg && typeof arg === "object" && "value" in arg) {
3243
+ const val = arg.value;
3244
+ if (typeof val === "string" && val.length > 5 && !["true", "false"].includes(val)) {
3245
+ strings.push(val);
3246
+ }
3247
+ }
3248
+ }
3249
+ return strings.length > 0 ? strings.join("\n") : null;
3250
+ }
3251
+
3252
+ // src/cdp-interceptor/rules/dom-mutation.ts
3253
+ var DOM_PATTERNS = [
3254
+ // ── P0: Value/Checked (bypasses React onChange) ────────────
3255
+ { pattern: /\.value\s*=\s*(?!["'\s]*$)/, name: ".value =", severity: "danger", action: "pass", errorCode: -32001, suggestion: "Use page.fill(selector, value) which dispatches proper input/change events." },
3256
+ { pattern: /\.checked\s*=\s*(?:true|false)/, name: ".checked =", severity: "danger", action: "pass", errorCode: -32001, suggestion: "Use page.check(selector) or page.uncheck(selector)." },
3257
+ { pattern: /\.indeterminate\s*=\s*true/, name: ".indeterminate =", severity: "warn", action: "pass", errorCode: -32021, suggestion: "No human can set indeterminate state \u2014 remove this call." },
3258
+ { pattern: /\.valueAsDate\s*=/, name: ".valueAsDate =", severity: "warn", action: "pass", errorCode: -32022, suggestion: "Use page.fill() with formatted date string instead." },
3259
+ { pattern: /\.valueAsNumber\s*=/, name: ".valueAsNumber =", severity: "warn", action: "pass", errorCode: -32022, suggestion: "Use page.fill() with numeric string instead." },
3260
+ // ── P1: Select/Option (bypasses React onChange on select) ─
3261
+ { pattern: /\.selectedIndex\s*=\s*\d+/, name: ".selectedIndex =", severity: "danger", action: "pass", errorCode: -32003, suggestion: "Use page.selectOption(selector, value)." },
3262
+ { pattern: /(?:options|children)\s*\[[^\]]*\]\s*\.\s*selected\s*=\s*(?:true|false)/, name: "options[N].selected =", severity: "danger", action: "pass", errorCode: -32003, suggestion: "Use page.selectOption(selector, value)." },
3263
+ { pattern: /\.value\s*=\s*["'][^"']*["']\s*[;)]?\s*$/, name: "selectElement.value =", severity: "warn", action: "pass", errorCode: -32023, suggestion: "For select elements, use page.selectOption(selector, value)." },
3264
+ // ── P2: Content properties (bypasses virtual DOM diffing) ──
3265
+ { pattern: /\.innerHTML\s*=/, name: ".innerHTML =", severity: "info", action: "pass", errorCode: -32007, suggestion: ".innerHTML bypasses React/Vue diffing. Use component state or page.setContent()." },
3266
+ { pattern: /\.outerHTML\s*=/, name: ".outerHTML =", severity: "info", action: "pass", errorCode: -32007, suggestion: "outerHTML replacement destroys React fiber tree. Use page.setContent()." },
3267
+ { pattern: /\.innerText\s*=/, name: ".innerText =", severity: "warn", action: "pass", errorCode: -32024, suggestion: "Framework components should be updated via state, not innerText." },
3268
+ { pattern: /\.textContent\s*=/, name: ".textContent =", severity: "warn", action: "pass", errorCode: -32024, suggestion: "textContent bypasses React/Vue diffing. Use component state instead." },
3269
+ { pattern: /\.outerText\s*=/, name: ".outerText =", severity: "warn", action: "pass", errorCode: -32024, suggestion: "Non-standard property \u2014 use proper framework update methods." },
3270
+ { pattern: /nodeValue\s*=/, name: "node.nodeValue =", severity: "info", action: "pass", errorCode: -32025, suggestion: "Direct text node mutation. Use textContent instead if needed." },
3271
+ // ── P3: Style properties ──────────────────────────────────
3272
+ { pattern: /\.style\s*=\s*["']/, name: ".style = (string override)", severity: "info", action: "pass", errorCode: -32008, suggestion: 'Setting style as a string overwrites CSSStyleDeclaration. Use element.style.prop = "value".' },
3273
+ { pattern: /\.style\.cssText\s*=/, name: ".style.cssText =", severity: "info", action: "pass", errorCode: -32008, suggestion: "style.cssText replacement destroys inline styles \u2014 use individual property set." },
3274
+ { pattern: /\.style\.setProperty\s*\(/, name: ".style.setProperty()", severity: "info", action: "pass", errorCode: -32008, suggestion: "Direct style property set bypasses CSS transitions." },
3275
+ { pattern: /\.style\.removeProperty\s*\(/, name: ".style.removeProperty()", severity: "info", action: "pass", errorCode: -32026, suggestion: "Style removal without user interaction is suspicious." },
3276
+ { pattern: /\.style\.animation\s*=/, name: ".style.animation =", severity: "info", action: "pass", errorCode: -32027, suggestion: "Forcing animation state via CDP is detectable." },
3277
+ { pattern: /\.style\.transition\s*=/, name: ".style.transition =", severity: "info", action: "pass", errorCode: -32027, suggestion: "Manipulating CSS transitions is rare in normal browsing." },
3278
+ // ── P4: Class/Attribute properties ────────────────────────
3279
+ { pattern: /\.className\s*=/, name: ".className =", severity: "info", action: "pass", errorCode: -32009, suggestion: "Use component state or a Playwright locator instead." },
3280
+ { pattern: /\.classList\.add\s*\(/, name: ".classList.add()", severity: "info", action: "pass", errorCode: -32009, suggestion: "classList manipulation via CDP bypasses framework state tracking." },
3281
+ { pattern: /\.classList\.remove\s*\(/, name: ".classList.remove()", severity: "info", action: "pass", errorCode: -32009, suggestion: "Use component state or attribute selectors instead." },
3282
+ { pattern: /\.classList\.toggle\s*\(/, name: ".classList.toggle()", severity: "info", action: "pass", errorCode: -32009, suggestion: "Toggle without user interaction is detectable." },
3283
+ { pattern: /\.classList\.replace\s*\(/, name: ".classList.replace()", severity: "info", action: "pass", errorCode: -32028, suggestion: "Rare operation \u2014 likely automated." },
3284
+ // ── P5: Attribute manipulation ────────────────────────────
3285
+ { pattern: /\.setAttribute\s*\(/, name: ".setAttribute()", severity: "info", action: "pass", errorCode: -32010, suggestion: "setAttribute bypasses framework attribute tracking. Use component state." },
3286
+ { pattern: /\.removeAttribute\s*\(/, name: ".removeAttribute()", severity: "info", action: "pass", errorCode: -32010, suggestion: "Attribute removal without user interaction is suspicious." },
3287
+ { pattern: /\.toggleAttribute\s*\(/, name: ".toggleAttribute()", severity: "info", action: "pass", errorCode: -32029, suggestion: "Attribute toggling via CDP is detectable." },
3288
+ { pattern: /\.dataset\.\w+\s*=/, name: ".dataset.* =", severity: "info", action: "pass", errorCode: -32030, suggestion: "dataset mutations via evaluate bypass native mutation observers." },
3289
+ // ── P6: Focus/Selection properties ────────────────────────
3290
+ { pattern: /\.selectionStart\s*=/, name: ".selectionStart =", severity: "info", action: "pass", errorCode: -32011, suggestion: "Setting cursor position without focus is detectable." },
3291
+ { pattern: /\.selectionEnd\s*=/, name: ".selectionEnd =", severity: "info", action: "pass", errorCode: -32011, suggestion: "Selection range manipulation without user input is suspicious." },
3292
+ { pattern: /\.selectionDirection\s*=/, name: ".selectionDirection =", severity: "info", action: "pass", errorCode: -32031, suggestion: "Selection direction changes normally via mouse drag." },
3293
+ // ── P7: Boolean properties ────────────────────────────────
3294
+ { pattern: /\.disabled\s*=/, name: ".disabled =", severity: "info", action: "pass", errorCode: -32012, suggestion: "Disabling elements via CDP mid-interaction is detectable." },
3295
+ { pattern: /\.readOnly\s*=/, name: ".readOnly =", severity: "info", action: "pass", errorCode: -32032, suggestion: "readOnly changes without user action." },
3296
+ { pattern: /\.hidden\s*=/, name: ".hidden =", severity: "info", action: "pass", errorCode: -32012, suggestion: "Hiding elements is a common scraper tactic \u2014 detectable." },
3297
+ { pattern: /\.required\s*=/, name: ".required =", severity: "info", action: "pass", errorCode: -32032, suggestion: "Validation constraint changes mid-session." },
3298
+ { pattern: /\.multiple\s*=/, name: ".multiple =", severity: "info", action: "pass", errorCode: -32032, suggestion: "Multiple attribute toggle is rare in normal browsing." },
3299
+ { pattern: /\.autofocus\s*=/, name: ".autofocus =", severity: "info", action: "pass", errorCode: -32032, suggestion: "autofocus changes mid-session are suspicious." },
3300
+ // ── P8: Frame/Navigation properties ───────────────────────
3301
+ { pattern: /\.src\s*=/, name: ".src = (on img/iframe/script)", severity: "info", action: "pass", errorCode: -32013, suggestion: "Changing src via CDP bypasses user interaction. Use page.click() on the element." },
3302
+ { pattern: /\.href\s*=/, name: ".href =", severity: "info", action: "pass", errorCode: -32033, suggestion: "Changing anchor href via evaluate \u2014 use page.click() instead." },
3303
+ { pattern: /\.action\s*=/, name: "form.action =", severity: "info", action: "pass", errorCode: -32034, suggestion: "Changing form action URL is highly suspicious." },
3304
+ { pattern: /\.method\s*=/, name: "form.method =", severity: "info", action: "pass", errorCode: -32034, suggestion: "Form method changes without user interaction." },
3305
+ { pattern: /\.target\s*=/, name: "link/area.target =", severity: "info", action: "pass", errorCode: -32034, suggestion: "Link target manipulation via CDP." },
3306
+ // ── P9: Media properties ──────────────────────────────────
3307
+ { pattern: /\.currentTime\s*=/, name: "media.currentTime = (seeking)", severity: "info", action: "pass", errorCode: -32014, suggestion: "Video seeking without user interaction \u2014 common scraper pattern." },
3308
+ { pattern: /\.playbackRate\s*=/, name: "media.playbackRate =", severity: "info", action: "pass", errorCode: -32014, suggestion: "Changing playback speed is detectable automation signal." },
3309
+ { pattern: /\.volume\s*=/, name: "media.volume =", severity: "info", action: "pass", errorCode: -32035, suggestion: "Volume setting via evaluate is suspicious." },
3310
+ { pattern: /\.muted\s*=/, name: "media.muted =", severity: "info", action: "pass", errorCode: -32035, suggestion: "Muting media without user click is suspicious." },
3311
+ // ── P10: Element geometry ─────────────────────────────────
3312
+ { pattern: /\.scrollTop\s*=/, name: ".scrollTop =", severity: "info", action: "pass", errorCode: -32015, suggestion: "Programmatic scroll without user gesture. Use page.mouse.wheel()." },
3313
+ { pattern: /\.scrollLeft\s*=/, name: ".scrollLeft =", severity: "info", action: "pass", errorCode: -32015, suggestion: "Horizontal scroll without user gesture." },
3314
+ { pattern: /\.scrollTo\s*\(/, name: ".scrollTo()", severity: "info", action: "pass", errorCode: -32015, suggestion: "ScrollTo bypasses user scroll detection." },
3315
+ { pattern: /\.scrollBy\s*\(/, name: ".scrollBy()", severity: "info", action: "pass", errorCode: -32015, suggestion: "ScrollBy without user gesture." },
3316
+ { pattern: /\.scrollIntoView\s*\(/, name: ".scrollIntoView()", severity: "info", action: "pass", errorCode: -32015, suggestion: "scrollIntoView is a common bot pattern. Let Playwright handle scrolling." },
3317
+ // ── P11: Shadow DOM ───────────────────────────────────────
3318
+ { pattern: /\.shadowRoot\s*=/, name: ".shadowRoot = (override)", severity: "info", action: "pass", errorCode: -32036, suggestion: "ShadowRoot is read-only \u2014 this set attempt is detectable." },
3319
+ // ── P12: Force reflow / layout thrashing ──────────────────
3320
+ { pattern: /\.offsetHeight\b(?!\s*===?\s*)/, name: ".offsetHeight read (forced reflow)", severity: "warn", action: "pass", errorCode: -32016, suggestion: "Reading offsetHeight triggers forced reflow \u2014 anti-crawlers detect this as layout probing." },
3321
+ { pattern: /\.offsetWidth\b(?!\s*===?\s*)/, name: ".offsetWidth read (forced reflow)", severity: "warn", action: "pass", errorCode: -32016, suggestion: "Reading offsetWidth triggers forced reflow \u2014 detectable." },
3322
+ { pattern: /getBoundingClientRect\s*\(/, name: "getBoundingClientRect()", severity: "warn", action: "pass", errorCode: -32037, suggestion: "getBoundingClientRect triggers reflow. Minimize calls." },
3323
+ { pattern: /getComputedStyle\s*\(/, name: "getComputedStyle()", severity: "info", action: "pass", errorCode: -32038, suggestion: "getComputedStyle can trigger style recalculation." },
3324
+ { pattern: /\.clientHeight\b/, name: ".clientHeight read", severity: "info", action: "pass", errorCode: -32038, suggestion: "clientHeight read triggers layout." },
3325
+ { pattern: /\.clientWidth\b/, name: ".clientWidth read", severity: "info", action: "pass", errorCode: -32038, suggestion: "clientWidth read triggers layout." }
3326
+ ];
3327
+ var domMutationRule = {
3328
+ id: "dom-mutation",
3329
+ name: "DOM Property Mutation Detection (50+ setters)",
3330
+ priority: 10,
3331
+ canHandle(ctx) {
3332
+ return ctx.method === "Runtime.evaluate" || ctx.method === "Runtime.callFunctionOn";
3333
+ },
3334
+ evaluate(ctx) {
3335
+ const userCode = extractUserCode(ctx);
3336
+ if (!userCode) return null;
3337
+ for (const p of DOM_PATTERNS) {
3338
+ if (p.pattern.test(userCode)) {
3339
+ return {
3340
+ ruleId: "dom-mutation",
3341
+ action: p.action,
3342
+ severity: p.severity,
3343
+ reason: `Direct DOM property setter: "${p.name}". This bypasses framework event systems and is detectable as automation.`,
3344
+ suggestion: p.suggestion,
3345
+ errorCode: p.errorCode,
3346
+ errorMessage: p.severity === "danger" ? `[CDP Firewall] ${p.name} blocked \u2014 bypasses framework reactivity` : `[CDP Firewall] ${p.name} detected \u2014 use proper interaction API`
3347
+ };
3348
+ }
3349
+ }
3350
+ return null;
3351
+ }
3352
+ };
3353
+
3354
+ // src/cdp-interceptor/rules/mouse-trajectory.ts
3355
+ var TRACKER_KEY = "mouse-trajectory-tracker";
3356
+ var MAX_SAMPLES = 200;
3357
+ var MIN_SAMPLES_FOR_ANALYSIS = 5;
3358
+ var mouseTrajectoryRule = {
3359
+ id: "mouse-trajectory",
3360
+ name: "Mouse Trajectory Analysis",
3361
+ priority: 20,
3362
+ canHandle(ctx) {
3363
+ return ctx.method === "Input.dispatchMouseEvent";
3364
+ },
3365
+ evaluate(ctx) {
3366
+ const type = ctx.params.type;
3367
+ const x = ctx.params.x;
3368
+ const y = ctx.params.y;
3369
+ if (typeof x !== "number" || typeof y !== "number") return null;
3370
+ let tracker = ctx.sessionState.get(TRACKER_KEY);
3371
+ if (!tracker) {
3372
+ tracker = { samples: [], lastMouseDownAt: 0, isDragging: false };
3373
+ ctx.sessionState.set(TRACKER_KEY, tracker);
3374
+ }
3375
+ if (type === "mousePressed") {
3376
+ const priorResult = analyzeTrajectory(tracker.samples);
3377
+ tracker.lastMouseDownAt = Date.now();
3378
+ tracker.isDragging = true;
3379
+ tracker.samples = [];
3380
+ return priorResult;
3381
+ }
3382
+ if (type === "mouseReleased") {
3383
+ tracker.isDragging = false;
3384
+ const result = analyzeTrajectory(tracker.samples);
3385
+ tracker.samples = [];
3386
+ return result;
3387
+ }
3388
+ if (type === "mouseMoved") {
3389
+ const now = Date.now();
3390
+ const prevSample = tracker.samples[tracker.samples.length - 1];
3391
+ const distanceTraveled = prevSample ? prevSample.distanceTraveled + distance(prevSample.x, prevSample.y, x, y) : 0;
3392
+ const sample = { x, y, timestamp: now, distanceTraveled };
3393
+ tracker.samples.push(sample);
3394
+ if (tracker.samples.length > MAX_SAMPLES) {
3395
+ tracker.samples.shift();
3396
+ }
3397
+ return null;
3398
+ }
3399
+ if (type === "mouseReleased" && tracker.samples.length < MIN_SAMPLES_FOR_ANALYSIS) {
3400
+ tracker.samples = [];
3401
+ return null;
3402
+ }
3403
+ return null;
3404
+ }
3405
+ };
3406
+ function analyzeTrajectory(samples) {
3407
+ if (samples.length < MIN_SAMPLES_FOR_ANALYSIS) return null;
3408
+ const issues = [];
3409
+ const startX = samples[0].x;
3410
+ const startY = samples[0].y;
3411
+ const endX = samples[samples.length - 1].x;
3412
+ const endY = samples[samples.length - 1].y;
3413
+ const lineLength = distance(startX, startY, endX, endY);
3414
+ const collinearityResult = checkCollinearity(samples, startX, startY, endX, endY, lineLength);
3415
+ if (collinearityResult) {
3416
+ issues.push(collinearityResult);
3417
+ }
3418
+ const velocityResult = checkConstantVelocity(samples);
3419
+ if (velocityResult) {
3420
+ issues.push(velocityResult);
3421
+ }
3422
+ const jitterResult = checkJitter(samples);
3423
+ if (jitterResult) {
3424
+ issues.push(jitterResult);
3425
+ }
3426
+ if (issues.length === 0) return null;
3427
+ const stopX = samples[samples.length - 1].x;
3428
+ const stopY = samples[samples.length - 1].y;
3429
+ return {
3430
+ ruleId: "mouse-trajectory",
3431
+ action: "pass",
3432
+ severity: "danger",
3433
+ reason: `Suspicious mouse trajectory: ${issues.join("; ")}`,
3434
+ suggestion: `This mouse movement appears automated (straight line A\u2192B, no natural variation).
3435
+ Use a humanized mouse API that generates:
3436
+ - Bezier curves instead of straight lines
3437
+ - Random acceleration/deceleration
3438
+ - 1-3px micro-jitter per sample
3439
+
3440
+ Example: The 'faker' or 'ghost-cursor' libraries generate realistic mouse paths.
3441
+ Target was: (${Math.round(startX)}, ${Math.round(startY)}) \u2192 (${Math.round(stopX)}, ${Math.round(stopY)})`,
3442
+ errorCode: -32002,
3443
+ errorMessage: "[CDP Firewall] Automated mouse trajectory blocked \u2014 appears non-human"
3444
+ };
3445
+ }
3446
+ function distance(x1, y1, x2, y2) {
3447
+ return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
3448
+ }
3449
+ function checkCollinearity(samples, x1, y1, x2, y2, lineLength) {
3450
+ if (lineLength < 5) return null;
3451
+ let maxDeviation = 0;
3452
+ const dx = x2 - x1;
3453
+ const dy = y2 - y1;
3454
+ for (let i = 1; i < samples.length - 1; i++) {
3455
+ const { x, y } = samples[i];
3456
+ const cross = Math.abs(dy * x - dx * y + x2 * y1 - y2 * x1);
3457
+ const dev = cross / lineLength;
3458
+ if (dev > maxDeviation) maxDeviation = dev;
3459
+ }
3460
+ if (maxDeviation < 1.5 && lineLength > 20) {
3461
+ return `Perfectly straight line (max deviation ${maxDeviation.toFixed(1)}px over ${lineLength.toFixed(0)}px)`;
3462
+ }
3463
+ if (maxDeviation < 0.5 && lineLength > 10) {
3464
+ return `Near-perfect straight line (max deviation ${maxDeviation.toFixed(1)}px)`;
3465
+ }
3466
+ return null;
3467
+ }
3468
+ function checkConstantVelocity(samples) {
3469
+ if (samples.length < 3) return null;
3470
+ const speeds = [];
3471
+ for (let i = 1; i < samples.length; i++) {
3472
+ const d = distance(
3473
+ samples[i - 1].x,
3474
+ samples[i - 1].y,
3475
+ samples[i].x,
3476
+ samples[i].y
3477
+ );
3478
+ const dt = samples[i].timestamp - samples[i - 1].timestamp;
3479
+ if (dt > 0) speeds.push(d / dt);
3480
+ }
3481
+ if (speeds.length < 2) return null;
3482
+ const mean = speeds.reduce((a, b) => a + b, 0) / speeds.length;
3483
+ if (mean === 0) return null;
3484
+ const variance = speeds.reduce((sum, v) => sum + (v - mean) ** 2, 0) / speeds.length;
3485
+ const stddev = Math.sqrt(variance);
3486
+ const cv = stddev / mean;
3487
+ if (cv < 0.05) {
3488
+ return `Constant velocity (CV=${cv.toFixed(3)}, mean=${mean.toFixed(1)} px/ms)`;
3489
+ }
3490
+ return null;
3491
+ }
3492
+ function checkJitter(samples) {
3493
+ if (samples.length < 4) return null;
3494
+ let totalLateralChange = 0;
3495
+ for (let i = 1; i < samples.length; i++) {
3496
+ const d = distance(
3497
+ samples[i - 1].x,
3498
+ samples[i - 1].y,
3499
+ samples[i].x,
3500
+ samples[i].y
3501
+ );
3502
+ totalLateralChange += d;
3503
+ }
3504
+ const avgLateral = totalLateralChange / (samples.length - 1);
3505
+ if (avgLateral < 0.3) {
3506
+ return "No micro-jitter (sub-pixel precision, impossible for human)";
3507
+ }
3508
+ return null;
3509
+ }
3510
+
3511
+ // src/cdp-interceptor/rules/input-keystroke.ts
3512
+ var TRACKER_KEY2 = "keystroke-tracker";
3513
+ var MIN_KEYS_FOR_ANALYSIS = 4;
3514
+ var inputKeystrokeRule = {
3515
+ id: "input-keystroke",
3516
+ name: "Input Keystroke Timing Analysis",
3517
+ priority: 40,
3518
+ canHandle(ctx) {
3519
+ return ctx.method === "Input.dispatchKeyEvent" || ctx.method === "Input.insertText";
3520
+ },
3521
+ evaluate(ctx) {
3522
+ if (ctx.method === "Input.insertText") {
3523
+ return {
3524
+ ruleId: "input-keystroke",
3525
+ action: "pass",
3526
+ severity: "info",
3527
+ reason: "Input.insertText bypasses native keyboard events. Playwright uses this internally for page.fill().",
3528
+ suggestion: "Prefer page.type() with variable delay for human-like input.",
3529
+ errorCode: -32004,
3530
+ errorMessage: "[CDP Firewall] Input.insertText detected \u2014 note: Playwright uses this for fill()"
3531
+ };
3532
+ }
3533
+ let tracker = ctx.sessionState.get(TRACKER_KEY2);
3534
+ if (!tracker) {
3535
+ tracker = { samples: [] };
3536
+ ctx.sessionState.set(TRACKER_KEY2, tracker);
3537
+ }
3538
+ const type = ctx.params.type;
3539
+ const code = ctx.params.code;
3540
+ const key = ctx.params.key;
3541
+ if (type === "keyDown" && key && key.length === 1) {
3542
+ tracker.samples.push({
3543
+ code,
3544
+ key,
3545
+ timestamp: Date.now(),
3546
+ type
3547
+ });
3548
+ }
3549
+ if (tracker.samples.length >= MIN_KEYS_FOR_ANALYSIS && (type === "keyUp" || type === "keyDown")) {
3550
+ return analyzeKeyTiming(tracker.samples);
3551
+ }
3552
+ return null;
3553
+ }
3554
+ };
3555
+ function analyzeKeyTiming(samples) {
3556
+ if (samples.length < MIN_KEYS_FOR_ANALYSIS) return null;
3557
+ const intervals = [];
3558
+ for (let i = 1; i < samples.length; i++) {
3559
+ const dt = samples[i].timestamp - samples[i - 1].timestamp;
3560
+ if (dt > 0) intervals.push(dt);
3561
+ }
3562
+ if (intervals.length < 3) return null;
3563
+ const mean = intervals.reduce((a, b) => a + b, 0) / intervals.length;
3564
+ if (mean === 0) return null;
3565
+ const variance = intervals.reduce((sum, v) => sum + (v - mean) ** 2, 0) / intervals.length;
3566
+ const stddev = Math.sqrt(variance);
3567
+ const cv = stddev / mean;
3568
+ const uniqueIntervals = new Set(intervals);
3569
+ const allIdentical = uniqueIntervals.size === 1;
3570
+ if (allIdentical) {
3571
+ return {
3572
+ ruleId: "input-keystroke",
3573
+ action: "pass",
3574
+ severity: "danger",
3575
+ reason: `All ${intervals.length} keystroke intervals are exactly ${intervals[0]}ms \u2014 impossible for human typing.`,
3576
+ suggestion: `Use page.fill(selector, text) instead of page.type() with delay.
3577
+ Or add random variation: page.type(selector, text, {delay: 50 + Math.random() * 80}).`,
3578
+ errorCode: -32004,
3579
+ errorMessage: "[CDP Firewall] Constant keystroke timing detected \u2014 automated typing pattern"
3580
+ };
3581
+ }
3582
+ if (cv < 0.08) {
3583
+ return {
3584
+ ruleId: "input-keystroke",
3585
+ action: "pass",
3586
+ severity: "warn",
3587
+ reason: `Unnatural keystroke timing (CV=${cv.toFixed(3)}). Human typing has CV > 0.2 on average.`,
3588
+ suggestion: `Add random variation to your typing delay: page.type(selector, text, {delay: 50 + Math.random() * 80}).`,
3589
+ errorCode: -32004,
3590
+ errorMessage: "[CDP Firewall] Suspicious keystroke timing \u2014 likely automated"
3591
+ };
3592
+ }
3593
+ return null;
3594
+ }
3595
+
3596
+ // src/cdp-interceptor/rules/automation-signals.ts
3597
+ var AUTOMATION_PATTERNS = [
3598
+ // ── Playwright markers ─────────────────────────
3599
+ { pattern: /window\s*\.\s*__playwright/, name: "window.__playwright", severity: "danger", errorCode: -32040 },
3600
+ { pattern: /window\s*\.\s*__pw_[a-zA-Z]/, name: "window.__pw_*", severity: "danger", errorCode: -32040 },
3601
+ { pattern: /window\s*\.\s*__pw_paused/, name: "window.__pw_paused", severity: "danger", errorCode: -32040 },
3602
+ { pattern: /window\s*\.\s*playwright\b/, name: "window.playwright", severity: "danger", errorCode: -32040 },
3603
+ { pattern: /window\s*\.\s*__pw_recorder/, name: "window.__pw_recorder", severity: "warn", errorCode: -32041 },
3604
+ { pattern: /window\s*\.\s*__pw_trace/, name: "window.__pw_trace", severity: "warn", errorCode: -32041 },
3605
+ // ── Puppeteer markers ──────────────────────────
3606
+ { pattern: /window\s*\.\s*__puppeteer\b/, name: "window.__puppeteer", severity: "danger", errorCode: -32040 },
3607
+ { pattern: /window\s*\.\s*__puppeteer_evaluation_script/, name: "window.__puppeteer_evaluation_script", severity: "danger", errorCode: -32040 },
3608
+ { pattern: /window\s*\.\s*__puppeteer_testId/, name: "window.__puppeteer_testId", severity: "warn", errorCode: -32041 },
3609
+ { pattern: /window\s*\.\s*__puppeteer_/, name: "window.__puppeteer_*", severity: "danger", errorCode: -32040 },
3610
+ { pattern: /window\s*\.\s*_puppeteer\b/, name: "window._puppeteer", severity: "warn", errorCode: -32041 },
3611
+ // ── Selenium / WebDriver markers ───────────────
3612
+ { pattern: /window\s*\.\s*__webdriver_script_fn/, name: "window.__webdriver_script_fn", severity: "danger", errorCode: -32040 },
3613
+ { pattern: /window\s*\.\s*__selenium\b/, name: "window.__selenium", severity: "danger", errorCode: -32040 },
3614
+ { pattern: /window\s*\.\s*__selenium_evaluate/, name: "window.__selenium_evaluate", severity: "danger", errorCode: -32040 },
3615
+ { pattern: /window\s*\.\s*__driver_evaluate/, name: "window.__driver_evaluate", severity: "warn", errorCode: -32041 },
3616
+ { pattern: /window\s*\.\s*__webdriver_evaluate/, name: "window.__webdriver_evaluate", severity: "danger", errorCode: -32040 },
3617
+ { pattern: /document\.\$cdc_/, name: "document.$cdc_* (Selenium marker)", severity: "danger", errorCode: -32040 },
3618
+ { pattern: /document\.\$chrome_asyncScriptInfo/, name: "document.$chrome_asyncScriptInfo", severity: "danger", errorCode: -32040 },
3619
+ // ── navigator.webdriver detection ─────────────
3620
+ { pattern: /navigator\s*\.\s*webdriver/, name: "navigator.webdriver read", severity: "danger", errorCode: -32042 },
3621
+ { pattern: /navigator\[["']webdriver["']\]/, name: 'navigator["webdriver"]', severity: "danger", errorCode: -32042 },
3622
+ // ── Chrome headless API surface checks ────────
3623
+ { pattern: /chrome\s*\.\s*app/, name: "chrome.app detection", severity: "danger", errorCode: -32043 },
3624
+ { pattern: /chrome\s*\.\s*runtime/, name: "chrome.runtime detection", severity: "danger", errorCode: -32043 },
3625
+ { pattern: /chrome\s*\.\s*loadTimes/, name: "chrome.loadTimes detection", severity: "warn", errorCode: -32044 },
3626
+ { pattern: /chrome\s*\.\s*csi\b/, name: "chrome.csi detection", severity: "warn", errorCode: -32044 },
3627
+ { pattern: /window\s*\.\s*chrome\b/, name: "window.chrome object probe", severity: "warn", errorCode: -32044 },
3628
+ { pattern: /navigator\s*\.\s*plugins\b/, name: "navigator.plugins enumeration", severity: "warn", errorCode: -32044 },
3629
+ { pattern: /navigator\s*\.\s*mimeTypes/, name: "navigator.mimeTypes enumeration", severity: "warn", errorCode: -32044 },
3630
+ { pattern: /navigator\s*\.\s*hardwareConcurrency/, name: "navigator.hardwareConcurrency", severity: "warn", errorCode: -32044 },
3631
+ { pattern: /navigator\s*\.\s*deviceMemory/, name: "navigator.deviceMemory", severity: "info", errorCode: -32045 },
3632
+ { pattern: /navigator\s*\.\s*maxTouchPoints/, name: "navigator.maxTouchPoints", severity: "warn", errorCode: -32044 },
3633
+ { pattern: /navigator\s*\.\s*languages/, name: "navigator.languages", severity: "info", errorCode: -32045 },
3634
+ { pattern: /navigator\s*\.\s*platform/, name: "navigator.platform", severity: "info", errorCode: -32045 },
3635
+ // ── Anti-detection injection attempts ─────────
3636
+ { pattern: /navigator\.webdriver\s*=\s*(false|undefined|null)/, name: "navigator.webdriver override attempt", severity: "danger", errorCode: -32046, suggestionOverride: "Overriding navigator.webdriver is detectable. Use CDP Page.addScriptToEvaluateOnNewDocument instead." },
3637
+ { pattern: /Object\.defineProperty\s*\([^)]*webdriver/, name: "Object.defineProperty navigator.webdriver", severity: "danger", errorCode: -32046, suggestionOverride: "Object.defineProperty patches are detectable via Function.prototype.toString checks." },
3638
+ { pattern: /delete\s+navigator\s*\.\s*webdriver/, name: "delete navigator.webdriver", severity: "danger", errorCode: -32046, suggestionOverride: "Deleting webdriver flag is detectable \u2014 the delete itself is visible." },
3639
+ // ── PhantomJS / Headless markers ──────────────
3640
+ { pattern: /window\s*\.\s*callPhantom/, name: "window.callPhantom", severity: "danger", errorCode: -32040 },
3641
+ { pattern: /window\s*\.\s*_phantom/, name: "window._phantom", severity: "danger", errorCode: -32040 },
3642
+ { pattern: /window\s*\.\s*phantom\b/, name: "window.phantom", severity: "danger", errorCode: -32040 },
3643
+ { pattern: /window\s*\.\s*Buffer\b/, name: "window.Buffer (Node.js leak)", severity: "danger", errorCode: -32040 },
3644
+ { pattern: /window\s*\.\s*process\b/, name: "window.process (Node.js leak)", severity: "danger", errorCode: -32040 },
3645
+ { pattern: /window\s*\.\s*global\b/, name: "window.global (Node.js leak)", severity: "danger", errorCode: -32040 },
3646
+ { pattern: /window\s*\.\s*__dirname/, name: "window.__dirname (Node.js leak)", severity: "danger", errorCode: -32040 }
3647
+ ];
3648
+ var automationSignalsRule = {
3649
+ id: "automation-signals",
3650
+ name: "Browser Automation Signal Detection (35+ markers)",
3651
+ priority: 20,
3652
+ canHandle(ctx) {
3653
+ return ctx.method === "Runtime.evaluate" || ctx.method === "Runtime.callFunctionOn" || ctx.method === "Page.addScriptToEvaluateOnNewDocument";
3654
+ },
3655
+ evaluate(ctx) {
3656
+ if (ctx.method === "Page.addScriptToEvaluateOnNewDocument") {
3657
+ const source = ctx.params.source;
3658
+ if (typeof source === "string") {
3659
+ for (const p of AUTOMATION_PATTERNS) {
3660
+ if (p.pattern.test(source)) {
3661
+ return makeDecision(p, source.substring(0, 60));
3662
+ }
3663
+ }
3664
+ }
3665
+ return null;
3666
+ }
3667
+ const userCode = extractUserCode(ctx);
3668
+ if (!userCode) return null;
3669
+ for (const p of AUTOMATION_PATTERNS) {
3670
+ if (p.pattern.test(userCode)) {
3671
+ return makeDecision(p, userCode.substring(0, 60));
3672
+ }
3673
+ }
3674
+ return null;
3675
+ }
3676
+ };
3677
+ function makeDecision(p, context) {
3678
+ const suggestion = p.suggestionOverride ?? `Detected: "${p.name}" \u2014 an automation tool marker that anti-crawler systems immediately flag. Remove this pattern from your code.`;
3679
+ return {
3680
+ ruleId: "automation-signals",
3681
+ action: "pass",
3682
+ severity: p.severity,
3683
+ reason: `Automation marker detected: "${p.name}". Context: "${context}..."`,
3684
+ suggestion,
3685
+ errorCode: p.errorCode,
3686
+ errorMessage: p.severity === "danger" ? `[CDP Firewall] ${p.name} blocked \u2014 automation tool marker detected` : `[CDP Firewall] ${p.name} detected \u2014 potential automation signal`
3687
+ };
3688
+ }
3689
+
3690
+ // src/cdp-interceptor/rules/fingerprinting.ts
3691
+ var FP_PATTERNS = [
3692
+ // ── Canvas Rendering fingerprinting ────────────────────
3693
+ { pattern: /\.toDataURL\s*\(/, name: "canvas.toDataURL()", severity: "danger", errorCode: -32050, suggestion: "canvas.toDataURL() returns a unique hash that identifies the browser engine. Minimize calls." },
3694
+ { pattern: /\.toBlob\s*\(/, name: "canvas.toBlob()", severity: "danger", errorCode: -32050, suggestion: "canvas.toBlob() is used for canvas fingerprinting. Avoid if possible." },
3695
+ { pattern: /getImageData\s*\(/, name: "CanvasRenderingContext2D.getImageData()", severity: "danger", errorCode: -32050, suggestion: "getImageData reads pixel-level data used for fingerprinting." },
3696
+ { pattern: /measureText\s*\(/, name: "CanvasRenderingContext2D.measureText()", severity: "warn", errorCode: -32051, suggestion: "Font metrics reveal installed fonts \u2014 a fingerprinting vector." },
3697
+ { pattern: /OffscreenCanvas\s*\(/, name: "new OffscreenCanvas()", severity: "warn", errorCode: -32051, suggestion: "OffscreenCanvas is sometimes used to avoid visibility detection." },
3698
+ { pattern: /convertToBlob\s*\(/, name: "OffscreenCanvas.convertToBlob()", severity: "warn", errorCode: -32051, suggestion: "Headless OffscreenCanvas rendering differs from real browser." },
3699
+ // ── WebGL Fingerprinting ──────────────────────────────
3700
+ { pattern: /getParameter\s*\([^)]*(?:VENDOR|RENDERER|VERSION)/, name: "WebGL getParameter(VENDOR/RENDERER)", severity: "danger", errorCode: -32052, suggestion: "WebGL VENDOR/RENDERER returns emulated values in headless. Cannot be reliably spoofed." },
3701
+ { pattern: /getSupportedExtensions\s*\(/, name: "WebGL getSupportedExtensions()", severity: "warn", errorCode: -32053, suggestion: "WebGL extension list differs in headless mode." },
3702
+ { pattern: /getShaderPrecisionFormat\s*\(/, name: "WebGL getShaderPrecisionFormat()", severity: "info", errorCode: -32054, suggestion: "Shader precision differs between headless and real GPU." },
3703
+ { pattern: /UNMASKED_VENDOR_WEBGL/, name: "WEBGL_debug_renderer_info UNMASKED_VENDOR", severity: "warn", errorCode: -32053, suggestion: "Unmasked vendor info reveals the real GPU \u2014 blocked in many envs." },
3704
+ { pattern: /UNMASKED_RENDERER_WEBGL/, name: "WEBGL_debug_renderer_info UNMASKED_RENDERER", severity: "warn", errorCode: -32053, suggestion: "Unmasked renderer string reveals the real GPU." },
3705
+ // ── AudioContext Fingerprinting ────────────────────────
3706
+ { pattern: /AnalyserNode\s*\(/, name: "new AnalyserNode()", severity: "warn", errorCode: -32055, suggestion: "Audio fingerprinting via AnalyserNode \u2014 produces silence in headless." },
3707
+ { pattern: /getFloatFrequencyData\s*\(/, name: "AnalyserNode.getFloatFrequencyData()", severity: "danger", errorCode: -32050, suggestion: "Audio frequency data in headless returns silence (all zeros) \u2014 detectable." },
3708
+ { pattern: /getByteFrequencyData\s*\(/, name: "AnalyserNode.getByteFrequencyData()", severity: "danger", errorCode: -32050, suggestion: "Audio byte frequency data in headless returns zeros." },
3709
+ { pattern: /getByteTimeDomainData\s*\(/, name: "AnalyserNode.getByteTimeDomainData()", severity: "danger", errorCode: -32050, suggestion: "Time domain audio data in headless is a flat line \u2014 detectable." },
3710
+ { pattern: /OfflineAudioContext\s*\(/, name: "new OfflineAudioContext()", severity: "warn", errorCode: -32055, suggestion: "Offline audio rendering is a known fingerprinting method." },
3711
+ { pattern: /OscillatorNode\s*\(/, name: "new OscillatorNode()", severity: "info", errorCode: -32056, suggestion: "Audio oscillator used in fingerprinting probes." },
3712
+ // ── Navigator property probing ───────────────────────
3713
+ { pattern: /navigator\s*\.\s*connection\b/, name: "navigator.connection", severity: "info", errorCode: -32057, suggestion: 'Network connection info is used for fingerprinting (always "4g" in bots).' },
3714
+ { pattern: /navigator\s*\.\s*getBattery\s*\(/, name: "navigator.getBattery()", severity: "warn", errorCode: -32058, suggestion: "Battery API is a fingerprinting vector. Returns fixed values in headless." },
3715
+ { pattern: /navigator\s*\.\s*mediaDevices\s*\.\s*enumerateDevices/, name: "navigator.mediaDevices.enumerateDevices()", severity: "warn", errorCode: -32058, suggestion: "Media device enumeration returns empty/no devices in headless." },
3716
+ { pattern: /navigator\s*\.\s*permissions\s*\.\s*query/, name: "navigator.permissions.query()", severity: "info", errorCode: -32059, suggestion: "Permission queries can reveal automation environment." },
3717
+ // ── Screen / Window geometry probing ──────────────────
3718
+ { pattern: /screen\.avail(Width|Height|Left|Top)/, name: "screen.avail*", severity: "warn", errorCode: -32060, suggestion: "screen.avail* values differ in headless (no OS chrome)." },
3719
+ { pattern: /window\.outerWidth\s*-?\s*window\.innerWidth/, name: "window.outerWidth - window.innerWidth", severity: "danger", errorCode: -32050, suggestion: "This difference is 0 in headless (no browser chrome) \u2014 100% detection rate." },
3720
+ { pattern: /window\.outerHeight\s*-?\s*window\.innerHeight/, name: "window.outerHeight - window.innerHeight", severity: "danger", errorCode: -32050, suggestion: "This difference is 0 in headless \u2014 immediate automation detection." },
3721
+ { pattern: /screen\.width\b/, name: "screen.width", severity: "info", errorCode: -32061, suggestion: "Screen dimensions can be spoofed but inconsistencies with viewport are detectable." },
3722
+ { pattern: /screen\.height\b/, name: "screen.height", severity: "info", errorCode: -32061, suggestion: "Screen dimension probes for viewport inconsistency detection." },
3723
+ { pattern: /window\.devicePixelRatio/, name: "window.devicePixelRatio", severity: "warn", errorCode: -32060, suggestion: "devicePixelRatio is always 1 in headless \u2014 differs from real displays." },
3724
+ { pattern: /matchMedia\s*\(/, name: "window.matchMedia()", severity: "warn", errorCode: -32060, suggestion: "matchMedia can detect CDP overridden viewport dimensions." },
3725
+ // ── Performance / Timing API ──────────────────────────
3726
+ { pattern: /performance\s*\.\s*now\s*\(/, name: "performance.now()", severity: "info", errorCode: -32062, suggestion: "High-resolution timer used for timing attacks and bot detection." },
3727
+ { pattern: /performance\s*\.\s*memory/, name: "performance.memory", severity: "warn", errorCode: -32063, suggestion: "performance.memory shows VM memory limits in containers." },
3728
+ { pattern: /performance\.getEntriesByType\s*\(\s*["']navigation["']\s*\)/, name: 'performance.getEntriesByType("navigation")', severity: "info", errorCode: -32062, suggestion: "Navigation timing reveals request pattern inconsistencies." },
3729
+ { pattern: /performance\.getEntriesByType\s*\(\s*["']resource["']\s*\)/, name: 'performance.getEntriesByType("resource")', severity: "info", errorCode: -32062, suggestion: "Resource loading timing analysis for bot detection." },
3730
+ // ── Font Detection ────────────────────────────────────
3731
+ { pattern: /document\.fonts\.check\s*\(/, name: "document.fonts.check()", severity: "warn", errorCode: -32064, suggestion: "Font availability checks are used for fingerprinting. Installed font list is unique per user." },
3732
+ { pattern: /document\.fonts\.ready/, name: "document.fonts.ready", severity: "info", errorCode: -32065, suggestion: "Font loading state probe for fingerprinting." },
3733
+ // ── WebRTC / Connectivity ────────────────────────────
3734
+ { pattern: /RTCPeerConnection\s*\(/, name: "new RTCPeerConnection()", severity: "warn", errorCode: -32066, suggestion: "WebRTC can leak internal IP and is used for connectivity fingerprinting." },
3735
+ { pattern: /navigator\.mediaDevices\.getUserMedia/, name: "navigator.mediaDevices.getUserMedia()", severity: "info", errorCode: -32067, suggestion: "getUserMedia always fails in headless (no camera)." },
3736
+ // ── Feature Consistency Checks ─────────────────────────
3737
+ { pattern: /Intl\.DateTimeFormat.*resolvedOptions.*timeZone/, name: "Intl.DateTimeFormat timezone check", severity: "warn", errorCode: -32068, suggestion: "Timezone from Intl API vs Emulation.setTimezoneOverride will be inconsistent when mocked." },
3738
+ { pattern: /new\s+Date\s*\(\s*\)\s*\.\s*getTimezoneOffset/, name: "Date.getTimezoneOffset()", severity: "info", errorCode: -32069, suggestion: "Timezone offset used for timing consistency cross-checks." },
3739
+ { pattern: /Error\s*\(\s*\)\s*\.\s*stack/, name: "Error().stack format check", severity: "info", errorCode: -32070, suggestion: "Stack trace format differs between headless and full Chrome." },
3740
+ { pattern: /Function\.prototype\.toString/, name: "Function.prototype.toString on native fn", severity: "info", errorCode: -32070, suggestion: "Native function toString() format can reveal patched APIs." }
3741
+ ];
3742
+ var fingerprintingRule = {
3743
+ id: "fingerprinting",
3744
+ name: "Browser Fingerprinting Access Detection (35+ APIs)",
3745
+ priority: 30,
3746
+ canHandle(ctx) {
3747
+ return ctx.method === "Runtime.evaluate" || ctx.method === "Runtime.callFunctionOn";
3748
+ },
3749
+ evaluate(ctx) {
3750
+ const userCode = extractUserCode(ctx);
3751
+ if (!userCode) return null;
3752
+ for (const p of FP_PATTERNS) {
3753
+ if (p.pattern.test(userCode)) {
3754
+ return {
3755
+ ruleId: "fingerprinting",
3756
+ action: "pass",
3757
+ severity: p.severity,
3758
+ reason: `Browser fingerprinting API accessed: "${p.name}". Anti-crawler systems use this to identify your browser.`,
3759
+ suggestion: p.suggestion,
3760
+ errorCode: p.errorCode,
3761
+ errorMessage: `[CDP Firewall] ${p.name} blocked \u2014 fingerprinting API access detected`
3762
+ };
3763
+ }
3764
+ }
3765
+ return null;
3766
+ }
3767
+ };
3768
+
3769
+ // src/cdp-interceptor/rules/event-simulation.ts
3770
+ var EVENT_PATTERNS = [
3771
+ // ── Direct method calls (all isTrusted=false) ─────────
3772
+ { pattern: /\.click\s*\(\s*\)/, name: "el.click()", severity: "danger", errorCode: -32070, suggestion: "el.click() fires isTrusted=false events. Use page.click(selector) which uses Input.dispatchMouseEvent (isTrusted=true)." },
3773
+ { pattern: /\.focus\s*\(\s*\)/, name: "el.focus()", severity: "warn", errorCode: -32071, suggestion: "el.focus() without user interaction is detectable. Use page.click(selector) which naturally focuses." },
3774
+ { pattern: /\.blur\s*\(\s*\)/, name: "el.blur()", severity: "danger", errorCode: -32071, suggestion: "el.blur() without user interaction. Avoid in automation scripts." },
3775
+ { pattern: /\.submit\s*\(\s*\)/, name: "el.submit()", severity: "danger", errorCode: -32072, suggestion: `form.submit() bypasses onSubmit handlers. Click the submit button: page.click('button[type="submit"]').` },
3776
+ { pattern: /\.reset\s*\(\s*\)/, name: "el.reset()", severity: "danger", errorCode: -32072, suggestion: "form.reset() without user action. Let the user clear fields manually." },
3777
+ { pattern: /\.select\s*\(\s*\)/, name: "el.select()", severity: "warn", errorCode: -32073, suggestion: "input.select() selects text without user interaction. Use page.click(selector) instead." },
3778
+ { pattern: /dialog\.close\s*\(\s*\)|showModal\(\)/, name: "dialog.showModal()/close()", severity: "danger", errorCode: -32074, suggestion: "dialog.showModal() requires user gesture. Let the user open the dialog naturally." },
3779
+ { pattern: /\.showPopover\s*\(\s*\)/, name: "el.showPopover()", severity: "warn", errorCode: -32073, suggestion: "Popover.show() requires user gesture. Simulate a click on the popover trigger." },
3780
+ { pattern: /\.hidePopover\s*\(\s*\)/, name: "el.hidePopover()", severity: "warn", errorCode: -32073, suggestion: "Hiding popovers via CDP is detectable." },
3781
+ { pattern: /\.requestFullscreen\s*\(\s*\)/, name: "el.requestFullscreen()", severity: "danger", errorCode: -32074, suggestion: "Fullscreen requests require user gesture. Cannot be triggered by automation." },
3782
+ { pattern: /\.requestPointerLock\s*\(\s*\)/, name: "el.requestPointerLock()", severity: "danger", errorCode: -32074, suggestion: "Pointer lock requires user gesture. Blocked in automation." },
3783
+ { pattern: /\.setSelectionRange\s*\(/, name: "el.setSelectionRange()", severity: "warn", errorCode: -32073, suggestion: "Setting selection range without user interaction is suspicious." },
3784
+ { pattern: /\.setRangeText\s*\(/, name: "el.setRangeText()", severity: "info", errorCode: -32076, suggestion: "Range text replacement without user input is detectable." },
3785
+ { pattern: /\.showPicker\s*\(\s*\)/, name: "HTMLInputElement.showPicker()", severity: "info", errorCode: -32076, suggestion: "Date/color picker shown without click \u2014 detectable." },
3786
+ { pattern: /\.reportValidity\s*\(\s*\)/, name: "el.reportValidity()", severity: "info", errorCode: -32076, suggestion: "Validity reporting without form submission attempt." },
3787
+ // ── dispatchEvent with synthetic events (isTrusted=false) ──
3788
+ { pattern: /dispatchEvent\s*\(\s*new\s+(?:Event|CustomEvent)\s*\(/, name: "dispatchEvent(new Event/CustomEvent)", severity: "warn", errorCode: -32077, suggestion: "Synthetic events have isTrusted=false. Use Input.dispatch* CDP methods for trusted events." },
3789
+ { pattern: /dispatchEvent\s*\(\s*new\s+MouseEvent\s*\(/, name: "dispatchEvent(new MouseEvent)", severity: "danger", errorCode: -32077, suggestion: "Synthetic mouse events (isTrusted=false). Use Input.dispatchMouseEvent CDP method." },
3790
+ { pattern: /dispatchEvent\s*\(\s*new\s+KeyboardEvent\s*\(/, name: "dispatchEvent(new KeyboardEvent)", severity: "danger", errorCode: -32077, suggestion: "Synthetic keyboard events (isTrusted=false). Use Input.dispatchKeyEvent CDP method." },
3791
+ { pattern: /dispatchEvent\s*\(\s*new\s+FocusEvent\s*\(/, name: "dispatchEvent(new FocusEvent)", severity: "warn", errorCode: -32078, suggestion: "Synthetic focus events bypass user interaction." },
3792
+ { pattern: /dispatchEvent\s*\(\s*new\s+InputEvent\s*\(/, name: "dispatchEvent(new InputEvent)", severity: "danger", errorCode: -32077, suggestion: "Synthetic input events (isTrusted=false). Use page.fill() or page.type()." },
3793
+ { pattern: /dispatchEvent\s*\(\s*new\s+(?:Event)\s*\(\s*["'](?:input|change|submit|reset)/, name: 'dispatchEvent("input"/"change"/"submit")', severity: "danger", errorCode: -32077, suggestion: "Synthetic input/change/submit events are trusted=false. Always detectable." },
3794
+ { pattern: /dispatchEvent\s*\(\s*new\s+PointerEvent\s*\(/, name: "dispatchEvent(new PointerEvent)", severity: "danger", errorCode: -32077, suggestion: "Synthetic pointer events bypass the trusted input pipeline." },
3795
+ { pattern: /dispatchEvent\s*\(\s*new\s+TouchEvent\s*\(/, name: "dispatchEvent(new TouchEvent)", severity: "danger", errorCode: -32077, suggestion: "Synthetic touch events on mobile are detectable." },
3796
+ { pattern: /dispatchEvent\s*\(\s*new\s+WheelEvent\s*\(/, name: "dispatchEvent(new WheelEvent)", severity: "warn", errorCode: -32078, suggestion: "Synthetic scroll events (isTrusted=false). Use Input.dispatchMouseEvent with wheel type." },
3797
+ { pattern: /dispatchEvent\s*\(\s*new\s+ClipboardEvent\s*\(/, name: "dispatchEvent(new ClipboardEvent)", severity: "warn", errorCode: -32078, suggestion: "Synthetic clipboard events are detectable." },
3798
+ { pattern: /dispatchEvent\s*\(\s*new\s+DragEvent\s*\(/, name: "dispatchEvent(new DragEvent)", severity: "warn", errorCode: -32078, suggestion: "Synthetic drag events bypass real user interaction." },
3799
+ { pattern: /dispatchEvent\s*\(\s*new\s+CompositionEvent\s*\(/, name: "dispatchEvent(new CompositionEvent)", severity: "info", errorCode: -32079, suggestion: "Synthetic IME composition events \u2014 detectable pattern." },
3800
+ { pattern: /dispatchEvent\s*\(\s*new\s+AnimationEvent\s*\(/, name: "dispatchEvent(new AnimationEvent)", severity: "info", errorCode: -32079, suggestion: "Forcing animation state transitions via fake events." },
3801
+ { pattern: /dispatchEvent\s*\(\s*new\s+TransitionEvent\s*\(/, name: "dispatchEvent(new TransitionEvent)", severity: "info", errorCode: -32079, suggestion: "Forcing CSS transition end via fake events." }
3802
+ ];
3803
+ var eventSimulationRule = {
3804
+ id: "event-simulation",
3805
+ name: "Event Simulation Detection (30+ patterns)",
3806
+ priority: 40,
3807
+ canHandle(ctx) {
3808
+ return ctx.method === "Runtime.evaluate" || ctx.method === "Runtime.callFunctionOn";
3809
+ },
3810
+ evaluate(ctx) {
3811
+ const userCode = extractUserCode(ctx);
3812
+ if (!userCode) return null;
3813
+ for (const p of EVENT_PATTERNS) {
3814
+ if (p.pattern.test(userCode)) {
3815
+ return {
3816
+ ruleId: "event-simulation",
3817
+ // danger 级硬拦(el.click 等 100% 暴露的模式);
3818
+ // warning 级放行+提示(dispatchEvent 在部分合法场景如 DataTransfer paste 使用)
3819
+ action: p.severity === "danger" ? "block" : "pass",
3820
+ severity: p.severity,
3821
+ reason: `Event simulation detected: "${p.name}". Synthetic events have isTrusted=false and are 100% detectable.`,
3822
+ suggestion: p.suggestion,
3823
+ errorCode: p.errorCode,
3824
+ errorMessage: p.severity === "danger" ? `[CDP Firewall] ${p.name} blocked \u2014 synthetic event (isTrusted=false)` : `[CDP Firewall] ${p.name} detected \u2014 event simulation`
3825
+ };
3826
+ }
3827
+ }
3828
+ return null;
3829
+ }
3830
+ };
3831
+
3832
+ // src/cdp-interceptor/rules/emulation-override.ts
3833
+ var OVERRIDE_PATTERNS = [
3834
+ // ── Emulation overrides ──────────────────────────────
3835
+ // NOTE: Emulation.setDeviceMetricsOverride is NOT included here because
3836
+ // Playwright calls it internally for every new page (viewport setup).
3837
+ // Blocking it would break page creation.
3838
+ { method: "Emulation.setUserAgentOverride", name: "Emulation.setUserAgentOverride", severity: "danger", errorCode: -32080, suggestion: "navigator.userAgent override can be detected by checking consistency with navigator.plugins, WebGL vendor, etc." },
3839
+ { method: "Emulation.setTouchEmulationEnabled", name: "Emulation.setTouchEmulationEnabled", severity: "warn", errorCode: -32081, suggestion: "Touch emulation creates inconsistent touch/mouse state. Windows touch events without real touch hardware." },
3840
+ { method: "Emulation.setGeolocationOverride", name: "Emulation.setGeolocationOverride", severity: "danger", errorCode: -32082, suggestion: "Geolocation changing mid-session without user travel is impossible. Detectable via IP geo vs overridden geo." },
3841
+ { method: "Emulation.setLocaleOverride", name: "Emulation.setLocaleOverride", severity: "warn", errorCode: -32081, suggestion: "Locale change without browser restart detectable via navigator.languages vs Accept-Language consistency." },
3842
+ { method: "Emulation.setTimezoneOverride", name: "Emulation.setTimezoneOverride", severity: "danger", errorCode: -32082, suggestion: "Timezone mismatch vs IP geolocation + Date() is 100% detectable." },
3843
+ { method: "Emulation.setDisabledImageTypes", name: "Emulation.setDisabledImageTypes", severity: "info", errorCode: -32083, suggestion: "Disabling image types prevents normal resource loading \u2014 visible to performance API." },
3844
+ { method: "Emulation.setScriptExecutionDisabled", name: "Emulation.setScriptExecutionDisabled", severity: "info", errorCode: -32083, suggestion: "Disabling JS mid-session kills page interactivity \u2014 immediately obvious." },
3845
+ { method: "Emulation.setCPUThrottlingRate", name: "Emulation.setCPUThrottlingRate", severity: "info", errorCode: -32083, suggestion: "CPU throttling creates unrealistic performance.now() profiles." },
3846
+ { method: "Emulation.setVirtualTimePolicy", name: "Emulation.setVirtualTimePolicy", severity: "info", errorCode: -32083, suggestion: "Virtual time breaks Date.now() and performance.now() based detections \u2014 detectable via timer drift." },
3847
+ // ── Network overrides ────────────────────────────────
3848
+ { method: "Network.setUserAgentOverride", name: "Network.setUserAgentOverride (HTTP layer)", severity: "danger", errorCode: -32080, suggestion: "HTTP User-Agent vs navigator.userAgent inconsistency = immediate detection." },
3849
+ { method: "Network.setExtraHTTPHeaders", name: "Network.setExtraHTTPHeaders", severity: "danger", errorCode: -32084, suggestion: "Custom headers can conflict with browser-generated headers. Missing client hints (Sec-CH-UA) are also detectable." },
3850
+ { method: "Network.emulateNetworkConditions", name: "Network.emulateNetworkConditions", severity: "warn", errorCode: -32081, suggestion: "Network throttling creates unrealistic load timing patterns." },
3851
+ { method: "Network.setCookie", name: "Network.setCookie", severity: "warn", errorCode: -32085, suggestion: "CDP-injected cookies are detectable via document.cookie vs Network.getCookies inconsistency." },
3852
+ { method: "Network.deleteCookies", name: "Network.deleteCookies", severity: "warn", errorCode: -32085, suggestion: "Cookie deletion via CDP bypasses HTTP cookie expiration \u2014 detectable." },
3853
+ // ── Security overrides ──────────────────────────────
3854
+ { method: "Security.setIgnoreCertificateErrors", name: "Security.setIgnoreCertificateErrors", severity: "info", errorCode: -32086, suggestion: "Ignoring certificate errors creates unusual TLS behavior visible at network level." },
3855
+ // ── Page overrides ──────────────────────────────────
3856
+ { method: "Page.setDownloadBehavior", name: "Page.setDownloadBehavior", severity: "info", errorCode: -32087, suggestion: "Bypassing download dialogs \u2014 detectable via download event flow." },
3857
+ { method: "Page.setWebLifecycleState", name: "Page.setWebLifecycleState", severity: "info", errorCode: -32087, suggestion: "Forcing page lifecycle transitions is unnatural." },
3858
+ // ── Storage / Permissions ───────────────────────────
3859
+ { method: "Storage.clearDataForOrigin", name: "Storage.clearDataForOrigin", severity: "info", errorCode: -32089, suggestion: "Clearing storage mid-session is unnatural for real users." },
3860
+ { method: "Browser.grantPermissions", name: "Browser.grantPermissions", severity: "warn", errorCode: -32090, suggestion: "Granting permissions via CDP is detectable as the permission flow skips the user prompt." },
3861
+ { method: "Browser.resetPermissions", name: "Browser.resetPermissions", severity: "info", errorCode: -32089, suggestion: "Permission resets without user action are unnatural." }
3862
+ ];
3863
+ var emulationOverrideRule = {
3864
+ id: "emulation-override",
3865
+ name: "CDP Emulation / Override Detection (20+ methods)",
3866
+ priority: 60,
3867
+ canHandle(ctx) {
3868
+ for (const p of OVERRIDE_PATTERNS) {
3869
+ if (ctx.method === p.method) return true;
3870
+ }
3871
+ return false;
3872
+ },
3873
+ evaluate(ctx) {
3874
+ for (const p of OVERRIDE_PATTERNS) {
3875
+ if (ctx.method !== p.method) continue;
3876
+ return {
3877
+ ruleId: "emulation-override",
3878
+ action: "pass",
3879
+ severity: p.severity,
3880
+ reason: `CDP emulation/override detected: "${p.name}". This creates detectable inconsistencies between the JS environment and real browser state.`,
3881
+ suggestion: p.suggestion,
3882
+ errorCode: p.errorCode,
3883
+ errorMessage: `[CDP Firewall] ${p.name} blocked \u2014 creates detectable browser state inconsistency`
3884
+ };
3885
+ }
3886
+ return null;
3887
+ }
3888
+ };
3889
+
3890
+ // src/cdp-interceptor/rules/network-anomaly.ts
3891
+ var networkAnomalyRule = {
3892
+ id: "network-anomaly",
3893
+ name: "Network Anomaly Detection (8+ patterns)",
3894
+ priority: 70,
3895
+ canHandle(ctx) {
3896
+ const m = ctx.method;
3897
+ return m === "Network.setExtraHTTPHeaders" || m === "Network.clearBrowserCache" || m === "Network.clearBrowserCookies" || m === "Network.setBlockedURLs" || m === "Network.setBypassServiceWorker" || m === "Fetch.enable" || m === "Network.enable";
3898
+ },
3899
+ evaluate(ctx) {
3900
+ switch (ctx.method) {
3901
+ case "Network.setExtraHTTPHeaders": {
3902
+ const headers = ctx.params.headers;
3903
+ if (headers) {
3904
+ const headerStr = JSON.stringify(headers).toLowerCase();
3905
+ if (!headerStr.includes("sec-ch-ua")) {
3906
+ return {
3907
+ ruleId: "network-anomaly",
3908
+ action: "pass",
3909
+ severity: "warn",
3910
+ reason: "Network.setExtraHTTPHeaders called without Sec-CH-UA client hints \u2014 browser normally sends these.",
3911
+ suggestion: "Modern browsers send Sec-CH-UA headers automatically. Adding custom headers without them creates detectable inconsistency.",
3912
+ errorCode: -32110,
3913
+ errorMessage: "[CDP Firewall] Missing client hints in custom headers"
3914
+ };
3915
+ }
3916
+ }
3917
+ return null;
3918
+ }
3919
+ case "Network.clearBrowserCache": {
3920
+ return {
3921
+ ruleId: "network-anomaly",
3922
+ action: "pass",
3923
+ severity: "warn",
3924
+ reason: "Network.clearBrowserCache called \u2014 cache clearing mid-session is unnatural for real users.",
3925
+ suggestion: "Avoid cache clearing during sessions. Start with a fresh profile if needed.",
3926
+ errorCode: -32111,
3927
+ errorMessage: "[CDP Firewall] Cache clearing detected"
3928
+ };
3929
+ }
3930
+ case "Network.clearBrowserCookies": {
3931
+ return {
3932
+ ruleId: "network-anomaly",
3933
+ action: "pass",
3934
+ severity: "warn",
3935
+ reason: "Network.clearBrowserCookies called \u2014 wiping cookies mid-session is a scraper optimization.",
3936
+ suggestion: "Cookies should only be cleared via normal browser flow (expiration, user action).",
3937
+ errorCode: -32112,
3938
+ errorMessage: "[CDP Firewall] Cookie clearing detected"
3939
+ };
3940
+ }
3941
+ case "Network.setBlockedURLs": {
3942
+ return {
3943
+ ruleId: "network-anomaly",
3944
+ action: "pass",
3945
+ severity: "warn",
3946
+ reason: "Network.setBlockedURLs blocks resource loading \u2014 this changes the page behavior and is detectable.",
3947
+ suggestion: "Blocking images/fonts/etc creates measurable differences in performance and page rendering.",
3948
+ errorCode: -32113,
3949
+ errorMessage: "[CDP Firewall] URL blocking detected"
3950
+ };
3951
+ }
3952
+ case "Network.setBypassServiceWorker": {
3953
+ return {
3954
+ ruleId: "network-anomaly",
3955
+ action: "block",
3956
+ severity: "info",
3957
+ reason: "Network.setBypassServiceWorker called \u2014 bypassing service workers for content extraction.",
3958
+ suggestion: "Service worker bypass changes fetch behavior and is detectable server-side.",
3959
+ errorCode: -32114,
3960
+ errorMessage: "[CDP Firewall] Service worker bypass detected"
3961
+ };
3962
+ }
3963
+ case "Fetch.enable": {
3964
+ return {
3965
+ ruleId: "network-anomaly",
3966
+ action: "pass",
3967
+ severity: "warn",
3968
+ reason: "Fetch.enable intercepts all network requests \u2014 a man-in-the-middle approach used by scrapers.",
3969
+ suggestion: "Do not use Fetch domain for network interception if avoiding detection.",
3970
+ errorCode: -32115,
3971
+ errorMessage: "[CDP Firewall] Fetch interception detected"
3972
+ };
3973
+ }
3974
+ default:
3975
+ return null;
3976
+ }
3977
+ }
3978
+ };
3979
+
3980
+ // src/cdp-interceptor/rules/page-lifecycle.ts
3981
+ var STAT_KEY = "lifecycle-tracker";
3982
+ var pageLifecycleRule = {
3983
+ id: "page-lifecycle",
3984
+ name: "Page Lifecycle Anomaly Detection (10+ patterns)",
3985
+ priority: 80,
3986
+ canHandle(ctx) {
3987
+ const m = ctx.method;
3988
+ return m === "Page.navigate" || m === "Page.captureScreenshot" || m === "Page.printToPDF" || m === "Page.reload" || m === "Page.close" || m === "Runtime.evaluate" || m === "Runtime.callFunctionOn";
3989
+ },
3990
+ evaluate(ctx) {
3991
+ let state = ctx.sessionState.get(STAT_KEY);
3992
+ if (!state) {
3993
+ state = { navigations: [], screenshots: 0, printToPDF: false, evaluateCount: 0, lastNavTime: 0, lastEvalTime: 0 };
3994
+ ctx.sessionState.set(STAT_KEY, state);
3995
+ }
3996
+ const now = Date.now();
3997
+ switch (ctx.method) {
3998
+ case "Page.navigate": {
3999
+ state.navigations.push(now);
4000
+ if (state.navigations.length >= 2) {
4001
+ const prev = state.navigations[state.navigations.length - 2];
4002
+ const interval = now - prev;
4003
+ if (interval < 100) {
4004
+ return {
4005
+ ruleId: "page-lifecycle",
4006
+ action: "pass",
4007
+ severity: "warn",
4008
+ reason: `Multiple Page.navigate calls within ${interval}ms of each other \u2014 unnatural rapid navigation.`,
4009
+ suggestion: "Add proper waits between navigations: wait for page load before navigating again.",
4010
+ errorCode: -32100,
4011
+ errorMessage: "[CDP Firewall] Rapid navigation sequence detected"
4012
+ };
4013
+ }
4014
+ }
4015
+ state.lastNavTime = now;
4016
+ return null;
4017
+ }
4018
+ case "Page.captureScreenshot": {
4019
+ state.screenshots++;
4020
+ if (state.lastNavTime > 0 && now - state.lastNavTime < 500) {
4021
+ return {
4022
+ ruleId: "page-lifecycle",
4023
+ action: "pass",
4024
+ severity: "danger",
4025
+ reason: "Page.captureScreenshot called within 500ms of navigation \u2014 content extraction pattern.",
4026
+ suggestion: "Wait for the page to fully render before taking screenshots: wait for load/networkidle.",
4027
+ errorCode: -32101,
4028
+ errorMessage: "[CDP Firewall] Pre-render screenshot blocked \u2014 content extraction pattern"
4029
+ };
4030
+ }
4031
+ if (state.screenshots > 3 && state.navigations.length < 2) {
4032
+ return {
4033
+ ruleId: "page-lifecycle",
4034
+ action: "pass",
4035
+ severity: "warn",
4036
+ reason: "Multiple screenshots on a single page without navigation \u2014 suspicious extraction behavior.",
4037
+ suggestion: "Consider if all screenshots are necessary.",
4038
+ errorCode: -32102,
4039
+ errorMessage: "[CDP Firewall] Excessive screenshot detection"
4040
+ };
4041
+ }
4042
+ return null;
4043
+ }
4044
+ case "Page.printToPDF": {
4045
+ return {
4046
+ ruleId: "page-lifecycle",
4047
+ action: "pass",
4048
+ severity: "danger",
4049
+ reason: "Page.printToPDF called \u2014 this is a telltale scraper pattern that gives away automation intent.",
4050
+ suggestion: "Avoid PDF generation. If you must, add significant delays and user-like interaction first.",
4051
+ errorCode: -32103,
4052
+ errorMessage: "[CDP Firewall] printToPDF blocked \u2014 scraper intent detected"
4053
+ };
4054
+ }
4055
+ case "Page.reload": {
4056
+ if (state.lastNavTime > 0 && now - state.lastNavTime < 1e3) {
4057
+ return {
4058
+ ruleId: "page-lifecycle",
4059
+ action: "pass",
4060
+ severity: "warn",
4061
+ reason: "Page.reload called immediately after navigate \u2014 unnatural fast-reload pattern.",
4062
+ suggestion: "Introduce delays between navigation and reload to simulate human behavior.",
4063
+ errorCode: -32104,
4064
+ errorMessage: "[CDP Firewall] Rapid reload detected"
4065
+ };
4066
+ }
4067
+ return null;
4068
+ }
4069
+ case "Page.close": {
4070
+ if (state.navigations.length < 2) {
4071
+ return {
4072
+ ruleId: "page-lifecycle",
4073
+ action: "pass",
4074
+ severity: "info",
4075
+ reason: "Page.close called after minimal interaction \u2014 zombie pages common in automation.",
4076
+ suggestion: "Ensure meaningful interaction before closing pages.",
4077
+ errorCode: -32105,
4078
+ errorMessage: "[CDP Firewall] Page close after minimal interaction"
4079
+ };
4080
+ }
4081
+ return null;
4082
+ }
4083
+ case "Runtime.evaluate":
4084
+ case "Runtime.callFunctionOn": {
4085
+ state.evaluateCount++;
4086
+ if (state.evaluateCount > 50 && state.navigations.length === 0) {
4087
+ return {
4088
+ ruleId: "page-lifecycle",
4089
+ action: "pass",
4090
+ severity: "info",
4091
+ reason: "50+ evaluate calls without any Page.navigate \u2014 data extraction without real browsing.",
4092
+ suggestion: "Navigate to a real page first. Evaluate on about:blank is suspicious.",
4093
+ errorCode: -32106,
4094
+ errorMessage: "[CDP Firewall] Excessive evaluate without navigation"
4095
+ };
4096
+ }
4097
+ return null;
4098
+ }
4099
+ default:
4100
+ return null;
4101
+ }
4102
+ }
4103
+ };
4104
+
4105
+ // src/cdp-interceptor/rules-engine.ts
4106
+ var BUILTIN_RULES = [
4107
+ domMutationRule,
4108
+ automationSignalsRule,
4109
+ fingerprintingRule,
4110
+ eventSimulationRule,
4111
+ mouseTrajectoryRule,
4112
+ inputKeystrokeRule,
4113
+ emulationOverrideRule,
4114
+ networkAnomalyRule,
4115
+ pageLifecycleRule
4116
+ ];
4117
+ function createRuleEngine(customRules) {
4118
+ const rules = [...BUILTIN_RULES, ...customRules ?? []].sort((a, b) => a.priority - b.priority);
4119
+ const sessionStates = /* @__PURE__ */ new Map();
4120
+ function getSessionState(sessionId) {
4121
+ let state = sessionStates.get(sessionId);
4122
+ if (!state) {
4123
+ state = /* @__PURE__ */ new Map();
4124
+ sessionStates.set(sessionId, state);
4125
+ }
4126
+ return state;
4127
+ }
4128
+ return {
4129
+ start() {
4130
+ sessionStates.clear();
4131
+ },
4132
+ stop() {
4133
+ sessionStates.clear();
4134
+ },
4135
+ evaluate(ctx) {
4136
+ const fullCtx = {
4137
+ ...ctx,
4138
+ sessionState: getSessionState(ctx.sessionId)
4139
+ };
4140
+ for (const rule of rules) {
4141
+ if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
4142
+ const decision = rule.evaluate(fullCtx);
4143
+ if (!decision) continue;
4144
+ if (decision.action !== "pass") return decision;
4145
+ }
4146
+ return null;
4147
+ }
4148
+ };
4149
+ }
4150
+
4151
+ // src/cdp-driver/connection.ts
4152
+ var CDPConnection = class _CDPConnection extends EventEmitter4 {
2782
4153
  ws;
2783
4154
  nextId = 1;
4155
+ /** CDP Guard:全部出站命令过规则引擎(env XBROWSER_CDP_GUARD=off 关闭)。
4156
+ * 173 条规则 / 9 模块:合成事件 block、指纹暴露警告、自动化信号拦截。 */
4157
+ static __guard;
4158
+ get guard() {
4159
+ if (_CDPConnection.__guard === void 0) {
4160
+ if (process.env.XBROWSER_CDP_GUARD === "off") {
4161
+ _CDPConnection.__guard = null;
4162
+ } else {
4163
+ try {
4164
+ const g = createRuleEngine();
4165
+ g.start();
4166
+ _CDPConnection.__guard = g;
4167
+ } catch {
4168
+ _CDPConnection.__guard = null;
4169
+ }
4170
+ }
4171
+ }
4172
+ return _CDPConnection.__guard;
4173
+ }
2784
4174
  pending = /* @__PURE__ */ new Map();
2785
4175
  closed = false;
2786
4176
  closeReason = null;
@@ -2804,6 +4194,8 @@ var CDPConnection = class extends EventEmitter4 {
2804
4194
  * ping, the connection is considered dead and forcibly closed. */
2805
4195
  keepaliveTimer = null;
2806
4196
  pongTimer = null;
4197
+ /** 最近一次收到任何 WS 消息的时间——有数据流动即证明连接存活 */
4198
+ lastIncomingAt = Date.now();
2807
4199
  startKeepalive() {
2808
4200
  this.ws.on("pong", () => {
2809
4201
  if (this.pongTimer) {
@@ -2815,9 +4207,14 @@ var CDPConnection = class extends EventEmitter4 {
2815
4207
  if (this.ws.readyState === WebSocket.OPEN) {
2816
4208
  if (!this.pongTimer) {
2817
4209
  this.pongTimer = setTimeout(() => {
4210
+ const recentlyActive = Date.now() - this.lastIncomingAt < 3e4;
4211
+ if (recentlyActive) {
4212
+ this.pongTimer = null;
4213
+ return;
4214
+ }
2818
4215
  if (!this.closed) {
2819
4216
  this.closed = true;
2820
- this.closeReason = "keepalive timeout (no pong in 10s)";
4217
+ this.closeReason = "keepalive timeout (no pong and idle >30s)";
2821
4218
  try {
2822
4219
  this.ws.terminate();
2823
4220
  } catch {
@@ -2829,7 +4226,7 @@ var CDPConnection = class extends EventEmitter4 {
2829
4226
  this.pending.clear();
2830
4227
  this.emit("disconnect");
2831
4228
  }
2832
- }, 1e4);
4229
+ }, 6e4);
2833
4230
  }
2834
4231
  this.ws.ping?.();
2835
4232
  } else if (this.closed) {
@@ -2867,10 +4264,23 @@ var CDPConnection = class extends EventEmitter4 {
2867
4264
  * @param method — CDP domain.method (e.g. "Page.navigate")
2868
4265
  * @param params — method parameters
2869
4266
  * @param sessionId — optional flat session ID for sub-targets
2870
- * @param timeoutMs — response timeout (default: 30s)
4267
+ * @param timeoutMs — response timeout (default: 30s;重 SPA 加载期间主线程忙,
4268
+ * evaluate 可排队 >30s——Runtime.evaluate 单独放宽到 90s)
2871
4269
  * @returns the `result` field from the CDP response
2872
4270
  */
2873
- async send(method, params, sessionId, timeoutMs = 3e4) {
4271
+ async send(method, params, sessionId, timeoutMs) {
4272
+ const effectiveTimeout = timeoutMs ?? (method === "Runtime.evaluate" ? 9e4 : 3e4);
4273
+ if (this.guard) {
4274
+ const decision = this.guard.evaluate({
4275
+ method,
4276
+ params: params ?? {},
4277
+ sessionId: sessionId ?? this.defaultSessionId ?? "",
4278
+ direction: "client\u2192browser"
4279
+ });
4280
+ if (decision && decision.action === "block") {
4281
+ throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
4282
+ }
4283
+ }
2874
4284
  if (this.closed) {
2875
4285
  throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
2876
4286
  }
@@ -2885,8 +4295,8 @@ var CDPConnection = class extends EventEmitter4 {
2885
4295
  return new Promise((resolve, reject) => {
2886
4296
  const timeout = setTimeout(() => {
2887
4297
  this.pending.delete(id);
2888
- reject(new Error(`CDP timeout: ${method} (${timeoutMs}ms)`));
2889
- }, timeoutMs);
4298
+ reject(new Error(`CDP timeout: ${method} (${effectiveTimeout}ms)`));
4299
+ }, effectiveTimeout);
2890
4300
  this.pending.set(id, {
2891
4301
  resolve: (v) => {
2892
4302
  clearTimeout(timeout);
@@ -2969,6 +4379,7 @@ var CDPConnection = class extends EventEmitter4 {
2969
4379
  // ── Private ─────────────────────────────────────────────────
2970
4380
  bindWebSocket() {
2971
4381
  this.ws.on("message", (raw) => {
4382
+ this.lastIncomingAt = Date.now();
2972
4383
  let msg;
2973
4384
  try {
2974
4385
  msg = JSON.parse(raw.toString());
@@ -3110,25 +4521,22 @@ async function launch(options = {}) {
3110
4521
  const browser = new XBBrowserImpl(conn, childProcess, tmpDir, httpEndpoint);
3111
4522
  return { browser, wsEndpoint };
3112
4523
  }
4524
+
3113
4525
  export {
3114
- CDPConnection,
3115
- CDPProtocolError,
3116
- XBBrowserImpl,
3117
- XBCDPSessionImpl,
3118
- XBContextImpl,
3119
- XBElementHandleImpl,
3120
- XBKeyboardImpl,
3121
- XBLocatorImpl,
3122
4526
  XBMouseImpl,
3123
- XBPageImpl,
4527
+ XBKeyboardImpl,
4528
+ waitForActionable,
3124
4529
  checkActionable,
3125
- connectToCDP,
3126
- findChrome,
3127
- getCDPTargets,
3128
- killChrome,
3129
- launch,
3130
- launchChrome,
3131
4530
  scrollIntoView,
3132
- waitForActionable,
3133
- waitForNetworkIdle
4531
+ XBLocatorImpl,
4532
+ XBElementHandleImpl,
4533
+ XBPageImpl,
4534
+ XBCDPSessionImpl,
4535
+ XBContextImpl,
4536
+ XBBrowserImpl,
4537
+ createRuleEngine,
4538
+ CDPConnection,
4539
+ CDPProtocolError,
4540
+ waitForNetworkIdle,
4541
+ launch
3134
4542
  };