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