@xbrowser/cli 1.11.0 → 1.13.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 (35) hide show
  1. package/dist/{browser-XNU7JQYC.js → browser-AQ2AT2YZ.js} +2 -2
  2. package/dist/{browser-Q5APBNF6.js → browser-OMGJMSBB.js} +1 -1
  3. package/dist/{browser-V3JIWSTR.js → browser-T7OVLAEC.js} +4 -3
  4. package/dist/{cdp-driver-XFTTZI5O.js → cdp-driver-ALDNOZYD.js} +1176 -13
  5. package/dist/{cdp-driver-GD6YBBGE.js → cdp-driver-HYCLE4YP.js} +2 -1
  6. package/dist/{cdp-driver-VEK6BNN6.js → cdp-driver-VS7Z7W7Y.js} +1 -1
  7. package/dist/chunk-A6LPGFAL.js +437 -0
  8. package/dist/{chunk-JEDP4PJW.js → chunk-BY5TT6WZ.js} +912 -688
  9. package/dist/{chunk-XKQVUFUS.js → chunk-CW7L53JE.js} +2 -2
  10. package/dist/{chunk-ABXMBNQ6.js → chunk-H2A5JUK5.js} +37 -466
  11. package/dist/{chunk-BNO7OKO4.js → chunk-HBMEFSTB.js} +39 -0
  12. package/dist/chunk-HD4FX2N5.js +1255 -0
  13. package/dist/{chunk-DWDXEGVK.js → chunk-NKW4A74J.js} +9 -3
  14. package/dist/{chunk-SQHSZENE.js → chunk-OMU63E6J.js} +3 -22
  15. package/dist/{chunk-7OFM755Z.js → chunk-R2POF2GP.js} +236 -13
  16. package/dist/{chunk-WHPBNUKB.js → chunk-SH6OTPXN.js} +42 -46
  17. package/dist/{chunk-XQ4HRPDJ.js → chunk-T2CNKWPV.js} +1177 -13
  18. package/dist/{chunk-MWFHZUIY.js → chunk-TEXCXIBW.js} +1 -1
  19. package/dist/{chunk-IIM5GOD7.js → chunk-ZTHE5RBZ.js} +7 -1
  20. package/dist/cli.js +1075 -569
  21. package/dist/{daemon-client-MMDRYCF5.js → daemon-client-7D6EZNOE.js} +42 -46
  22. package/dist/{daemon-client-Y2YSZCGK.js → daemon-client-HEGAXWGK.js} +1 -1
  23. package/dist/daemon-main.js +950 -499
  24. package/dist/{human-interaction-5AO42MBA.js → human-interaction-4YR2N6R6.js} +2 -2
  25. package/dist/{human-interaction-C5OEGXGO.js → human-interaction-Y5IDH6LD.js} +1 -1
  26. package/dist/{human-interaction-ISXZTAYY.js → human-interaction-ZUTR5AC2.js} +2 -2
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +1086 -578
  29. package/dist/{proxy-C6CK3UH5.js → proxy-LUR4U5YF.js} +2 -1
  30. package/dist/{recovery-J2ISVGUL.js → recovery-FTZGV6VY.js} +2 -2
  31. package/dist/{recovery-ZJVVHP7N.js → recovery-L5GLDX4O.js} +1 -1
  32. package/dist/{recovery-EF33LKRJ.js → recovery-Z3RDZENA.js} +2 -2
  33. package/dist/{session-replayer-WIUYVN5J.js → session-replayer-UVH5FGY2.js} +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-HVPUVVSA.js +0 -2194
@@ -128,8 +128,8 @@ function buildStealthInitScript() {
128
128
  " if(!e||e.constructor===FocusEvent||e.constructor===KeyboardEvent)return f.call(this,e);",
129
129
  " return f.call(this,new Proxy(e,{get:function(k,p){",
130
130
  ' if(p==="sourceCapabilities")return fc;',
131
- ' if(p==="isTrusted")return true;',
132
- ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isFinite(k[p])){',
131
+ ' if(p==="isTrusted")return k.isTrusted;',
132
+ ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])&&k.isTrusted===true){',
133
133
  " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;",
134
134
  " return k[p]+_f;",
135
135
  " }",
@@ -147,7 +147,160 @@ function buildStealthInitScript() {
147
147
  ' Object.defineProperty(Screen.prototype,"height",{get:_gh,configurable:true});',
148
148
  ' Object.defineProperty(Screen.prototype,"availWidth",{get:_gw,configurable:true});',
149
149
  ' Object.defineProperty(Screen.prototype,"availHeight",{get:_gah,configurable:true});',
150
- " document.hasFocus=function(){return true};",
150
+ // hasFocus 与 visibilityState 联动(d29):恒 true 在 hidden 标签下暴露
151
+ // —— 真实浏览器失焦/后台时 hasFocus=false
152
+ ' document.hasFocus=function(){return document.visibilityState==="visible";};',
153
+ // 4. Canvas/WebGL fingerprint: per-session stable noise (d20).
154
+ // Headless software raster differs subtly from Chrome GPU raster —
155
+ // toDataURL hashes fingerprint the rasterizer. Inject a stable
156
+ // (per-page-load) subpixel shift into fillText so hashes look like a
157
+ // distinct-but-consistent real GPU, and hide the HEADLESS tell in
158
+ // WebGL renderer strings.
159
+ " var _seed=Math.floor(Math.random()*2147483647);",
160
+ " var _prng=function(){_seed=(_seed*48271)%2147483647;return _seed/2147483647;};",
161
+ " var _dx=(_prng()*0.4-0.2).toFixed(3)*1, _dy=(_prng()*0.4-0.2).toFixed(3)*1;",
162
+ " var _fillText=CanvasRenderingContext2D.prototype.fillText;",
163
+ " CanvasRenderingContext2D.prototype.fillText=function(t,x,y,m){",
164
+ " return _fillText.call(this,t,x+_dx,y+_dy,m);",
165
+ " };",
166
+ " var _toDataURL=HTMLCanvasElement.prototype.toDataURL;",
167
+ " HTMLCanvasElement.prototype.toDataURL=function(){",
168
+ ' var ctx=this.getContext("2d");',
169
+ " if(ctx){var d=ctx.getImageData(0,0,Math.min(this.width,2),Math.min(this.height,2));",
170
+ " for(var i=0;i<d.data.length;i+=4){if(d.data[i+3]>0){d.data[i]^=1;break;}}",
171
+ " ctx.putImageData(d,0,0);}",
172
+ " return _toDataURL.apply(this,arguments);",
173
+ " };",
174
+ " try{",
175
+ " var _gl=HTMLCanvasElement.prototype.getContext;",
176
+ " HTMLCanvasElement.prototype.getContext=function(t,o){",
177
+ " var c=_gl.call(this,t,o);",
178
+ ' if(c&&(t==="webgl"||t==="experimental-webgl")&&c.getParameter){',
179
+ " var _gp=c.getParameter.bind(c);",
180
+ " c.getParameter=function(p){",
181
+ " var v=_gp(p);",
182
+ ' if(typeof v==="string"&&/SwiftShader|Software|Rasterizer|Headless/i.test(v))',
183
+ ' return "ANGLE (Apple, ANGLE Metal Renderer: Apple M2 Max, Unspecified Version)";',
184
+ " return v;};}",
185
+ " return c;};",
186
+ " }catch(e){}",
187
+ // 5. AudioContext fingerprint: per-load stable micro-noise on channel
188
+ // data (d21). DSP sum differences between headless software audio and
189
+ // real hardware audio are a classic fingerprint — add ±1e-7 level
190
+ // noise (inaudible, changes the sum hash).
191
+ " try{",
192
+ " var _gcd=AudioBuffer.prototype.getChannelData;",
193
+ " AudioBuffer.prototype.getChannelData=function(ch){",
194
+ " var d=_gcd.call(this,ch);",
195
+ ' var key="__xb_audio_"+ch;',
196
+ " if(!this[key]){",
197
+ " this[key]=true;",
198
+ " for(var i=0;i<d.length;i+=997){d[i]=d[i]+(_prng()-0.5)*2e-7;}",
199
+ " }",
200
+ " return d;",
201
+ " };",
202
+ " var _gffd=AnalyserNode.prototype.getFloatFrequencyData;",
203
+ " AnalyserNode.prototype.getFloatFrequencyData=function(arr){",
204
+ " _gffd.call(this,arr);",
205
+ " for(var i=0;i<arr.length;i+=31){arr[i]=arr[i]+(_prng()-0.5)*0.01;}",
206
+ " };",
207
+ " var _gfbd=AnalyserNode.prototype.getByteFrequencyData;",
208
+ " AnalyserNode.prototype.getByteFrequencyData=function(arr){",
209
+ " _gfbd.call(this,arr);",
210
+ " for(var i=0;i<arr.length;i+=31){arr[i]=(arr[i]+((_prng()*3)|0))&255;}",
211
+ " };",
212
+ " }catch(e){}",
213
+ // 3b. Font metrics + speechSynthesis + battery (d22): headless tells
214
+ " try{",
215
+ " var _mt=CanvasRenderingContext2D.prototype.measureText;",
216
+ ' var _tmw=Object.getOwnPropertyDescriptor(TextMetrics.prototype,"width");',
217
+ " CanvasRenderingContext2D.prototype.measureText=function(t){",
218
+ " var m=_mt.call(this,t);",
219
+ ' try{Object.defineProperty(m,"width",{get:function(){return _tmw.get.call(m)+_dx*0.01;},configurable:true});}catch(e){}',
220
+ " return m;",
221
+ " };",
222
+ " }catch(e){}",
223
+ " try{",
224
+ ' var _fakeVoices=["Alex","Daniel","Karen","Moira","Ralph","Samantha","Ting-Ting","Mei-Jia","Sinji","Yunda"];',
225
+ " var _sv=speechSynthesis.getVoices.bind(speechSynthesis);",
226
+ " speechSynthesis.getVoices=function(){",
227
+ " var real=_sv();",
228
+ " if(real&&real.length>50)return real;",
229
+ // 注意阈值从 0 改 50:iframe 原生约 10 个 —— 原阈值下 iframe 返回原生 10 个
230
+ // 而不是伪装 180(d33 暴露)。>50 = 主文档伪装列表已生效,其余返回伪装。
231
+ ' 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};});',
232
+ " };",
233
+ // d33 修复:iframe 的 speechSynthesis 是独立实例(主文档 hook 不可达)——
234
+ // 轮询同源 iframe,对其 contentWindow.speechSynthesis 同样 patch
235
+ " try{",
236
+ " var _piv=function(){",
237
+ ' var frs=document.querySelectorAll("iframe");',
238
+ " for(var i=0;i<frs.length;i++){try{",
239
+ " var cw=frs[i].contentWindow;",
240
+ " if(!cw||!cw.speechSynthesis||cw.speechSynthesis.__xbP)continue;",
241
+ " cw.speechSynthesis.__xbP=true;",
242
+ " var _sv2=cw.speechSynthesis.getVoices.bind(cw.speechSynthesis);",
243
+ " cw.speechSynthesis.getVoices=function(){var r=_sv2();if(r&&r.length>50)return r;",
244
+ ' return _fakeVoices.map(function(n,j){return{name:n,lang:j<2?"en-US":j<6?"en-GB":"zh-TW",localService:true,default:j===0,voiceURI:n};});};',
245
+ " }catch(e2){}}",
246
+ " };",
247
+ " setInterval(_piv,2000);",
248
+ " var _mo=new MutationObserver(function(muts){",
249
+ " for(var k=0;k<muts.length;k++){var ns=muts[k].addedNodes;",
250
+ ' for(var q=0;q<ns.length;q++){if(ns[q].tagName==="IFRAME")setTimeout(_piv,20);}}',
251
+ " });",
252
+ " _mo.observe(document.documentElement,{childList:true,subtree:true});",
253
+ " }catch(e){}",
254
+ " }catch(e){}",
255
+ " try{",
256
+ " var _gb=navigator.getBattery.bind(navigator);",
257
+ " navigator.getBattery=function(){",
258
+ " return _gb().then(function(b){",
259
+ ' Object.defineProperty(b,"charging",{get:function(){return true;},configurable:true});',
260
+ " return b;});",
261
+ " };",
262
+ " }catch(e){}",
263
+ // 3c. WebRTC local IP leak guard (d23): headless STUN candidates can
264
+ // expose host IPs; mDNS-only candidates are the modern Chrome default.
265
+ " try{",
266
+ " var _oc=RTCPeerConnection.prototype.createOffer;",
267
+ " RTCPeerConnection.prototype.createOffer=function(){",
268
+ " var p=_oc.apply(this,arguments);",
269
+ " var self=this;",
270
+ " return p.then(function(offer){",
271
+ ' offer.sdp=offer.sdp.split(String.fromCharCode(10)).filter(function(l){return l.indexOf("typ host")<0}).join(String.fromCharCode(10));',
272
+ " return offer;});",
273
+ " };",
274
+ " }catch(e){}",
275
+ // 3d-2. performance.now precision clamp (d34): full-precision timestamps
276
+ // (11 decimals) differ from site-isolation-clamped real Chrome (~100μs).
277
+ " try{",
278
+ " var _pn=performance.now.bind(performance);",
279
+ " performance.now=function(){return Math.round(_pn()*10)/10;};",
280
+ ' var _pto=Object.getOwnPropertyDescriptor(Performance.prototype,"timeOrigin");',
281
+ ' if(_pto&&_pto.get){Object.defineProperty(performance,"timeOrigin",{get:function(){return _pto.get.call(performance);},configurable:true});}',
282
+ " }catch(e){}",
283
+ // 3d. Chrome object depth (d24): automation fakes usually only set
284
+ // window.chrome = {}; deep checks hit app.run/runtime/csi/loadTimes.
285
+ " try{",
286
+ " if(window.chrome){",
287
+ ' 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"}};',
288
+ ' 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};',
289
+ " if(!window.chrome.csi)window.chrome.csi=function(){return{};}",
290
+ " if(!window.chrome.loadTimes)window.chrome.loadTimes=function(){return{};}",
291
+ " }",
292
+ " }catch(e){}",
293
+ // 3e. Font availability patch (d25): headless Chromium misses some system
294
+ // fonts (e.g. Menlo on macOS) that real Chrome has. Register a FontFace
295
+ // aliasing the missing font to a local() equivalent so offsetWidth-based
296
+ // font probing sees the same availability as the faked environment.
297
+ " try{",
298
+ ' var _fontAliases=[["Menlo","Courier New"],["SF Mono","Menlo"],["Segoe UI","Helvetica"]];',
299
+ " _fontAliases.forEach(function(pa){",
300
+ ' try{var ff=new FontFace(pa[0],"local("+JSON.stringify(pa[1])+")");',
301
+ " document.fonts.add(ff);ff.load();}catch(e2){}",
302
+ " });",
303
+ " }catch(e){}",
151
304
  // 3. toString disguise (name-list based)
152
305
  " var _ts=Function.prototype.toString;",
153
306
  " var _hf=document.hasFocus;",
@@ -157,12 +310,16 @@ function buildStealthInitScript() {
157
310
  ' if(this===_gw)return"function get width() { [native code] }";',
158
311
  ' if(this===_gh)return"function get height() { [native code] }";',
159
312
  ' if(this===_gah)return"function get availHeight() { [native code] }";',
313
+ ' if(this===CanvasRenderingContext2D.prototype.fillText)return"function fillText() { [native code] }";',
314
+ ' if(this===HTMLCanvasElement.prototype.toDataURL)return"function toDataURL() { [native code] }";',
315
+ ' if(this===AnalyserNode.prototype.getFloatFrequencyData)return"function getFloatFrequencyData() { [native code] }";',
316
+ ' if(this===AudioBuffer.prototype.getChannelData)return"function getChannelData() { [native code] }";',
160
317
  " return _ts.call(this);",
161
318
  " };",
162
319
  // 4. onclick prototype hijack (dual-stream consistency)
163
320
  " var _ba=function(k,p){",
164
- ' if(p==="isTrusted")return true;',
165
- ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isFinite(k[p])){',
321
+ ' if(p==="isTrusted")return k.isTrusted;',
322
+ ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])&&k.isTrusted===true){',
166
323
  " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;return k[p]+_f;",
167
324
  " }",
168
325
  ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
@@ -198,7 +355,7 @@ var XBMouseImpl = class {
198
355
  }
199
356
  async click(x, y, opts = {}) {
200
357
  const button = opts.button ?? "left";
201
- const stealth = opts.stealth ?? true;
358
+ const stealth = opts.stealth ?? process.env.XBROWSER_STEALTH !== "off";
202
359
  let tx = x, ty = y;
203
360
  if (stealth && opts.elementWidth !== void 0 && opts.elementHeight !== void 0) {
204
361
  const off = landingOffset(opts.elementWidth, opts.elementHeight);
@@ -207,12 +364,23 @@ var XBMouseImpl = class {
207
364
  }
208
365
  if (stealth) {
209
366
  const traj = bezierTrajectory(this._x, this._y, tx, ty);
367
+ const _tb = Date.now();
368
+ let _truncated = false;
210
369
  for (const p of traj) {
370
+ if (Date.now() - _tb > 5e3) {
371
+ _truncated = true;
372
+ break;
373
+ }
211
374
  await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
212
375
  this._x = p.x;
213
376
  this._y = p.y;
214
377
  await sleep(p.delay);
215
378
  }
379
+ this._x = tx;
380
+ this._y = ty;
381
+ if (_truncated) {
382
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button });
383
+ }
216
384
  await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
217
385
  } else {
218
386
  await this.move(tx, ty);
@@ -317,12 +485,20 @@ var XBKeyboardImpl = class {
317
485
  }
318
486
  await this.dispatchKeyEvent(downParams);
319
487
  if (mapping.text) {
488
+ if (process.env.XBROWSER_STEALTH !== "off") {
489
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
490
+ }
320
491
  await this.dispatchKeyEvent({
321
492
  type: "char",
322
493
  text: mapping.text
323
494
  });
324
495
  }
325
496
  if (delay > 0) await sleep2(delay);
497
+ else {
498
+ if (process.env.XBROWSER_STEALTH !== "off") {
499
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
500
+ }
501
+ }
326
502
  const upParams = {
327
503
  type: "keyUp",
328
504
  key: mapping.key,
@@ -1930,6 +2106,10 @@ Last error: ${lastError.message}` : "";
1930
2106
  this.sessionId
1931
2107
  );
1932
2108
  }
2109
+ /** 覆盖 User-Agent(headless 环境对抗 UA 检测的标配能力) */
2110
+ async setUserAgent(userAgent) {
2111
+ await this._setUserAgent(userAgent);
2112
+ }
1933
2113
  /** Internal: set extra HTTP headers */
1934
2114
  async _setExtraHTTPHeaders(headers) {
1935
2115
  await this.setExtraHTTPHeaders(headers);
@@ -3059,9 +3239,971 @@ var XBBrowserImpl = class {
3059
3239
  // src/cdp-driver/connection.ts
3060
3240
  import { EventEmitter as EventEmitter4 } from "events";
3061
3241
  import { WebSocket } from "ws";
3062
- var CDPConnection = class extends EventEmitter4 {
3242
+
3243
+ // src/cdp-interceptor/rules/shared.ts
3244
+ var PLAYWRIGHT_INTERNAL_MARKERS = [
3245
+ "__commonJS",
3246
+ "module.exports",
3247
+ "__require",
3248
+ "__toESM",
3249
+ "inject_utils"
3250
+ ];
3251
+ function isPlaywrightInternal(code) {
3252
+ return PLAYWRIGHT_INTERNAL_MARKERS.some((marker) => code.includes(marker));
3253
+ }
3254
+ function extractUserCode(ctx) {
3255
+ if (ctx.method === "Runtime.evaluate") {
3256
+ const expr = ctx.params.expression;
3257
+ if (typeof expr === "string") {
3258
+ if (isPlaywrightInternal(expr)) return null;
3259
+ return expr;
3260
+ }
3261
+ }
3262
+ if (ctx.method === "Runtime.callFunctionOn") {
3263
+ const decl = ctx.params.functionDeclaration;
3264
+ if (typeof decl === "string" && decl.includes("utilityScript.evaluate")) {
3265
+ return extractAllStrings(ctx.params.arguments);
3266
+ }
3267
+ if (typeof decl === "string") return decl;
3268
+ }
3269
+ return null;
3270
+ }
3271
+ function extractAllStrings(rawArgs) {
3272
+ if (!Array.isArray(rawArgs)) return null;
3273
+ const strings = [];
3274
+ for (const arg of rawArgs) {
3275
+ if (arg && typeof arg === "object" && "value" in arg) {
3276
+ const val = arg.value;
3277
+ if (typeof val === "string" && val.length > 5 && !["true", "false"].includes(val)) {
3278
+ strings.push(val);
3279
+ }
3280
+ }
3281
+ }
3282
+ return strings.length > 0 ? strings.join("\n") : null;
3283
+ }
3284
+
3285
+ // src/cdp-interceptor/rules/dom-mutation.ts
3286
+ var DOM_PATTERNS = [
3287
+ // ── P0: Value/Checked (bypasses React onChange) ────────────
3288
+ { 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." },
3289
+ { pattern: /\.checked\s*=\s*(?:true|false)/, name: ".checked =", severity: "danger", action: "pass", errorCode: -32001, suggestion: "Use page.check(selector) or page.uncheck(selector)." },
3290
+ { pattern: /\.indeterminate\s*=\s*true/, name: ".indeterminate =", severity: "warn", action: "pass", errorCode: -32021, suggestion: "No human can set indeterminate state \u2014 remove this call." },
3291
+ { pattern: /\.valueAsDate\s*=/, name: ".valueAsDate =", severity: "warn", action: "pass", errorCode: -32022, suggestion: "Use page.fill() with formatted date string instead." },
3292
+ { pattern: /\.valueAsNumber\s*=/, name: ".valueAsNumber =", severity: "warn", action: "pass", errorCode: -32022, suggestion: "Use page.fill() with numeric string instead." },
3293
+ // ── P1: Select/Option (bypasses React onChange on select) ─
3294
+ { pattern: /\.selectedIndex\s*=\s*\d+/, name: ".selectedIndex =", severity: "danger", action: "pass", errorCode: -32003, suggestion: "Use page.selectOption(selector, value)." },
3295
+ { 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)." },
3296
+ { pattern: /\.value\s*=\s*["'][^"']*["']\s*[;)]?\s*$/, name: "selectElement.value =", severity: "warn", action: "pass", errorCode: -32023, suggestion: "For select elements, use page.selectOption(selector, value)." },
3297
+ // ── P2: Content properties (bypasses virtual DOM diffing) ──
3298
+ { pattern: /\.innerHTML\s*=/, name: ".innerHTML =", severity: "info", action: "pass", errorCode: -32007, suggestion: ".innerHTML bypasses React/Vue diffing. Use component state or page.setContent()." },
3299
+ { pattern: /\.outerHTML\s*=/, name: ".outerHTML =", severity: "info", action: "pass", errorCode: -32007, suggestion: "outerHTML replacement destroys React fiber tree. Use page.setContent()." },
3300
+ { pattern: /\.innerText\s*=/, name: ".innerText =", severity: "warn", action: "pass", errorCode: -32024, suggestion: "Framework components should be updated via state, not innerText." },
3301
+ { pattern: /\.textContent\s*=/, name: ".textContent =", severity: "warn", action: "pass", errorCode: -32024, suggestion: "textContent bypasses React/Vue diffing. Use component state instead." },
3302
+ { pattern: /\.outerText\s*=/, name: ".outerText =", severity: "warn", action: "pass", errorCode: -32024, suggestion: "Non-standard property \u2014 use proper framework update methods." },
3303
+ { pattern: /nodeValue\s*=/, name: "node.nodeValue =", severity: "info", action: "pass", errorCode: -32025, suggestion: "Direct text node mutation. Use textContent instead if needed." },
3304
+ // ── P3: Style properties ──────────────────────────────────
3305
+ { 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".' },
3306
+ { 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." },
3307
+ { pattern: /\.style\.setProperty\s*\(/, name: ".style.setProperty()", severity: "info", action: "pass", errorCode: -32008, suggestion: "Direct style property set bypasses CSS transitions." },
3308
+ { pattern: /\.style\.removeProperty\s*\(/, name: ".style.removeProperty()", severity: "info", action: "pass", errorCode: -32026, suggestion: "Style removal without user interaction is suspicious." },
3309
+ { pattern: /\.style\.animation\s*=/, name: ".style.animation =", severity: "info", action: "pass", errorCode: -32027, suggestion: "Forcing animation state via CDP is detectable." },
3310
+ { pattern: /\.style\.transition\s*=/, name: ".style.transition =", severity: "info", action: "pass", errorCode: -32027, suggestion: "Manipulating CSS transitions is rare in normal browsing." },
3311
+ // ── P4: Class/Attribute properties ────────────────────────
3312
+ { pattern: /\.className\s*=/, name: ".className =", severity: "info", action: "pass", errorCode: -32009, suggestion: "Use component state or a Playwright locator instead." },
3313
+ { pattern: /\.classList\.add\s*\(/, name: ".classList.add()", severity: "info", action: "pass", errorCode: -32009, suggestion: "classList manipulation via CDP bypasses framework state tracking." },
3314
+ { pattern: /\.classList\.remove\s*\(/, name: ".classList.remove()", severity: "info", action: "pass", errorCode: -32009, suggestion: "Use component state or attribute selectors instead." },
3315
+ { pattern: /\.classList\.toggle\s*\(/, name: ".classList.toggle()", severity: "info", action: "pass", errorCode: -32009, suggestion: "Toggle without user interaction is detectable." },
3316
+ { pattern: /\.classList\.replace\s*\(/, name: ".classList.replace()", severity: "info", action: "pass", errorCode: -32028, suggestion: "Rare operation \u2014 likely automated." },
3317
+ // ── P5: Attribute manipulation ────────────────────────────
3318
+ { pattern: /\.setAttribute\s*\(/, name: ".setAttribute()", severity: "info", action: "pass", errorCode: -32010, suggestion: "setAttribute bypasses framework attribute tracking. Use component state." },
3319
+ { pattern: /\.removeAttribute\s*\(/, name: ".removeAttribute()", severity: "info", action: "pass", errorCode: -32010, suggestion: "Attribute removal without user interaction is suspicious." },
3320
+ { pattern: /\.toggleAttribute\s*\(/, name: ".toggleAttribute()", severity: "info", action: "pass", errorCode: -32029, suggestion: "Attribute toggling via CDP is detectable." },
3321
+ { pattern: /\.dataset\.\w+\s*=/, name: ".dataset.* =", severity: "info", action: "pass", errorCode: -32030, suggestion: "dataset mutations via evaluate bypass native mutation observers." },
3322
+ // ── P6: Focus/Selection properties ────────────────────────
3323
+ { pattern: /\.selectionStart\s*=/, name: ".selectionStart =", severity: "info", action: "pass", errorCode: -32011, suggestion: "Setting cursor position without focus is detectable." },
3324
+ { pattern: /\.selectionEnd\s*=/, name: ".selectionEnd =", severity: "info", action: "pass", errorCode: -32011, suggestion: "Selection range manipulation without user input is suspicious." },
3325
+ { pattern: /\.selectionDirection\s*=/, name: ".selectionDirection =", severity: "info", action: "pass", errorCode: -32031, suggestion: "Selection direction changes normally via mouse drag." },
3326
+ // ── P7: Boolean properties ────────────────────────────────
3327
+ { pattern: /\.disabled\s*=/, name: ".disabled =", severity: "info", action: "pass", errorCode: -32012, suggestion: "Disabling elements via CDP mid-interaction is detectable." },
3328
+ { pattern: /\.readOnly\s*=/, name: ".readOnly =", severity: "info", action: "pass", errorCode: -32032, suggestion: "readOnly changes without user action." },
3329
+ { pattern: /\.hidden\s*=/, name: ".hidden =", severity: "info", action: "pass", errorCode: -32012, suggestion: "Hiding elements is a common scraper tactic \u2014 detectable." },
3330
+ { pattern: /\.required\s*=/, name: ".required =", severity: "info", action: "pass", errorCode: -32032, suggestion: "Validation constraint changes mid-session." },
3331
+ { pattern: /\.multiple\s*=/, name: ".multiple =", severity: "info", action: "pass", errorCode: -32032, suggestion: "Multiple attribute toggle is rare in normal browsing." },
3332
+ { pattern: /\.autofocus\s*=/, name: ".autofocus =", severity: "info", action: "pass", errorCode: -32032, suggestion: "autofocus changes mid-session are suspicious." },
3333
+ // ── P8: Frame/Navigation properties ───────────────────────
3334
+ { 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." },
3335
+ { pattern: /\.href\s*=/, name: ".href =", severity: "info", action: "pass", errorCode: -32033, suggestion: "Changing anchor href via evaluate \u2014 use page.click() instead." },
3336
+ { pattern: /\.action\s*=/, name: "form.action =", severity: "info", action: "pass", errorCode: -32034, suggestion: "Changing form action URL is highly suspicious." },
3337
+ { pattern: /\.method\s*=/, name: "form.method =", severity: "info", action: "pass", errorCode: -32034, suggestion: "Form method changes without user interaction." },
3338
+ { pattern: /\.target\s*=/, name: "link/area.target =", severity: "info", action: "pass", errorCode: -32034, suggestion: "Link target manipulation via CDP." },
3339
+ // ── P9: Media properties ──────────────────────────────────
3340
+ { pattern: /\.currentTime\s*=/, name: "media.currentTime = (seeking)", severity: "info", action: "pass", errorCode: -32014, suggestion: "Video seeking without user interaction \u2014 common scraper pattern." },
3341
+ { pattern: /\.playbackRate\s*=/, name: "media.playbackRate =", severity: "info", action: "pass", errorCode: -32014, suggestion: "Changing playback speed is detectable automation signal." },
3342
+ { pattern: /\.volume\s*=/, name: "media.volume =", severity: "info", action: "pass", errorCode: -32035, suggestion: "Volume setting via evaluate is suspicious." },
3343
+ { pattern: /\.muted\s*=/, name: "media.muted =", severity: "info", action: "pass", errorCode: -32035, suggestion: "Muting media without user click is suspicious." },
3344
+ // ── P10: Element geometry ─────────────────────────────────
3345
+ { pattern: /\.scrollTop\s*=/, name: ".scrollTop =", severity: "info", action: "pass", errorCode: -32015, suggestion: "Programmatic scroll without user gesture. Use page.mouse.wheel()." },
3346
+ { pattern: /\.scrollLeft\s*=/, name: ".scrollLeft =", severity: "info", action: "pass", errorCode: -32015, suggestion: "Horizontal scroll without user gesture." },
3347
+ { pattern: /\.scrollTo\s*\(/, name: ".scrollTo()", severity: "info", action: "pass", errorCode: -32015, suggestion: "ScrollTo bypasses user scroll detection." },
3348
+ { pattern: /\.scrollBy\s*\(/, name: ".scrollBy()", severity: "info", action: "pass", errorCode: -32015, suggestion: "ScrollBy without user gesture." },
3349
+ { pattern: /\.scrollIntoView\s*\(/, name: ".scrollIntoView()", severity: "info", action: "pass", errorCode: -32015, suggestion: "scrollIntoView is a common bot pattern. Let Playwright handle scrolling." },
3350
+ // ── P11: Shadow DOM ───────────────────────────────────────
3351
+ { pattern: /\.shadowRoot\s*=/, name: ".shadowRoot = (override)", severity: "info", action: "pass", errorCode: -32036, suggestion: "ShadowRoot is read-only \u2014 this set attempt is detectable." },
3352
+ // ── P12: Force reflow / layout thrashing ──────────────────
3353
+ { 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." },
3354
+ { pattern: /\.offsetWidth\b(?!\s*===?\s*)/, name: ".offsetWidth read (forced reflow)", severity: "warn", action: "pass", errorCode: -32016, suggestion: "Reading offsetWidth triggers forced reflow \u2014 detectable." },
3355
+ { pattern: /getBoundingClientRect\s*\(/, name: "getBoundingClientRect()", severity: "warn", action: "pass", errorCode: -32037, suggestion: "getBoundingClientRect triggers reflow. Minimize calls." },
3356
+ { pattern: /getComputedStyle\s*\(/, name: "getComputedStyle()", severity: "info", action: "pass", errorCode: -32038, suggestion: "getComputedStyle can trigger style recalculation." },
3357
+ { pattern: /\.clientHeight\b/, name: ".clientHeight read", severity: "info", action: "pass", errorCode: -32038, suggestion: "clientHeight read triggers layout." },
3358
+ { pattern: /\.clientWidth\b/, name: ".clientWidth read", severity: "info", action: "pass", errorCode: -32038, suggestion: "clientWidth read triggers layout." }
3359
+ ];
3360
+ var domMutationRule = {
3361
+ id: "dom-mutation",
3362
+ name: "DOM Property Mutation Detection (50+ setters)",
3363
+ priority: 10,
3364
+ canHandle(ctx) {
3365
+ return ctx.method === "Runtime.evaluate" || ctx.method === "Runtime.callFunctionOn";
3366
+ },
3367
+ evaluate(ctx) {
3368
+ const userCode = extractUserCode(ctx);
3369
+ if (!userCode) return null;
3370
+ for (const p of DOM_PATTERNS) {
3371
+ if (p.pattern.test(userCode)) {
3372
+ return {
3373
+ ruleId: "dom-mutation",
3374
+ action: p.action,
3375
+ severity: p.severity,
3376
+ reason: `Direct DOM property setter: "${p.name}". This bypasses framework event systems and is detectable as automation.`,
3377
+ suggestion: p.suggestion,
3378
+ errorCode: p.errorCode,
3379
+ errorMessage: p.severity === "danger" ? `[CDP Firewall] ${p.name} blocked \u2014 bypasses framework reactivity` : `[CDP Firewall] ${p.name} detected \u2014 use proper interaction API`
3380
+ };
3381
+ }
3382
+ }
3383
+ return null;
3384
+ }
3385
+ };
3386
+
3387
+ // src/cdp-interceptor/rules/mouse-trajectory.ts
3388
+ var TRACKER_KEY = "mouse-trajectory-tracker";
3389
+ var MAX_SAMPLES = 200;
3390
+ var MIN_SAMPLES_FOR_ANALYSIS = 5;
3391
+ var mouseTrajectoryRule = {
3392
+ id: "mouse-trajectory",
3393
+ name: "Mouse Trajectory Analysis",
3394
+ priority: 20,
3395
+ canHandle(ctx) {
3396
+ return ctx.method === "Input.dispatchMouseEvent";
3397
+ },
3398
+ evaluate(ctx) {
3399
+ const type = ctx.params.type;
3400
+ const x = ctx.params.x;
3401
+ const y = ctx.params.y;
3402
+ if (typeof x !== "number" || typeof y !== "number") return null;
3403
+ let tracker = ctx.sessionState.get(TRACKER_KEY);
3404
+ if (!tracker) {
3405
+ tracker = { samples: [], lastMouseDownAt: 0, isDragging: false };
3406
+ ctx.sessionState.set(TRACKER_KEY, tracker);
3407
+ }
3408
+ if (type === "mousePressed") {
3409
+ const priorResult = analyzeTrajectory(tracker.samples);
3410
+ tracker.lastMouseDownAt = Date.now();
3411
+ tracker.isDragging = true;
3412
+ tracker.samples = [];
3413
+ return priorResult;
3414
+ }
3415
+ if (type === "mouseReleased") {
3416
+ tracker.isDragging = false;
3417
+ const result = analyzeTrajectory(tracker.samples);
3418
+ tracker.samples = [];
3419
+ return result;
3420
+ }
3421
+ if (type === "mouseMoved") {
3422
+ const now = Date.now();
3423
+ const prevSample = tracker.samples[tracker.samples.length - 1];
3424
+ const distanceTraveled = prevSample ? prevSample.distanceTraveled + distance(prevSample.x, prevSample.y, x, y) : 0;
3425
+ const sample = { x, y, timestamp: now, distanceTraveled };
3426
+ tracker.samples.push(sample);
3427
+ if (tracker.samples.length > MAX_SAMPLES) {
3428
+ tracker.samples.shift();
3429
+ }
3430
+ return null;
3431
+ }
3432
+ if (type === "mouseReleased" && tracker.samples.length < MIN_SAMPLES_FOR_ANALYSIS) {
3433
+ tracker.samples = [];
3434
+ return null;
3435
+ }
3436
+ return null;
3437
+ }
3438
+ };
3439
+ function analyzeTrajectory(samples) {
3440
+ if (samples.length < MIN_SAMPLES_FOR_ANALYSIS) return null;
3441
+ const issues = [];
3442
+ const startX = samples[0].x;
3443
+ const startY = samples[0].y;
3444
+ const endX = samples[samples.length - 1].x;
3445
+ const endY = samples[samples.length - 1].y;
3446
+ const lineLength = distance(startX, startY, endX, endY);
3447
+ const collinearityResult = checkCollinearity(samples, startX, startY, endX, endY, lineLength);
3448
+ if (collinearityResult) {
3449
+ issues.push(collinearityResult);
3450
+ }
3451
+ const velocityResult = checkConstantVelocity(samples);
3452
+ if (velocityResult) {
3453
+ issues.push(velocityResult);
3454
+ }
3455
+ const jitterResult = checkJitter(samples);
3456
+ if (jitterResult) {
3457
+ issues.push(jitterResult);
3458
+ }
3459
+ if (issues.length === 0) return null;
3460
+ const stopX = samples[samples.length - 1].x;
3461
+ const stopY = samples[samples.length - 1].y;
3462
+ return {
3463
+ ruleId: "mouse-trajectory",
3464
+ action: "pass",
3465
+ severity: "danger",
3466
+ reason: `Suspicious mouse trajectory: ${issues.join("; ")}`,
3467
+ suggestion: `This mouse movement appears automated (straight line A\u2192B, no natural variation).
3468
+ Use a humanized mouse API that generates:
3469
+ - Bezier curves instead of straight lines
3470
+ - Random acceleration/deceleration
3471
+ - 1-3px micro-jitter per sample
3472
+
3473
+ Example: The 'faker' or 'ghost-cursor' libraries generate realistic mouse paths.
3474
+ Target was: (${Math.round(startX)}, ${Math.round(startY)}) \u2192 (${Math.round(stopX)}, ${Math.round(stopY)})`,
3475
+ errorCode: -32002,
3476
+ errorMessage: "[CDP Firewall] Automated mouse trajectory blocked \u2014 appears non-human"
3477
+ };
3478
+ }
3479
+ function distance(x1, y1, x2, y2) {
3480
+ return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
3481
+ }
3482
+ function checkCollinearity(samples, x1, y1, x2, y2, lineLength) {
3483
+ if (lineLength < 5) return null;
3484
+ let maxDeviation = 0;
3485
+ const dx = x2 - x1;
3486
+ const dy = y2 - y1;
3487
+ for (let i = 1; i < samples.length - 1; i++) {
3488
+ const { x, y } = samples[i];
3489
+ const cross = Math.abs(dy * x - dx * y + x2 * y1 - y2 * x1);
3490
+ const dev = cross / lineLength;
3491
+ if (dev > maxDeviation) maxDeviation = dev;
3492
+ }
3493
+ if (maxDeviation < 1.5 && lineLength > 20) {
3494
+ return `Perfectly straight line (max deviation ${maxDeviation.toFixed(1)}px over ${lineLength.toFixed(0)}px)`;
3495
+ }
3496
+ if (maxDeviation < 0.5 && lineLength > 10) {
3497
+ return `Near-perfect straight line (max deviation ${maxDeviation.toFixed(1)}px)`;
3498
+ }
3499
+ return null;
3500
+ }
3501
+ function checkConstantVelocity(samples) {
3502
+ if (samples.length < 3) return null;
3503
+ const speeds = [];
3504
+ for (let i = 1; i < samples.length; i++) {
3505
+ const d = distance(
3506
+ samples[i - 1].x,
3507
+ samples[i - 1].y,
3508
+ samples[i].x,
3509
+ samples[i].y
3510
+ );
3511
+ const dt = samples[i].timestamp - samples[i - 1].timestamp;
3512
+ if (dt > 0) speeds.push(d / dt);
3513
+ }
3514
+ if (speeds.length < 2) return null;
3515
+ const mean = speeds.reduce((a, b) => a + b, 0) / speeds.length;
3516
+ if (mean === 0) return null;
3517
+ const variance = speeds.reduce((sum, v) => sum + (v - mean) ** 2, 0) / speeds.length;
3518
+ const stddev = Math.sqrt(variance);
3519
+ const cv = stddev / mean;
3520
+ if (cv < 0.05) {
3521
+ return `Constant velocity (CV=${cv.toFixed(3)}, mean=${mean.toFixed(1)} px/ms)`;
3522
+ }
3523
+ return null;
3524
+ }
3525
+ function checkJitter(samples) {
3526
+ if (samples.length < 4) return null;
3527
+ let totalLateralChange = 0;
3528
+ for (let i = 1; i < samples.length; i++) {
3529
+ const d = distance(
3530
+ samples[i - 1].x,
3531
+ samples[i - 1].y,
3532
+ samples[i].x,
3533
+ samples[i].y
3534
+ );
3535
+ totalLateralChange += d;
3536
+ }
3537
+ const avgLateral = totalLateralChange / (samples.length - 1);
3538
+ if (avgLateral < 0.3) {
3539
+ return "No micro-jitter (sub-pixel precision, impossible for human)";
3540
+ }
3541
+ return null;
3542
+ }
3543
+
3544
+ // src/cdp-interceptor/rules/input-keystroke.ts
3545
+ var TRACKER_KEY2 = "keystroke-tracker";
3546
+ var MIN_KEYS_FOR_ANALYSIS = 4;
3547
+ var inputKeystrokeRule = {
3548
+ id: "input-keystroke",
3549
+ name: "Input Keystroke Timing Analysis",
3550
+ priority: 40,
3551
+ canHandle(ctx) {
3552
+ return ctx.method === "Input.dispatchKeyEvent" || ctx.method === "Input.insertText";
3553
+ },
3554
+ evaluate(ctx) {
3555
+ if (ctx.method === "Input.insertText") {
3556
+ return {
3557
+ ruleId: "input-keystroke",
3558
+ action: "pass",
3559
+ severity: "info",
3560
+ reason: "Input.insertText bypasses native keyboard events. Playwright uses this internally for page.fill().",
3561
+ suggestion: "Prefer page.type() with variable delay for human-like input.",
3562
+ errorCode: -32004,
3563
+ errorMessage: "[CDP Firewall] Input.insertText detected \u2014 note: Playwright uses this for fill()"
3564
+ };
3565
+ }
3566
+ let tracker = ctx.sessionState.get(TRACKER_KEY2);
3567
+ if (!tracker) {
3568
+ tracker = { samples: [] };
3569
+ ctx.sessionState.set(TRACKER_KEY2, tracker);
3570
+ }
3571
+ const type = ctx.params.type;
3572
+ const code = ctx.params.code;
3573
+ const key = ctx.params.key;
3574
+ if (type === "keyDown" && key && key.length === 1) {
3575
+ tracker.samples.push({
3576
+ code,
3577
+ key,
3578
+ timestamp: Date.now(),
3579
+ type
3580
+ });
3581
+ }
3582
+ if (tracker.samples.length >= MIN_KEYS_FOR_ANALYSIS && (type === "keyUp" || type === "keyDown")) {
3583
+ return analyzeKeyTiming(tracker.samples);
3584
+ }
3585
+ return null;
3586
+ }
3587
+ };
3588
+ function analyzeKeyTiming(samples) {
3589
+ if (samples.length < MIN_KEYS_FOR_ANALYSIS) return null;
3590
+ const intervals = [];
3591
+ for (let i = 1; i < samples.length; i++) {
3592
+ const dt = samples[i].timestamp - samples[i - 1].timestamp;
3593
+ if (dt > 0) intervals.push(dt);
3594
+ }
3595
+ if (intervals.length < 3) return null;
3596
+ const mean = intervals.reduce((a, b) => a + b, 0) / intervals.length;
3597
+ if (mean === 0) return null;
3598
+ const variance = intervals.reduce((sum, v) => sum + (v - mean) ** 2, 0) / intervals.length;
3599
+ const stddev = Math.sqrt(variance);
3600
+ const cv = stddev / mean;
3601
+ const uniqueIntervals = new Set(intervals);
3602
+ const allIdentical = uniqueIntervals.size === 1;
3603
+ if (allIdentical) {
3604
+ return {
3605
+ ruleId: "input-keystroke",
3606
+ action: "pass",
3607
+ severity: "danger",
3608
+ reason: `All ${intervals.length} keystroke intervals are exactly ${intervals[0]}ms \u2014 impossible for human typing.`,
3609
+ suggestion: `Use page.fill(selector, text) instead of page.type() with delay.
3610
+ Or add random variation: page.type(selector, text, {delay: 50 + Math.random() * 80}).`,
3611
+ errorCode: -32004,
3612
+ errorMessage: "[CDP Firewall] Constant keystroke timing detected \u2014 automated typing pattern"
3613
+ };
3614
+ }
3615
+ if (cv < 0.08) {
3616
+ return {
3617
+ ruleId: "input-keystroke",
3618
+ action: "pass",
3619
+ severity: "warn",
3620
+ reason: `Unnatural keystroke timing (CV=${cv.toFixed(3)}). Human typing has CV > 0.2 on average.`,
3621
+ suggestion: `Add random variation to your typing delay: page.type(selector, text, {delay: 50 + Math.random() * 80}).`,
3622
+ errorCode: -32004,
3623
+ errorMessage: "[CDP Firewall] Suspicious keystroke timing \u2014 likely automated"
3624
+ };
3625
+ }
3626
+ return null;
3627
+ }
3628
+
3629
+ // src/cdp-interceptor/rules/automation-signals.ts
3630
+ var AUTOMATION_PATTERNS = [
3631
+ // ── Playwright markers ─────────────────────────
3632
+ { pattern: /window\s*\.\s*__playwright/, name: "window.__playwright", severity: "danger", errorCode: -32040 },
3633
+ { pattern: /window\s*\.\s*__pw_[a-zA-Z]/, name: "window.__pw_*", severity: "danger", errorCode: -32040 },
3634
+ { pattern: /window\s*\.\s*__pw_paused/, name: "window.__pw_paused", severity: "danger", errorCode: -32040 },
3635
+ { pattern: /window\s*\.\s*playwright\b/, name: "window.playwright", severity: "danger", errorCode: -32040 },
3636
+ { pattern: /window\s*\.\s*__pw_recorder/, name: "window.__pw_recorder", severity: "warn", errorCode: -32041 },
3637
+ { pattern: /window\s*\.\s*__pw_trace/, name: "window.__pw_trace", severity: "warn", errorCode: -32041 },
3638
+ // ── Puppeteer markers ──────────────────────────
3639
+ { pattern: /window\s*\.\s*__puppeteer\b/, name: "window.__puppeteer", severity: "danger", errorCode: -32040 },
3640
+ { pattern: /window\s*\.\s*__puppeteer_evaluation_script/, name: "window.__puppeteer_evaluation_script", severity: "danger", errorCode: -32040 },
3641
+ { pattern: /window\s*\.\s*__puppeteer_testId/, name: "window.__puppeteer_testId", severity: "warn", errorCode: -32041 },
3642
+ { pattern: /window\s*\.\s*__puppeteer_/, name: "window.__puppeteer_*", severity: "danger", errorCode: -32040 },
3643
+ { pattern: /window\s*\.\s*_puppeteer\b/, name: "window._puppeteer", severity: "warn", errorCode: -32041 },
3644
+ // ── Selenium / WebDriver markers ───────────────
3645
+ { pattern: /window\s*\.\s*__webdriver_script_fn/, name: "window.__webdriver_script_fn", severity: "danger", errorCode: -32040 },
3646
+ { pattern: /window\s*\.\s*__selenium\b/, name: "window.__selenium", severity: "danger", errorCode: -32040 },
3647
+ { pattern: /window\s*\.\s*__selenium_evaluate/, name: "window.__selenium_evaluate", severity: "danger", errorCode: -32040 },
3648
+ { pattern: /window\s*\.\s*__driver_evaluate/, name: "window.__driver_evaluate", severity: "warn", errorCode: -32041 },
3649
+ { pattern: /window\s*\.\s*__webdriver_evaluate/, name: "window.__webdriver_evaluate", severity: "danger", errorCode: -32040 },
3650
+ { pattern: /document\.\$cdc_/, name: "document.$cdc_* (Selenium marker)", severity: "danger", errorCode: -32040 },
3651
+ { pattern: /document\.\$chrome_asyncScriptInfo/, name: "document.$chrome_asyncScriptInfo", severity: "danger", errorCode: -32040 },
3652
+ // ── navigator.webdriver detection ─────────────
3653
+ { pattern: /navigator\s*\.\s*webdriver/, name: "navigator.webdriver read", severity: "danger", errorCode: -32042 },
3654
+ { pattern: /navigator\[["']webdriver["']\]/, name: 'navigator["webdriver"]', severity: "danger", errorCode: -32042 },
3655
+ // ── Chrome headless API surface checks ────────
3656
+ { pattern: /chrome\s*\.\s*app/, name: "chrome.app detection", severity: "danger", errorCode: -32043 },
3657
+ { pattern: /chrome\s*\.\s*runtime/, name: "chrome.runtime detection", severity: "danger", errorCode: -32043 },
3658
+ { pattern: /chrome\s*\.\s*loadTimes/, name: "chrome.loadTimes detection", severity: "warn", errorCode: -32044 },
3659
+ { pattern: /chrome\s*\.\s*csi\b/, name: "chrome.csi detection", severity: "warn", errorCode: -32044 },
3660
+ { pattern: /window\s*\.\s*chrome\b/, name: "window.chrome object probe", severity: "warn", errorCode: -32044 },
3661
+ { pattern: /navigator\s*\.\s*plugins\b/, name: "navigator.plugins enumeration", severity: "warn", errorCode: -32044 },
3662
+ { pattern: /navigator\s*\.\s*mimeTypes/, name: "navigator.mimeTypes enumeration", severity: "warn", errorCode: -32044 },
3663
+ { pattern: /navigator\s*\.\s*hardwareConcurrency/, name: "navigator.hardwareConcurrency", severity: "warn", errorCode: -32044 },
3664
+ { pattern: /navigator\s*\.\s*deviceMemory/, name: "navigator.deviceMemory", severity: "info", errorCode: -32045 },
3665
+ { pattern: /navigator\s*\.\s*maxTouchPoints/, name: "navigator.maxTouchPoints", severity: "warn", errorCode: -32044 },
3666
+ { pattern: /navigator\s*\.\s*languages/, name: "navigator.languages", severity: "info", errorCode: -32045 },
3667
+ { pattern: /navigator\s*\.\s*platform/, name: "navigator.platform", severity: "info", errorCode: -32045 },
3668
+ // ── Anti-detection injection attempts ─────────
3669
+ { 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." },
3670
+ { 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." },
3671
+ { 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." },
3672
+ // ── PhantomJS / Headless markers ──────────────
3673
+ { pattern: /window\s*\.\s*callPhantom/, name: "window.callPhantom", severity: "danger", errorCode: -32040 },
3674
+ { pattern: /window\s*\.\s*_phantom/, name: "window._phantom", severity: "danger", errorCode: -32040 },
3675
+ { pattern: /window\s*\.\s*phantom\b/, name: "window.phantom", severity: "danger", errorCode: -32040 },
3676
+ { pattern: /window\s*\.\s*Buffer\b/, name: "window.Buffer (Node.js leak)", severity: "danger", errorCode: -32040 },
3677
+ { pattern: /window\s*\.\s*process\b/, name: "window.process (Node.js leak)", severity: "danger", errorCode: -32040 },
3678
+ { pattern: /window\s*\.\s*global\b/, name: "window.global (Node.js leak)", severity: "danger", errorCode: -32040 },
3679
+ { pattern: /window\s*\.\s*__dirname/, name: "window.__dirname (Node.js leak)", severity: "danger", errorCode: -32040 }
3680
+ ];
3681
+ var automationSignalsRule = {
3682
+ id: "automation-signals",
3683
+ name: "Browser Automation Signal Detection (35+ markers)",
3684
+ priority: 20,
3685
+ canHandle(ctx) {
3686
+ return ctx.method === "Runtime.evaluate" || ctx.method === "Runtime.callFunctionOn" || ctx.method === "Page.addScriptToEvaluateOnNewDocument";
3687
+ },
3688
+ evaluate(ctx) {
3689
+ if (ctx.method === "Page.addScriptToEvaluateOnNewDocument") {
3690
+ const source = ctx.params.source;
3691
+ if (typeof source === "string") {
3692
+ for (const p of AUTOMATION_PATTERNS) {
3693
+ if (p.pattern.test(source)) {
3694
+ return makeDecision(p, source.substring(0, 60));
3695
+ }
3696
+ }
3697
+ }
3698
+ return null;
3699
+ }
3700
+ const userCode = extractUserCode(ctx);
3701
+ if (!userCode) return null;
3702
+ for (const p of AUTOMATION_PATTERNS) {
3703
+ if (p.pattern.test(userCode)) {
3704
+ return makeDecision(p, userCode.substring(0, 60));
3705
+ }
3706
+ }
3707
+ return null;
3708
+ }
3709
+ };
3710
+ function makeDecision(p, context) {
3711
+ const suggestion = p.suggestionOverride ?? `Detected: "${p.name}" \u2014 an automation tool marker that anti-crawler systems immediately flag. Remove this pattern from your code.`;
3712
+ return {
3713
+ ruleId: "automation-signals",
3714
+ action: "pass",
3715
+ severity: p.severity,
3716
+ reason: `Automation marker detected: "${p.name}". Context: "${context}..."`,
3717
+ suggestion,
3718
+ errorCode: p.errorCode,
3719
+ errorMessage: p.severity === "danger" ? `[CDP Firewall] ${p.name} blocked \u2014 automation tool marker detected` : `[CDP Firewall] ${p.name} detected \u2014 potential automation signal`
3720
+ };
3721
+ }
3722
+
3723
+ // src/cdp-interceptor/rules/fingerprinting.ts
3724
+ var FP_PATTERNS = [
3725
+ // ── Canvas Rendering fingerprinting ────────────────────
3726
+ { pattern: /\.toDataURL\s*\(/, name: "canvas.toDataURL()", severity: "danger", errorCode: -32050, suggestion: "canvas.toDataURL() returns a unique hash that identifies the browser engine. Minimize calls." },
3727
+ { pattern: /\.toBlob\s*\(/, name: "canvas.toBlob()", severity: "danger", errorCode: -32050, suggestion: "canvas.toBlob() is used for canvas fingerprinting. Avoid if possible." },
3728
+ { pattern: /getImageData\s*\(/, name: "CanvasRenderingContext2D.getImageData()", severity: "danger", errorCode: -32050, suggestion: "getImageData reads pixel-level data used for fingerprinting." },
3729
+ { pattern: /measureText\s*\(/, name: "CanvasRenderingContext2D.measureText()", severity: "warn", errorCode: -32051, suggestion: "Font metrics reveal installed fonts \u2014 a fingerprinting vector." },
3730
+ { pattern: /OffscreenCanvas\s*\(/, name: "new OffscreenCanvas()", severity: "warn", errorCode: -32051, suggestion: "OffscreenCanvas is sometimes used to avoid visibility detection." },
3731
+ { pattern: /convertToBlob\s*\(/, name: "OffscreenCanvas.convertToBlob()", severity: "warn", errorCode: -32051, suggestion: "Headless OffscreenCanvas rendering differs from real browser." },
3732
+ // ── WebGL Fingerprinting ──────────────────────────────
3733
+ { 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." },
3734
+ { pattern: /getSupportedExtensions\s*\(/, name: "WebGL getSupportedExtensions()", severity: "warn", errorCode: -32053, suggestion: "WebGL extension list differs in headless mode." },
3735
+ { pattern: /getShaderPrecisionFormat\s*\(/, name: "WebGL getShaderPrecisionFormat()", severity: "info", errorCode: -32054, suggestion: "Shader precision differs between headless and real GPU." },
3736
+ { 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." },
3737
+ { pattern: /UNMASKED_RENDERER_WEBGL/, name: "WEBGL_debug_renderer_info UNMASKED_RENDERER", severity: "warn", errorCode: -32053, suggestion: "Unmasked renderer string reveals the real GPU." },
3738
+ // ── AudioContext Fingerprinting ────────────────────────
3739
+ { pattern: /AnalyserNode\s*\(/, name: "new AnalyserNode()", severity: "warn", errorCode: -32055, suggestion: "Audio fingerprinting via AnalyserNode \u2014 produces silence in headless." },
3740
+ { pattern: /getFloatFrequencyData\s*\(/, name: "AnalyserNode.getFloatFrequencyData()", severity: "danger", errorCode: -32050, suggestion: "Audio frequency data in headless returns silence (all zeros) \u2014 detectable." },
3741
+ { pattern: /getByteFrequencyData\s*\(/, name: "AnalyserNode.getByteFrequencyData()", severity: "danger", errorCode: -32050, suggestion: "Audio byte frequency data in headless returns zeros." },
3742
+ { pattern: /getByteTimeDomainData\s*\(/, name: "AnalyserNode.getByteTimeDomainData()", severity: "danger", errorCode: -32050, suggestion: "Time domain audio data in headless is a flat line \u2014 detectable." },
3743
+ { pattern: /OfflineAudioContext\s*\(/, name: "new OfflineAudioContext()", severity: "warn", errorCode: -32055, suggestion: "Offline audio rendering is a known fingerprinting method." },
3744
+ { pattern: /OscillatorNode\s*\(/, name: "new OscillatorNode()", severity: "info", errorCode: -32056, suggestion: "Audio oscillator used in fingerprinting probes." },
3745
+ // ── Navigator property probing ───────────────────────
3746
+ { 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).' },
3747
+ { 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." },
3748
+ { 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." },
3749
+ { pattern: /navigator\s*\.\s*permissions\s*\.\s*query/, name: "navigator.permissions.query()", severity: "info", errorCode: -32059, suggestion: "Permission queries can reveal automation environment." },
3750
+ // ── Screen / Window geometry probing ──────────────────
3751
+ { pattern: /screen\.avail(Width|Height|Left|Top)/, name: "screen.avail*", severity: "warn", errorCode: -32060, suggestion: "screen.avail* values differ in headless (no OS chrome)." },
3752
+ { 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." },
3753
+ { 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." },
3754
+ { pattern: /screen\.width\b/, name: "screen.width", severity: "info", errorCode: -32061, suggestion: "Screen dimensions can be spoofed but inconsistencies with viewport are detectable." },
3755
+ { pattern: /screen\.height\b/, name: "screen.height", severity: "info", errorCode: -32061, suggestion: "Screen dimension probes for viewport inconsistency detection." },
3756
+ { pattern: /window\.devicePixelRatio/, name: "window.devicePixelRatio", severity: "warn", errorCode: -32060, suggestion: "devicePixelRatio is always 1 in headless \u2014 differs from real displays." },
3757
+ { pattern: /matchMedia\s*\(/, name: "window.matchMedia()", severity: "warn", errorCode: -32060, suggestion: "matchMedia can detect CDP overridden viewport dimensions." },
3758
+ // ── Performance / Timing API ──────────────────────────
3759
+ { pattern: /performance\s*\.\s*now\s*\(/, name: "performance.now()", severity: "info", errorCode: -32062, suggestion: "High-resolution timer used for timing attacks and bot detection." },
3760
+ { pattern: /performance\s*\.\s*memory/, name: "performance.memory", severity: "warn", errorCode: -32063, suggestion: "performance.memory shows VM memory limits in containers." },
3761
+ { pattern: /performance\.getEntriesByType\s*\(\s*["']navigation["']\s*\)/, name: 'performance.getEntriesByType("navigation")', severity: "info", errorCode: -32062, suggestion: "Navigation timing reveals request pattern inconsistencies." },
3762
+ { pattern: /performance\.getEntriesByType\s*\(\s*["']resource["']\s*\)/, name: 'performance.getEntriesByType("resource")', severity: "info", errorCode: -32062, suggestion: "Resource loading timing analysis for bot detection." },
3763
+ // ── Font Detection ────────────────────────────────────
3764
+ { 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." },
3765
+ { pattern: /document\.fonts\.ready/, name: "document.fonts.ready", severity: "info", errorCode: -32065, suggestion: "Font loading state probe for fingerprinting." },
3766
+ // ── WebRTC / Connectivity ────────────────────────────
3767
+ { pattern: /RTCPeerConnection\s*\(/, name: "new RTCPeerConnection()", severity: "warn", errorCode: -32066, suggestion: "WebRTC can leak internal IP and is used for connectivity fingerprinting." },
3768
+ { pattern: /navigator\.mediaDevices\.getUserMedia/, name: "navigator.mediaDevices.getUserMedia()", severity: "info", errorCode: -32067, suggestion: "getUserMedia always fails in headless (no camera)." },
3769
+ // ── Feature Consistency Checks ─────────────────────────
3770
+ { 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." },
3771
+ { 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." },
3772
+ { 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." },
3773
+ { pattern: /Function\.prototype\.toString/, name: "Function.prototype.toString on native fn", severity: "info", errorCode: -32070, suggestion: "Native function toString() format can reveal patched APIs." }
3774
+ ];
3775
+ var fingerprintingRule = {
3776
+ id: "fingerprinting",
3777
+ name: "Browser Fingerprinting Access Detection (35+ APIs)",
3778
+ priority: 30,
3779
+ canHandle(ctx) {
3780
+ return ctx.method === "Runtime.evaluate" || ctx.method === "Runtime.callFunctionOn";
3781
+ },
3782
+ evaluate(ctx) {
3783
+ const userCode = extractUserCode(ctx);
3784
+ if (!userCode) return null;
3785
+ for (const p of FP_PATTERNS) {
3786
+ if (p.pattern.test(userCode)) {
3787
+ return {
3788
+ ruleId: "fingerprinting",
3789
+ action: "pass",
3790
+ severity: p.severity,
3791
+ reason: `Browser fingerprinting API accessed: "${p.name}". Anti-crawler systems use this to identify your browser.`,
3792
+ suggestion: p.suggestion,
3793
+ errorCode: p.errorCode,
3794
+ errorMessage: `[CDP Firewall] ${p.name} blocked \u2014 fingerprinting API access detected`
3795
+ };
3796
+ }
3797
+ }
3798
+ return null;
3799
+ }
3800
+ };
3801
+
3802
+ // src/cdp-interceptor/rules/event-simulation.ts
3803
+ var EVENT_PATTERNS = [
3804
+ // ── Direct method calls (all isTrusted=false) ─────────
3805
+ { 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)." },
3806
+ { 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." },
3807
+ { pattern: /\.blur\s*\(\s*\)/, name: "el.blur()", severity: "danger", errorCode: -32071, suggestion: "el.blur() without user interaction. Avoid in automation scripts." },
3808
+ { 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"]').` },
3809
+ { pattern: /\.reset\s*\(\s*\)/, name: "el.reset()", severity: "danger", errorCode: -32072, suggestion: "form.reset() without user action. Let the user clear fields manually." },
3810
+ { pattern: /\.select\s*\(\s*\)/, name: "el.select()", severity: "warn", errorCode: -32073, suggestion: "input.select() selects text without user interaction. Use page.click(selector) instead." },
3811
+ { 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." },
3812
+ { pattern: /\.showPopover\s*\(\s*\)/, name: "el.showPopover()", severity: "warn", errorCode: -32073, suggestion: "Popover.show() requires user gesture. Simulate a click on the popover trigger." },
3813
+ { pattern: /\.hidePopover\s*\(\s*\)/, name: "el.hidePopover()", severity: "warn", errorCode: -32073, suggestion: "Hiding popovers via CDP is detectable." },
3814
+ { pattern: /\.requestFullscreen\s*\(\s*\)/, name: "el.requestFullscreen()", severity: "danger", errorCode: -32074, suggestion: "Fullscreen requests require user gesture. Cannot be triggered by automation." },
3815
+ { pattern: /\.requestPointerLock\s*\(\s*\)/, name: "el.requestPointerLock()", severity: "danger", errorCode: -32074, suggestion: "Pointer lock requires user gesture. Blocked in automation." },
3816
+ { pattern: /\.setSelectionRange\s*\(/, name: "el.setSelectionRange()", severity: "warn", errorCode: -32073, suggestion: "Setting selection range without user interaction is suspicious." },
3817
+ { pattern: /\.setRangeText\s*\(/, name: "el.setRangeText()", severity: "info", errorCode: -32076, suggestion: "Range text replacement without user input is detectable." },
3818
+ { pattern: /\.showPicker\s*\(\s*\)/, name: "HTMLInputElement.showPicker()", severity: "info", errorCode: -32076, suggestion: "Date/color picker shown without click \u2014 detectable." },
3819
+ { pattern: /\.reportValidity\s*\(\s*\)/, name: "el.reportValidity()", severity: "info", errorCode: -32076, suggestion: "Validity reporting without form submission attempt." },
3820
+ // ── dispatchEvent with synthetic events (isTrusted=false) ──
3821
+ { 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." },
3822
+ { 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." },
3823
+ { 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." },
3824
+ { pattern: /dispatchEvent\s*\(\s*new\s+FocusEvent\s*\(/, name: "dispatchEvent(new FocusEvent)", severity: "warn", errorCode: -32078, suggestion: "Synthetic focus events bypass user interaction." },
3825
+ { 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()." },
3826
+ { 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." },
3827
+ { 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." },
3828
+ { pattern: /dispatchEvent\s*\(\s*new\s+TouchEvent\s*\(/, name: "dispatchEvent(new TouchEvent)", severity: "danger", errorCode: -32077, suggestion: "Synthetic touch events on mobile are detectable." },
3829
+ { 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." },
3830
+ { pattern: /dispatchEvent\s*\(\s*new\s+ClipboardEvent\s*\(/, name: "dispatchEvent(new ClipboardEvent)", severity: "warn", errorCode: -32078, suggestion: "Synthetic clipboard events are detectable." },
3831
+ { pattern: /dispatchEvent\s*\(\s*new\s+DragEvent\s*\(/, name: "dispatchEvent(new DragEvent)", severity: "warn", errorCode: -32078, suggestion: "Synthetic drag events bypass real user interaction." },
3832
+ { pattern: /dispatchEvent\s*\(\s*new\s+CompositionEvent\s*\(/, name: "dispatchEvent(new CompositionEvent)", severity: "info", errorCode: -32079, suggestion: "Synthetic IME composition events \u2014 detectable pattern." },
3833
+ { pattern: /dispatchEvent\s*\(\s*new\s+AnimationEvent\s*\(/, name: "dispatchEvent(new AnimationEvent)", severity: "info", errorCode: -32079, suggestion: "Forcing animation state transitions via fake events." },
3834
+ { pattern: /dispatchEvent\s*\(\s*new\s+TransitionEvent\s*\(/, name: "dispatchEvent(new TransitionEvent)", severity: "info", errorCode: -32079, suggestion: "Forcing CSS transition end via fake events." }
3835
+ ];
3836
+ var eventSimulationRule = {
3837
+ id: "event-simulation",
3838
+ name: "Event Simulation Detection (30+ patterns)",
3839
+ priority: 40,
3840
+ canHandle(ctx) {
3841
+ return ctx.method === "Runtime.evaluate" || ctx.method === "Runtime.callFunctionOn";
3842
+ },
3843
+ evaluate(ctx) {
3844
+ const userCode = extractUserCode(ctx);
3845
+ if (!userCode) return null;
3846
+ for (const p of EVENT_PATTERNS) {
3847
+ if (p.pattern.test(userCode)) {
3848
+ return {
3849
+ ruleId: "event-simulation",
3850
+ // danger 级硬拦(el.click 等 100% 暴露的模式);
3851
+ // warning 级放行+提示(dispatchEvent 在部分合法场景如 DataTransfer paste 使用)
3852
+ action: p.severity === "danger" ? "block" : "pass",
3853
+ severity: p.severity,
3854
+ reason: `Event simulation detected: "${p.name}". Synthetic events have isTrusted=false and are 100% detectable.`,
3855
+ suggestion: p.suggestion,
3856
+ errorCode: p.errorCode,
3857
+ errorMessage: p.severity === "danger" ? `[CDP Firewall] ${p.name} blocked \u2014 synthetic event (isTrusted=false)` : `[CDP Firewall] ${p.name} detected \u2014 event simulation`
3858
+ };
3859
+ }
3860
+ }
3861
+ return null;
3862
+ }
3863
+ };
3864
+
3865
+ // src/cdp-interceptor/rules/emulation-override.ts
3866
+ var OVERRIDE_PATTERNS = [
3867
+ // ── Emulation overrides ──────────────────────────────
3868
+ // NOTE: Emulation.setDeviceMetricsOverride is NOT included here because
3869
+ // Playwright calls it internally for every new page (viewport setup).
3870
+ // Blocking it would break page creation.
3871
+ { 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." },
3872
+ { 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." },
3873
+ { 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." },
3874
+ { method: "Emulation.setLocaleOverride", name: "Emulation.setLocaleOverride", severity: "warn", errorCode: -32081, suggestion: "Locale change without browser restart detectable via navigator.languages vs Accept-Language consistency." },
3875
+ { method: "Emulation.setTimezoneOverride", name: "Emulation.setTimezoneOverride", severity: "danger", errorCode: -32082, suggestion: "Timezone mismatch vs IP geolocation + Date() is 100% detectable." },
3876
+ { method: "Emulation.setDisabledImageTypes", name: "Emulation.setDisabledImageTypes", severity: "info", errorCode: -32083, suggestion: "Disabling image types prevents normal resource loading \u2014 visible to performance API." },
3877
+ { method: "Emulation.setScriptExecutionDisabled", name: "Emulation.setScriptExecutionDisabled", severity: "info", errorCode: -32083, suggestion: "Disabling JS mid-session kills page interactivity \u2014 immediately obvious." },
3878
+ { method: "Emulation.setCPUThrottlingRate", name: "Emulation.setCPUThrottlingRate", severity: "info", errorCode: -32083, suggestion: "CPU throttling creates unrealistic performance.now() profiles." },
3879
+ { 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." },
3880
+ // ── Network overrides ────────────────────────────────
3881
+ { method: "Network.setUserAgentOverride", name: "Network.setUserAgentOverride (HTTP layer)", severity: "danger", errorCode: -32080, suggestion: "HTTP User-Agent vs navigator.userAgent inconsistency = immediate detection." },
3882
+ { 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." },
3883
+ { method: "Network.emulateNetworkConditions", name: "Network.emulateNetworkConditions", severity: "warn", errorCode: -32081, suggestion: "Network throttling creates unrealistic load timing patterns." },
3884
+ { method: "Network.setCookie", name: "Network.setCookie", severity: "warn", errorCode: -32085, suggestion: "CDP-injected cookies are detectable via document.cookie vs Network.getCookies inconsistency." },
3885
+ { method: "Network.deleteCookies", name: "Network.deleteCookies", severity: "warn", errorCode: -32085, suggestion: "Cookie deletion via CDP bypasses HTTP cookie expiration \u2014 detectable." },
3886
+ // ── Security overrides ──────────────────────────────
3887
+ { method: "Security.setIgnoreCertificateErrors", name: "Security.setIgnoreCertificateErrors", severity: "info", errorCode: -32086, suggestion: "Ignoring certificate errors creates unusual TLS behavior visible at network level." },
3888
+ // ── Page overrides ──────────────────────────────────
3889
+ { method: "Page.setDownloadBehavior", name: "Page.setDownloadBehavior", severity: "info", errorCode: -32087, suggestion: "Bypassing download dialogs \u2014 detectable via download event flow." },
3890
+ { method: "Page.setWebLifecycleState", name: "Page.setWebLifecycleState", severity: "info", errorCode: -32087, suggestion: "Forcing page lifecycle transitions is unnatural." },
3891
+ // ── Storage / Permissions ───────────────────────────
3892
+ { method: "Storage.clearDataForOrigin", name: "Storage.clearDataForOrigin", severity: "info", errorCode: -32089, suggestion: "Clearing storage mid-session is unnatural for real users." },
3893
+ { 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." },
3894
+ { method: "Browser.resetPermissions", name: "Browser.resetPermissions", severity: "info", errorCode: -32089, suggestion: "Permission resets without user action are unnatural." }
3895
+ ];
3896
+ var emulationOverrideRule = {
3897
+ id: "emulation-override",
3898
+ name: "CDP Emulation / Override Detection (20+ methods)",
3899
+ priority: 60,
3900
+ canHandle(ctx) {
3901
+ for (const p of OVERRIDE_PATTERNS) {
3902
+ if (ctx.method === p.method) return true;
3903
+ }
3904
+ return false;
3905
+ },
3906
+ evaluate(ctx) {
3907
+ for (const p of OVERRIDE_PATTERNS) {
3908
+ if (ctx.method !== p.method) continue;
3909
+ return {
3910
+ ruleId: "emulation-override",
3911
+ action: "pass",
3912
+ severity: p.severity,
3913
+ reason: `CDP emulation/override detected: "${p.name}". This creates detectable inconsistencies between the JS environment and real browser state.`,
3914
+ suggestion: p.suggestion,
3915
+ errorCode: p.errorCode,
3916
+ errorMessage: `[CDP Firewall] ${p.name} blocked \u2014 creates detectable browser state inconsistency`
3917
+ };
3918
+ }
3919
+ return null;
3920
+ }
3921
+ };
3922
+
3923
+ // src/cdp-interceptor/rules/network-anomaly.ts
3924
+ var networkAnomalyRule = {
3925
+ id: "network-anomaly",
3926
+ name: "Network Anomaly Detection (8+ patterns)",
3927
+ priority: 70,
3928
+ canHandle(ctx) {
3929
+ const m = ctx.method;
3930
+ return m === "Network.setExtraHTTPHeaders" || m === "Network.clearBrowserCache" || m === "Network.clearBrowserCookies" || m === "Network.setBlockedURLs" || m === "Network.setBypassServiceWorker" || m === "Fetch.enable" || m === "Network.enable";
3931
+ },
3932
+ evaluate(ctx) {
3933
+ switch (ctx.method) {
3934
+ case "Network.setExtraHTTPHeaders": {
3935
+ const headers = ctx.params.headers;
3936
+ if (headers) {
3937
+ const headerStr = JSON.stringify(headers).toLowerCase();
3938
+ if (!headerStr.includes("sec-ch-ua")) {
3939
+ return {
3940
+ ruleId: "network-anomaly",
3941
+ action: "pass",
3942
+ severity: "warn",
3943
+ reason: "Network.setExtraHTTPHeaders called without Sec-CH-UA client hints \u2014 browser normally sends these.",
3944
+ suggestion: "Modern browsers send Sec-CH-UA headers automatically. Adding custom headers without them creates detectable inconsistency.",
3945
+ errorCode: -32110,
3946
+ errorMessage: "[CDP Firewall] Missing client hints in custom headers"
3947
+ };
3948
+ }
3949
+ }
3950
+ return null;
3951
+ }
3952
+ case "Network.clearBrowserCache": {
3953
+ return {
3954
+ ruleId: "network-anomaly",
3955
+ action: "pass",
3956
+ severity: "warn",
3957
+ reason: "Network.clearBrowserCache called \u2014 cache clearing mid-session is unnatural for real users.",
3958
+ suggestion: "Avoid cache clearing during sessions. Start with a fresh profile if needed.",
3959
+ errorCode: -32111,
3960
+ errorMessage: "[CDP Firewall] Cache clearing detected"
3961
+ };
3962
+ }
3963
+ case "Network.clearBrowserCookies": {
3964
+ return {
3965
+ ruleId: "network-anomaly",
3966
+ action: "pass",
3967
+ severity: "warn",
3968
+ reason: "Network.clearBrowserCookies called \u2014 wiping cookies mid-session is a scraper optimization.",
3969
+ suggestion: "Cookies should only be cleared via normal browser flow (expiration, user action).",
3970
+ errorCode: -32112,
3971
+ errorMessage: "[CDP Firewall] Cookie clearing detected"
3972
+ };
3973
+ }
3974
+ case "Network.setBlockedURLs": {
3975
+ return {
3976
+ ruleId: "network-anomaly",
3977
+ action: "pass",
3978
+ severity: "warn",
3979
+ reason: "Network.setBlockedURLs blocks resource loading \u2014 this changes the page behavior and is detectable.",
3980
+ suggestion: "Blocking images/fonts/etc creates measurable differences in performance and page rendering.",
3981
+ errorCode: -32113,
3982
+ errorMessage: "[CDP Firewall] URL blocking detected"
3983
+ };
3984
+ }
3985
+ case "Network.setBypassServiceWorker": {
3986
+ return {
3987
+ ruleId: "network-anomaly",
3988
+ action: "block",
3989
+ severity: "info",
3990
+ reason: "Network.setBypassServiceWorker called \u2014 bypassing service workers for content extraction.",
3991
+ suggestion: "Service worker bypass changes fetch behavior and is detectable server-side.",
3992
+ errorCode: -32114,
3993
+ errorMessage: "[CDP Firewall] Service worker bypass detected"
3994
+ };
3995
+ }
3996
+ case "Fetch.enable": {
3997
+ return {
3998
+ ruleId: "network-anomaly",
3999
+ action: "pass",
4000
+ severity: "warn",
4001
+ reason: "Fetch.enable intercepts all network requests \u2014 a man-in-the-middle approach used by scrapers.",
4002
+ suggestion: "Do not use Fetch domain for network interception if avoiding detection.",
4003
+ errorCode: -32115,
4004
+ errorMessage: "[CDP Firewall] Fetch interception detected"
4005
+ };
4006
+ }
4007
+ default:
4008
+ return null;
4009
+ }
4010
+ }
4011
+ };
4012
+
4013
+ // src/cdp-interceptor/rules/page-lifecycle.ts
4014
+ var STAT_KEY = "lifecycle-tracker";
4015
+ var pageLifecycleRule = {
4016
+ id: "page-lifecycle",
4017
+ name: "Page Lifecycle Anomaly Detection (10+ patterns)",
4018
+ priority: 80,
4019
+ canHandle(ctx) {
4020
+ const m = ctx.method;
4021
+ return m === "Page.navigate" || m === "Page.captureScreenshot" || m === "Page.printToPDF" || m === "Page.reload" || m === "Page.close" || m === "Runtime.evaluate" || m === "Runtime.callFunctionOn";
4022
+ },
4023
+ evaluate(ctx) {
4024
+ let state = ctx.sessionState.get(STAT_KEY);
4025
+ if (!state) {
4026
+ state = { navigations: [], screenshots: 0, printToPDF: false, evaluateCount: 0, lastNavTime: 0, lastEvalTime: 0 };
4027
+ ctx.sessionState.set(STAT_KEY, state);
4028
+ }
4029
+ const now = Date.now();
4030
+ switch (ctx.method) {
4031
+ case "Page.navigate": {
4032
+ state.navigations.push(now);
4033
+ if (state.navigations.length >= 2) {
4034
+ const prev = state.navigations[state.navigations.length - 2];
4035
+ const interval = now - prev;
4036
+ if (interval < 100) {
4037
+ return {
4038
+ ruleId: "page-lifecycle",
4039
+ action: "pass",
4040
+ severity: "warn",
4041
+ reason: `Multiple Page.navigate calls within ${interval}ms of each other \u2014 unnatural rapid navigation.`,
4042
+ suggestion: "Add proper waits between navigations: wait for page load before navigating again.",
4043
+ errorCode: -32100,
4044
+ errorMessage: "[CDP Firewall] Rapid navigation sequence detected"
4045
+ };
4046
+ }
4047
+ }
4048
+ state.lastNavTime = now;
4049
+ return null;
4050
+ }
4051
+ case "Page.captureScreenshot": {
4052
+ state.screenshots++;
4053
+ if (state.lastNavTime > 0 && now - state.lastNavTime < 500) {
4054
+ return {
4055
+ ruleId: "page-lifecycle",
4056
+ action: "pass",
4057
+ severity: "danger",
4058
+ reason: "Page.captureScreenshot called within 500ms of navigation \u2014 content extraction pattern.",
4059
+ suggestion: "Wait for the page to fully render before taking screenshots: wait for load/networkidle.",
4060
+ errorCode: -32101,
4061
+ errorMessage: "[CDP Firewall] Pre-render screenshot blocked \u2014 content extraction pattern"
4062
+ };
4063
+ }
4064
+ if (state.screenshots > 3 && state.navigations.length < 2) {
4065
+ return {
4066
+ ruleId: "page-lifecycle",
4067
+ action: "pass",
4068
+ severity: "warn",
4069
+ reason: "Multiple screenshots on a single page without navigation \u2014 suspicious extraction behavior.",
4070
+ suggestion: "Consider if all screenshots are necessary.",
4071
+ errorCode: -32102,
4072
+ errorMessage: "[CDP Firewall] Excessive screenshot detection"
4073
+ };
4074
+ }
4075
+ return null;
4076
+ }
4077
+ case "Page.printToPDF": {
4078
+ return {
4079
+ ruleId: "page-lifecycle",
4080
+ action: "pass",
4081
+ severity: "danger",
4082
+ reason: "Page.printToPDF called \u2014 this is a telltale scraper pattern that gives away automation intent.",
4083
+ suggestion: "Avoid PDF generation. If you must, add significant delays and user-like interaction first.",
4084
+ errorCode: -32103,
4085
+ errorMessage: "[CDP Firewall] printToPDF blocked \u2014 scraper intent detected"
4086
+ };
4087
+ }
4088
+ case "Page.reload": {
4089
+ if (state.lastNavTime > 0 && now - state.lastNavTime < 1e3) {
4090
+ return {
4091
+ ruleId: "page-lifecycle",
4092
+ action: "pass",
4093
+ severity: "warn",
4094
+ reason: "Page.reload called immediately after navigate \u2014 unnatural fast-reload pattern.",
4095
+ suggestion: "Introduce delays between navigation and reload to simulate human behavior.",
4096
+ errorCode: -32104,
4097
+ errorMessage: "[CDP Firewall] Rapid reload detected"
4098
+ };
4099
+ }
4100
+ return null;
4101
+ }
4102
+ case "Page.close": {
4103
+ if (state.navigations.length < 2) {
4104
+ return {
4105
+ ruleId: "page-lifecycle",
4106
+ action: "pass",
4107
+ severity: "info",
4108
+ reason: "Page.close called after minimal interaction \u2014 zombie pages common in automation.",
4109
+ suggestion: "Ensure meaningful interaction before closing pages.",
4110
+ errorCode: -32105,
4111
+ errorMessage: "[CDP Firewall] Page close after minimal interaction"
4112
+ };
4113
+ }
4114
+ return null;
4115
+ }
4116
+ case "Runtime.evaluate":
4117
+ case "Runtime.callFunctionOn": {
4118
+ state.evaluateCount++;
4119
+ if (state.evaluateCount > 50 && state.navigations.length === 0) {
4120
+ return {
4121
+ ruleId: "page-lifecycle",
4122
+ action: "pass",
4123
+ severity: "info",
4124
+ reason: "50+ evaluate calls without any Page.navigate \u2014 data extraction without real browsing.",
4125
+ suggestion: "Navigate to a real page first. Evaluate on about:blank is suspicious.",
4126
+ errorCode: -32106,
4127
+ errorMessage: "[CDP Firewall] Excessive evaluate without navigation"
4128
+ };
4129
+ }
4130
+ return null;
4131
+ }
4132
+ default:
4133
+ return null;
4134
+ }
4135
+ }
4136
+ };
4137
+
4138
+ // src/cdp-interceptor/rules-engine.ts
4139
+ var BUILTIN_RULES = [
4140
+ domMutationRule,
4141
+ automationSignalsRule,
4142
+ fingerprintingRule,
4143
+ eventSimulationRule,
4144
+ mouseTrajectoryRule,
4145
+ inputKeystrokeRule,
4146
+ emulationOverrideRule,
4147
+ networkAnomalyRule,
4148
+ pageLifecycleRule
4149
+ ];
4150
+ function createRuleEngine(customRules) {
4151
+ const rules = [...BUILTIN_RULES, ...customRules ?? []].sort((a, b) => a.priority - b.priority);
4152
+ const sessionStates = /* @__PURE__ */ new Map();
4153
+ function getSessionState(sessionId) {
4154
+ let state = sessionStates.get(sessionId);
4155
+ if (!state) {
4156
+ state = /* @__PURE__ */ new Map();
4157
+ sessionStates.set(sessionId, state);
4158
+ }
4159
+ return state;
4160
+ }
4161
+ return {
4162
+ start() {
4163
+ sessionStates.clear();
4164
+ },
4165
+ stop() {
4166
+ sessionStates.clear();
4167
+ },
4168
+ evaluate(ctx) {
4169
+ const fullCtx = {
4170
+ ...ctx,
4171
+ sessionState: getSessionState(ctx.sessionId)
4172
+ };
4173
+ for (const rule of rules) {
4174
+ if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
4175
+ const decision = rule.evaluate(fullCtx);
4176
+ if (!decision) continue;
4177
+ if (decision.action !== "pass") return decision;
4178
+ }
4179
+ return null;
4180
+ }
4181
+ };
4182
+ }
4183
+
4184
+ // src/cdp-driver/connection.ts
4185
+ var CDPConnection = class _CDPConnection extends EventEmitter4 {
3063
4186
  ws;
3064
4187
  nextId = 1;
4188
+ /** CDP Guard:全部出站命令过规则引擎(env XBROWSER_CDP_GUARD=off 关闭)。
4189
+ * 173 条规则 / 9 模块:合成事件 block、指纹暴露警告、自动化信号拦截。 */
4190
+ static __guard;
4191
+ get guard() {
4192
+ if (_CDPConnection.__guard === void 0) {
4193
+ if (process.env.XBROWSER_CDP_GUARD === "off") {
4194
+ _CDPConnection.__guard = null;
4195
+ } else {
4196
+ try {
4197
+ const g = createRuleEngine();
4198
+ g.start();
4199
+ _CDPConnection.__guard = g;
4200
+ } catch {
4201
+ _CDPConnection.__guard = null;
4202
+ }
4203
+ }
4204
+ }
4205
+ return _CDPConnection.__guard;
4206
+ }
3065
4207
  pending = /* @__PURE__ */ new Map();
3066
4208
  closed = false;
3067
4209
  closeReason = null;
@@ -3085,6 +4227,8 @@ var CDPConnection = class extends EventEmitter4 {
3085
4227
  * ping, the connection is considered dead and forcibly closed. */
3086
4228
  keepaliveTimer = null;
3087
4229
  pongTimer = null;
4230
+ /** 最近一次收到任何 WS 消息的时间——有数据流动即证明连接存活 */
4231
+ lastIncomingAt = Date.now();
3088
4232
  startKeepalive() {
3089
4233
  this.ws.on("pong", () => {
3090
4234
  if (this.pongTimer) {
@@ -3096,9 +4240,14 @@ var CDPConnection = class extends EventEmitter4 {
3096
4240
  if (this.ws.readyState === WebSocket.OPEN) {
3097
4241
  if (!this.pongTimer) {
3098
4242
  this.pongTimer = setTimeout(() => {
4243
+ const recentlyActive = Date.now() - this.lastIncomingAt < 3e4;
4244
+ if (recentlyActive) {
4245
+ this.pongTimer = null;
4246
+ return;
4247
+ }
3099
4248
  if (!this.closed) {
3100
4249
  this.closed = true;
3101
- this.closeReason = "keepalive timeout (no pong in 10s)";
4250
+ this.closeReason = "keepalive timeout (no pong and idle >30s)";
3102
4251
  try {
3103
4252
  this.ws.terminate();
3104
4253
  } catch {
@@ -3110,7 +4259,7 @@ var CDPConnection = class extends EventEmitter4 {
3110
4259
  this.pending.clear();
3111
4260
  this.emit("disconnect");
3112
4261
  }
3113
- }, 1e4);
4262
+ }, 6e4);
3114
4263
  }
3115
4264
  this.ws.ping?.();
3116
4265
  } else if (this.closed) {
@@ -3148,10 +4297,23 @@ var CDPConnection = class extends EventEmitter4 {
3148
4297
  * @param method — CDP domain.method (e.g. "Page.navigate")
3149
4298
  * @param params — method parameters
3150
4299
  * @param sessionId — optional flat session ID for sub-targets
3151
- * @param timeoutMs — response timeout (default: 30s)
4300
+ * @param timeoutMs — response timeout (default: 30s;重 SPA 加载期间主线程忙,
4301
+ * evaluate 可排队 >30s——Runtime.evaluate 单独放宽到 90s)
3152
4302
  * @returns the `result` field from the CDP response
3153
4303
  */
3154
- async send(method, params, sessionId, timeoutMs = 3e4) {
4304
+ async send(method, params, sessionId, timeoutMs) {
4305
+ const effectiveTimeout = timeoutMs ?? (method === "Runtime.evaluate" ? 9e4 : 3e4);
4306
+ if (this.guard) {
4307
+ const decision = this.guard.evaluate({
4308
+ method,
4309
+ params: params ?? {},
4310
+ sessionId: sessionId ?? this.defaultSessionId ?? "",
4311
+ direction: "client\u2192browser"
4312
+ });
4313
+ if (decision && decision.action === "block") {
4314
+ throw new Error(`[CDP-Guard] ${decision.reason}${decision.suggestion ? " | \u66FF\u4EE3: " + decision.suggestion : ""} [${decision.ruleId}]`);
4315
+ }
4316
+ }
3155
4317
  if (this.closed) {
3156
4318
  throw new Error(`CDP connection closed: ${this.closeReason ?? "unknown"}`);
3157
4319
  }
@@ -3166,8 +4328,8 @@ var CDPConnection = class extends EventEmitter4 {
3166
4328
  return new Promise((resolve, reject) => {
3167
4329
  const timeout = setTimeout(() => {
3168
4330
  this.pending.delete(id);
3169
- reject(new Error(`CDP timeout: ${method} (${timeoutMs}ms)`));
3170
- }, timeoutMs);
4331
+ reject(new Error(`CDP timeout: ${method} (${effectiveTimeout}ms)`));
4332
+ }, effectiveTimeout);
3171
4333
  this.pending.set(id, {
3172
4334
  resolve: (v) => {
3173
4335
  clearTimeout(timeout);
@@ -3250,6 +4412,7 @@ var CDPConnection = class extends EventEmitter4 {
3250
4412
  // ── Private ─────────────────────────────────────────────────
3251
4413
  bindWebSocket() {
3252
4414
  this.ws.on("message", (raw) => {
4415
+ this.lastIncomingAt = Date.now();
3253
4416
  let msg;
3254
4417
  try {
3255
4418
  msg = JSON.parse(raw.toString());
@@ -3404,6 +4567,7 @@ export {
3404
4567
  XBCDPSessionImpl,
3405
4568
  XBContextImpl,
3406
4569
  XBBrowserImpl,
4570
+ createRuleEngine,
3407
4571
  CDPConnection,
3408
4572
  CDPProtocolError,
3409
4573
  waitForNetworkIdle,