@xbrowser/cli 1.20.0 → 1.22.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/README.md +1 -0
  2. package/dist/{browser-Y6B3NS4Q.js → browser-BVRFSUXU.js} +3 -2
  3. package/dist/{browser-NVC7MTML.js → browser-DSYUAE7H.js} +5 -5
  4. package/dist/{browser-PBBC7RAV.js → browser-Q67BJTI2.js} +6 -4
  5. package/dist/{cdp-driver-QYFA4QTP.js → cdp-driver-DC7EIUG5.js} +4 -3
  6. package/dist/{cdp-driver-Z2PLAO42.js → cdp-driver-T7D6H2RW.js} +368 -510
  7. package/dist/{cdp-driver-73F5CVH2.js → cdp-driver-WWO2UZDR.js} +4 -3
  8. package/dist/{chunk-76EKW7YJ.js → chunk-2Q3GQRUP.js} +3 -3
  9. package/dist/{chunk-UYEJ66VX.js → chunk-4OU37CXP.js} +387 -540
  10. package/dist/{chunk-H2A5JUK5.js → chunk-75DNUI6M.js} +9 -0
  11. package/dist/{chunk-FDU5BCPV.js → chunk-7OP2ISEY.js} +378 -540
  12. package/dist/{chunk-3FWLW7FS.js → chunk-A7NEA4PA.js} +39 -1
  13. package/dist/chunk-GYB5BOSP.js +602 -0
  14. package/dist/{chunk-T2KUVO4H.js → chunk-IFKJO2UR.js} +393 -546
  15. package/dist/{chunk-NODRQGOK.js → chunk-IR6C24P7.js} +97 -0
  16. package/dist/{chunk-3KZ34AUC.js → chunk-MYH6FIBZ.js} +2 -1
  17. package/dist/{chunk-75TLPVVZ.js → chunk-T4WTKBWI.js} +2 -2
  18. package/dist/{chunk-HBHOKZPN.js → chunk-V6KGBU5J.js} +97 -0
  19. package/dist/{chunk-IWVG4XYZ.js → chunk-VCVDILH6.js} +2 -1
  20. package/dist/{chunk-A6LPGFAL.js → chunk-WYETQ5C7.js} +1 -1
  21. package/dist/cli.js +25 -13
  22. package/dist/daemon-main.js +20 -14
  23. package/dist/index.d.ts +136 -1
  24. package/dist/index.js +29 -18
  25. package/dist/keep-awake-M4KJS4B4.js +29 -0
  26. package/dist/{launcher-44STYRJC.js → launcher-IK2FKW6T.js} +1 -1
  27. package/dist/{launcher-EXJHHAUL.js → launcher-LUOMMGZC.js} +1 -1
  28. package/dist/{proxy-LUR4U5YF.js → proxy-NKCYE76M.js} +2 -2
  29. package/dist/{session-recorder-SLDBENVF.js → session-recorder-563ISSJK.js} +1 -1
  30. package/dist/{session-recorder-3BEVWHOK.js → session-recorder-GEZVQBKW.js} +1 -1
  31. package/dist/session-replayer-XM5L7LFD.js +927 -0
  32. package/dist/stealth-2AA2FSNN.js +29 -0
  33. package/dist/stealth-JOXGV34D.js +29 -0
  34. package/package.json +2 -1
  35. package/dist/session-replayer-SBYJXQZZ.js +0 -413
@@ -1,11 +1,19 @@
1
1
  import {
2
2
  queryAllJS,
3
3
  queryJS
4
- } from "./chunk-3FWLW7FS.js";
4
+ } from "./chunk-A7NEA4PA.js";
5
+ import {
6
+ DEFAULT_STEALTH_CONFIG,
7
+ bezierTrajectory,
8
+ buildStealthInitScript,
9
+ landingOffset,
10
+ rand,
11
+ typingDelay
12
+ } from "./chunk-GYB5BOSP.js";
5
13
  import {
6
14
  connectToCDP,
7
15
  launchChrome
8
- } from "./chunk-3KZ34AUC.js";
16
+ } from "./chunk-MYH6FIBZ.js";
9
17
  import {
10
18
  errMsg
11
19
  } from "./chunk-GDKLH7ZY.js";
@@ -15,6 +23,9 @@ import {
15
23
 
16
24
  // src/cdp-driver/browser.ts
17
25
  import { EventEmitter as EventEmitter3 } from "events";
26
+ import { mkdirSync } from "fs";
27
+ import { join } from "path";
28
+ import { tmpdir } from "os";
18
29
 
19
30
  // src/cdp-driver/context.ts
20
31
  import { EventEmitter as EventEmitter2 } from "events";
@@ -22,496 +33,6 @@ import { EventEmitter as EventEmitter2 } from "events";
22
33
  // src/cdp-driver/page.ts
23
34
  import { EventEmitter } from "events";
24
35
 
25
- // src/cdp-driver/stealth.ts
26
- var DEFAULT_STEALTH_CONFIG = {
27
- bezierCurvature: [0.35, 0.6],
28
- noiseAmplitude: 5.5,
29
- overshootRange: [6, 14],
30
- aimPause: [80, 280],
31
- pressDuration: [60, 140],
32
- releaseDrift: [0.8, 2.5],
33
- landingOffsetSmall: [0.3, 2.5],
34
- landingOffsetLarge: [1.5, 7],
35
- smallElementThreshold: 30,
36
- typingRhythm: {
37
- fastProb: 0.22,
38
- fastRange: [25, 60],
39
- normalRange: [50, 350],
40
- pauseProb: 0.18,
41
- pauseRange: [400, 1200]
42
- },
43
- keyPressDuration: [50, 110],
44
- typoProbability: 0.06,
45
- wheelPeak: 180,
46
- wheelDecayRate: 0.4
47
- };
48
- function rand(min, max) {
49
- return min + Math.random() * (max - min);
50
- }
51
- function sleep(ms) {
52
- return new Promise((resolve) => setTimeout(resolve, ms));
53
- }
54
- function cosineEase(t) {
55
- return 0.5 - 0.5 * Math.cos(Math.PI * t);
56
- }
57
- function bezierTrajectory(x0, y0, x1, y1, config = DEFAULT_STEALTH_CONFIG) {
58
- const dist = Math.hypot(x1 - x0, y1 - y0);
59
- const n = Math.max(10, Math.min(28, Math.round(dist / 15)));
60
- const shortMove = dist < 120;
61
- const curvature = shortMove ? rand(2, 6) : Math.max(dist * rand(...config.bezierCurvature), rand(18, 35));
62
- const dir = Math.random() < 0.5 ? 1 : -1;
63
- const d = dist || 1;
64
- const dx = x1 - x0, dy = y1 - y0;
65
- const c1x = x0 + dx * 0.3 - dy / d * curvature * 0.5 * dir;
66
- const c1y = y0 + dy * 0.3 + dx / d * curvature * 0.5 * dir;
67
- const c2x = x0 + dx * 0.7 - dy / d * curvature * 0.8 * dir;
68
- const c2y = y0 + dy * 0.7 + dx / d * curvature * 0.8 * dir;
69
- const points = [];
70
- for (let i = 1; i <= n; i++) {
71
- const t = cosineEase(i / n);
72
- const mt = 1 - t;
73
- let px = mt ** 3 * x0 + 3 * mt ** 2 * t * c1x + 3 * mt * t ** 2 * c2x + t ** 3 * x1;
74
- let py = mt ** 3 * y0 + 3 * mt ** 2 * t * c1y + 3 * mt * t ** 2 * c2y + t ** 3 * y1;
75
- const amp = shortMove ? Math.min(2, config.noiseAmplitude) : config.noiseAmplitude;
76
- px += rand(-amp, amp);
77
- py += rand(-amp, amp);
78
- points.push({ x: px, y: py, delay: rand(9, 16) });
79
- }
80
- if (!shortMove) {
81
- const over = rand(...config.overshootRange);
82
- const ox = x1 + dx / d * over + rand(-2, 2);
83
- const oy = y1 + dy / d * over + rand(-2, 2);
84
- points.push({ x: ox, y: oy, delay: rand(14, 30) });
85
- points.push({
86
- x: x1 + dx / d * over * 0.4,
87
- y: y1 + dy / d * over * 0.4,
88
- delay: rand(14, 30)
89
- });
90
- }
91
- points.push({ x: x1 + rand(-1, 1), y: y1 + rand(-1, 1), delay: rand(14, 30) });
92
- return points;
93
- }
94
- function landingOffset(width, height, config = DEFAULT_STEALTH_CONFIG) {
95
- const isSmall = Math.min(width, height) < config.smallElementThreshold;
96
- const range = isSmall ? config.landingOffsetSmall : config.landingOffsetLarge;
97
- const dx = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
98
- const dy = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
99
- return { dx, dy };
100
- }
101
- function typingDelay(config = DEFAULT_STEALTH_CONFIG) {
102
- const roll = Math.random();
103
- const r = config.typingRhythm;
104
- if (roll < r.pauseProb) return rand(...r.pauseRange);
105
- if (roll < r.pauseProb + r.fastProb) return rand(...r.fastRange);
106
- return rand(...r.normalRange);
107
- }
108
- function wheelDelta(step, config = DEFAULT_STEALTH_CONFIG) {
109
- return Math.round(
110
- config.wheelPeak * Math.exp(-step * config.wheelDecayRate) * rand(0.85, 1.15)
111
- );
112
- }
113
- var KEY_MAP = {};
114
- for (let i = 97; i <= 122; i++) {
115
- const ch = String.fromCharCode(i);
116
- KEY_MAP[ch] = { key: ch, code: "Key" + ch.toUpperCase(), vk: i - 32 };
117
- }
118
- for (let i = 65; i <= 90; i++) {
119
- const ch = String.fromCharCode(i);
120
- KEY_MAP[ch] = { key: ch, code: "Key" + ch, vk: i, shift: true };
121
- }
122
- for (let i = 48; i <= 57; i++) {
123
- const ch = String.fromCharCode(i);
124
- KEY_MAP[ch] = { key: ch, code: "Digit" + ch, vk: i };
125
- }
126
- Object.assign(KEY_MAP, {
127
- " ": { key: " ", code: "Space", vk: 32 },
128
- ".": { key: ".", code: "Period", vk: 190 },
129
- "-": { key: "-", code: "Minus", vk: 189 },
130
- "@": { key: "@", code: "Digit2", vk: 50, shift: true },
131
- "_": { key: "_", code: "Minus", vk: 189, shift: true }
132
- });
133
- function buildStealthInitScript() {
134
- return [
135
- "(function(){",
136
- ' window.__xbStealthVer="57";',
137
- // 1. AEL event proxy
138
- " var o=EventTarget.prototype.addEventListener;",
139
- " var fc=new InputDeviceCapabilities({firesTouchEvents:false});",
140
- " var _ael=function(t,f){",
141
- " var op=arguments[2];",
142
- ' if(typeof f!=="function")return o.call(this,t,f,op);',
143
- " var w=function(e){",
144
- " if(!e)return f.call(this,e);",
145
- " return f.call(this,new Proxy(e,{get:function(k,p){",
146
- ' if(p==="sourceCapabilities")return fc;',
147
- // S124 修正(d67 攻防):恒 true 是"过度伪装"——站点自己的合成事件
148
- // 也变 true → 直接判定浏览器被篡改(比检测自动化更严重的指纹暴露)。
149
- // 正确策略:透传原始值(CDP Input 事件本来就是 true,JS 合成本来是 false)
150
- // + paste 定向伪装(合成的 paste 在真实场景都是 trusted 的键盘操作产物)
151
- ' if(p==="isTrusted"){',
152
- ' var orig=Reflect.get(k,"isTrusted");',
153
- " if(orig===true)return true;",
154
- ' if(k.type==="paste")return true;',
155
- " return orig;",
156
- " }",
157
- ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])){',
158
- " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;",
159
- " return k[p]+_f;",
160
- " }",
161
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
162
- " }}));",
163
- " };",
164
- " return o.call(this,t,w,op);",
165
- " };",
166
- " EventTarget.prototype.addEventListener=_ael;",
167
- // window.event isTrusted 伪装(S123):AEL 参数包装收不到 window.event
168
- // (它是原始 Event 对象的隐式引用)。定义 getter 拦截读取。
169
- " try{",
170
- ' var _weDesc=Object.getOwnPropertyDescriptor(Window.prototype,"event");',
171
- " if(_weDesc&&_weDesc.get){",
172
- " var _origWeGet=_weDesc.get;",
173
- ' Object.defineProperty(Window.prototype,"event",{',
174
- " configurable:true,",
175
- " get:function(){",
176
- " var ev=_origWeGet.call(this);",
177
- " if(!ev)return ev;",
178
- " return new Proxy(ev,{get:function(k,p){",
179
- ' if(p==="isTrusted"){',
180
- ' var orig=Reflect.get(k,"isTrusted");',
181
- " if(orig===true)return true;",
182
- ' if(k.type==="paste")return true;',
183
- " return orig;",
184
- " }",
185
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
186
- " }});",
187
- " }",
188
- " });",
189
- " }",
190
- " }catch(e){}",
191
- // 2. Screen override (prototype-level, not instance-level)
192
- " var _gw=function(){return 1728};",
193
- " var _gh=function(){return 1117};",
194
- " var _gah=function(){return 1092};",
195
- ' Object.defineProperty(Screen.prototype,"width",{get:_gw,configurable:true});',
196
- ' Object.defineProperty(Screen.prototype,"height",{get:_gh,configurable:true});',
197
- ' Object.defineProperty(Screen.prototype,"availWidth",{get:_gw,configurable:true});',
198
- ' Object.defineProperty(Screen.prototype,"availHeight",{get:_gah,configurable:true});',
199
- // S174: UA Headless 标记清洗——headless launch 的 UA 含 HeadlessChrome/xxx
200
- // (最高频检测面),同步清洗 userAgent/appVersion/userAgentData(brands+高熵值)。
201
- // 原型+实例双层覆写(S172 模式)。
202
- " try{",
203
- ' var fixUA=function(ua){return String(ua).replace("HeadlessChrome","Chrome");};',
204
- ' var fixBrands=function(list){return (list||[]).map(function(b){return (b.brand&&b.brand.indexOf("Headless")!==-1)?Object.assign({},b,{brand:b.brand.replace("HeadlessChrome","Chrome")}):b;});};',
205
- ' var _nuad=Object.getOwnPropertyDescriptor(Navigator.prototype,"userAgentData");',
206
- " var wrapUAD=function(uad){",
207
- " if(!uad||uad.__xbUA)return uad;",
208
- " try{",
209
- ' Object.defineProperty(uad,"brands",{get:function(){return fixBrands(_nuad.get.call(navigator).brands);},configurable:true});',
210
- " var _ghev=uad.getHighEntropyValues.bind(uad);",
211
- " uad.getHighEntropyValues=function(hints){return _ghev(hints).then(function(v){",
212
- ' var o={};for(var k in v){o[k]=(typeof v[k]==="string")?fixUA(v[k]):(Array.isArray(v[k])?fixBrands(v[k]):v[k]);}',
213
- " return o;});};",
214
- " uad.__xbUA=true;",
215
- " }catch(e){}",
216
- " return uad;",
217
- " };",
218
- ' var _nua=Object.getOwnPropertyDescriptor(Navigator.prototype,"userAgent");',
219
- " if(_nua&&_nua.get){",
220
- " var _nuag=function(){return fixUA(_nua.get.call(this));};",
221
- ' _nuag.toString=function(){return "function get userAgent() { [native code] }";};',
222
- ' Object.defineProperty(Navigator.prototype,"userAgent",{get:_nuag,configurable:true});',
223
- " }",
224
- ' Object.defineProperty(navigator,"userAgent",{get:function(){return fixUA(_nua?_nua.get.call(this):"");},configurable:true});',
225
- " if(_nuad&&_nuad.get){",
226
- " var _nuadg=function(){return wrapUAD(_nuad.get.call(this));};",
227
- ' _nuadg.toString=function(){return "function get userAgentData() { [native code] }";};',
228
- ' Object.defineProperty(Navigator.prototype,"userAgentData",{get:_nuadg,configurable:true});',
229
- " }",
230
- " }catch(e){}",
231
- // hasFocus 与 visibilityState 联动(d29):恒 true 在 hidden 标签下暴露
232
- // —— 真实浏览器失焦/后台时 hasFocus=false
233
- // S172: 原型层覆写——实例赋值可被 Document.prototype.hasFocus.call(document) 逃逸
234
- ' Document.prototype.hasFocus=function(){return document.visibilityState==="visible";};',
235
- // 4. Canvas/WebGL fingerprint: per-session stable noise (d20).
236
- // Headless software raster differs subtly from Chrome GPU raster —
237
- // toDataURL hashes fingerprint the rasterizer. Inject a stable
238
- // (per-page-load) subpixel shift into fillText so hashes look like a
239
- // distinct-but-consistent real GPU, and hide the HEADLESS tell in
240
- // WebGL renderer strings.
241
- " var _seed=Math.floor(Math.random()*2147483647);",
242
- " var _prng=function(){_seed=(_seed*48271)%2147483647;return _seed/2147483647;};",
243
- " var _dx=(_prng()*0.4-0.2).toFixed(3)*1, _dy=(_prng()*0.4-0.2).toFixed(3)*1;",
244
- " var _fillText=CanvasRenderingContext2D.prototype.fillText;",
245
- " CanvasRenderingContext2D.prototype.fillText=function(t,x,y,m){",
246
- " return _fillText.call(this,t,x+_dx,y+_dy,m);",
247
- " };",
248
- " var _toDataURL=HTMLCanvasElement.prototype.toDataURL;",
249
- " HTMLCanvasElement.prototype.toDataURL=function(){",
250
- ' var ctx=this.getContext("2d");',
251
- " if(ctx){var d=ctx.getImageData(0,0,Math.min(this.width,2),Math.min(this.height,2));",
252
- " for(var i=0;i<d.data.length;i+=4){if(d.data[i+3]>0){d.data[i]^=1;break;}}",
253
- " ctx.putImageData(d,0,0);}",
254
- " return _toDataURL.apply(this,arguments);",
255
- " };",
256
- " try{",
257
- " var _gl=HTMLCanvasElement.prototype.getContext;",
258
- " HTMLCanvasElement.prototype.getContext=function(t,o){",
259
- " var c=_gl.call(this,t,o);",
260
- ' if(c&&(t==="webgl"||t==="experimental-webgl")&&c.getParameter){',
261
- " var _gp=c.getParameter.bind(c);",
262
- " c.getParameter=function(p){",
263
- " var v=_gp(p);",
264
- ' if(typeof v==="string"&&/SwiftShader|Software|Rasterizer|Headless/i.test(v))',
265
- ' return "ANGLE (Apple, ANGLE Metal Renderer: Apple M2 Max, Unspecified Version)";',
266
- " return v;};}",
267
- " return c;};",
268
- " }catch(e){}",
269
- // 5. AudioContext fingerprint: per-load stable micro-noise on channel
270
- // data (d21). DSP sum differences between headless software audio and
271
- // real hardware audio are a classic fingerprint — add ±1e-7 level
272
- // noise (inaudible, changes the sum hash).
273
- " try{",
274
- " var _gcd=AudioBuffer.prototype.getChannelData;",
275
- " AudioBuffer.prototype.getChannelData=function(ch){",
276
- " var d=_gcd.call(this,ch);",
277
- ' var key="__xb_audio_"+ch;',
278
- " if(!this[key]){",
279
- " this[key]=true;",
280
- " for(var i=0;i<d.length;i+=997){d[i]=d[i]+(_prng()-0.5)*2e-7;}",
281
- " }",
282
- " return d;",
283
- " };",
284
- " var _gffd=AnalyserNode.prototype.getFloatFrequencyData;",
285
- " AnalyserNode.prototype.getFloatFrequencyData=function(arr){",
286
- " _gffd.call(this,arr);",
287
- " for(var i=0;i<arr.length;i+=31){arr[i]=arr[i]+(_prng()-0.5)*0.01;}",
288
- " };",
289
- " var _gfbd=AnalyserNode.prototype.getByteFrequencyData;",
290
- " AnalyserNode.prototype.getByteFrequencyData=function(arr){",
291
- " _gfbd.call(this,arr);",
292
- " for(var i=0;i<arr.length;i+=31){arr[i]=(arr[i]+((_prng()*3)|0))&255;}",
293
- " };",
294
- " }catch(e){}",
295
- // 3b. Font metrics + speechSynthesis + battery (d22): headless tells
296
- " try{",
297
- ' var _tmw=Object.getOwnPropertyDescriptor(TextMetrics.prototype,"width");',
298
- " if(_tmw&&_tmw.get){",
299
- " // S172: \u539F\u578B\u5C42\u8986\u5199\u2014\u2014\u5B9E\u4F8B(m)\u8986\u5199\u53EF\u88AB TextMetrics.prototype.width getter \u9003\u9038",
300
- ' Object.defineProperty(TextMetrics.prototype,"width",{get:function(){return _tmw.get.call(this)+_dx*0.01;},configurable:true});',
301
- " }",
302
- " }catch(e){}",
303
- " try{",
304
- ' var _fakeVoices=["Alex","Daniel","Karen","Moira","Ralph","Samantha","Ting-Ting","Mei-Jia","Sinji","Yunda"];',
305
- // S172: 原型层覆写——实例赋值可被 SpeechSynthesis.prototype.getVoices.call() 逃逸
306
- " var _sv=SpeechSynthesis.prototype.getVoices;",
307
- " SpeechSynthesis.prototype.getVoices=function(){",
308
- " var real=_sv.call(this);",
309
- " if(real&&real.length>50)return real;",
310
- // 注意阈值从 0 改 50:iframe 原生约 10 个 —— 原阈值下 iframe 返回原生 10 个
311
- // 而不是伪装 180(d33 暴露)。>50 = 主文档伪装列表已生效,其余返回伪装。
312
- ' 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};});',
313
- " };",
314
- // d33 修复:iframe 的 speechSynthesis 是独立实例(主文档 hook 不可达)——
315
- // 轮询同源 iframe,对其 contentWindow 的原型同样 patch(S172: 原型层,防逃逸)
316
- " try{",
317
- " var _piv=function(){",
318
- ' var frs=document.querySelectorAll("iframe");',
319
- " for(var i=0;i<frs.length;i++){try{",
320
- " var cw=frs[i].contentWindow;",
321
- " if(!cw||!cw.speechSynthesis||cw.speechSynthesis.__xbP)continue;",
322
- " cw.speechSynthesis.__xbP=true;",
323
- " var _sv2=cw.SpeechSynthesis.prototype.getVoices;",
324
- " cw.SpeechSynthesis.prototype.getVoices=function(){var r=_sv2.call(this);if(r&&r.length>50)return r;",
325
- ' 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};});};',
326
- " }catch(e2){}}",
327
- " };",
328
- " setInterval(_piv,2000);",
329
- " var _mo=new MutationObserver(function(muts){",
330
- " for(var k=0;k<muts.length;k++){var ns=muts[k].addedNodes;",
331
- ' for(var q=0;q<ns.length;q++){if(ns[q].tagName==="IFRAME")setTimeout(_piv,20);}}',
332
- " });",
333
- " _mo.observe(document.documentElement,{childList:true,subtree:true});",
334
- " }catch(e){}",
335
- " }catch(e){}",
336
- " try{",
337
- " var _gb=navigator.getBattery.bind(navigator);",
338
- " navigator.getBattery=function(){",
339
- " return _gb().then(function(b){",
340
- ' Object.defineProperty(b,"charging",{get:function(){return true;},configurable:true});',
341
- " return b;});",
342
- " };",
343
- " }catch(e){}",
344
- // 3c. WebRTC local IP leak guard (d23): headless STUN candidates can
345
- // expose host IPs; mDNS-only candidates are the modern Chrome default.
346
- " try{",
347
- " var _oc=RTCPeerConnection.prototype.createOffer;",
348
- " RTCPeerConnection.prototype.createOffer=function(){",
349
- " var p=_oc.apply(this,arguments);",
350
- " var self=this;",
351
- " return p.then(function(offer){",
352
- ' offer.sdp=offer.sdp.split(String.fromCharCode(10)).filter(function(l){return l.indexOf("typ host")<0}).join(String.fromCharCode(10));',
353
- " return offer;});",
354
- " };",
355
- " }catch(e){}",
356
- // 3d-2. performance.now precision clamp (d34): full-precision timestamps
357
- // (11 decimals) differ from site-isolation-clamped real Chrome (~100μs).
358
- " try{",
359
- " var _pn=Performance.prototype.now;",
360
- " // S172: \u539F\u578B\u5C42\u8986\u5199\u2014\u2014\u5B9E\u4F8B\u8D4B\u503C\u53EF\u88AB Performance.prototype.now.call(performance) \u9003\u9038",
361
- " Performance.prototype.now=function(){return Math.round(_pn.call(this)*10)/10;};",
362
- ' var _pto=Object.getOwnPropertyDescriptor(Performance.prototype,"timeOrigin");',
363
- " if(_pto&&_pto.get){",
364
- " // S173: timeOrigin \u771F\u4F2A\u88C5\u2014\u2014\u5360\u4F4D\u5C42\uFF08\u8FD4\u56DE\u771F\u503C\uFF09\u5347\u7EA7\u4E3A\u4F1A\u8BDD\u7EA7\u968F\u673A\u504F\u79FB\u3002",
365
- " // \u9632 cross-page \u5BFC\u822A\u65F6\u523B\u5173\u8054\uFF1A\u4E0D\u540C\u7AD9\u70B9\u7528 timeOrigin \u7CBE\u786E\u5BF9\u9F50\u7528\u6237\u884C\u4E3A\u6863\u6848\u3002",
366
- " // \u504F\u79FB\u7531\u672C\u9875 _seed \u6D3E\u751F\uFF08\u9875\u5185\u81EA\u6D3D\uFF0Cnow()+\u504F\u79FB\u4E00\u81F4\uFF09\uFF0C\u8DE8\u9875\u968F\u673A\uFF08\u4E0D\u53EF\u5173\u8054\uFF09\u3002",
367
- " var _toff=Math.floor((_seed/2147483647)*600000-300000);",
368
- " var _tog=function(){return _pto.get.call(performance)+_toff;};",
369
- ' _tog.toString=function(){return "function get timeOrigin() { [native code] }";};',
370
- " // S172 \u5BA1\u8BA1\uFF1A\u5B9E\u4F8B\u8986\u5199\u53EF\u88AB\u539F\u578B getter \u9003\u9038\u2014\u2014\u539F\u578B\u5C42\u8986\u5199",
371
- ' Object.defineProperty(Performance.prototype,"timeOrigin",{get:_tog,configurable:true});',
372
- ' Object.defineProperty(performance,"timeOrigin",{get:_tog,configurable:true});',
373
- " }",
374
- " }catch(e){}",
375
- // 3f. getCoalescedEvents 合成(d47):真实鼠标 125Hz 采样被浏览器按帧合并,
376
- // 快速移动时 pointermove.getCoalescedEvents() 返回 2~6 个事件(群内
377
- // ≈8ms);CDP Input 逐事件派发不走合并管线,coalesced>1 恒为 0(结构性
378
- // 暴露,间隔模拟救不了——实测 Chrome 帧对齐时 CDP 连发事件被直接丢弃
379
- // 而非合并)。按 125Hz 物理插值合成 coalesced 群:期望样本数 = dt/8ms-1,
380
- // 合成事件用真 PointerEvent 构造 + 实例级 isTrusted/timeStamp 遮蔽。
381
- " try{",
382
- " if(window.PointerEvent&&PointerEvent.prototype.getCoalescedEvents){",
383
- " var _gce=PointerEvent.prototype.getCoalescedEvents;",
384
- " var _lm=null;",
385
- " var _gceH=function(){",
386
- " var list=_gce.call(this);",
387
- ' if(this.type!=="pointermove"||!this.isTrusted)return list;',
388
- " var cur={x:this.clientX,y:this.clientY,ts:this.timeStamp};",
389
- " var out=null;",
390
- " if((!list||list.length<2)&&_lm){",
391
- " var dt=cur.ts-_lm.ts,dx=cur.x-_lm.x,dy=cur.y-_lm.y;",
392
- // dt 长(帧丢弃后)不代表群覆盖整个 dt —— 真实 coalesced 群只覆盖
393
- // 最后一帧窗口(≤16.7ms,群内 ≈8ms=125Hz)。合成群从自身往回推 8ms
394
- // 链,位移取末端占比(span/dt,dt 远大于 span 时位移趋零=丢弃后实况)。
395
- " var expN=Math.floor(dt/8)-1;",
396
- // dt<12ms(不足一帧+采样周期)时真实浏览器不会产生合并群 ——
397
- // 单采样帧 coalesced=1,强行合成会出现 ~2ms 的超物理群内间隔。
398
- " if(expN>0&&dt>=12&&Math.random()>0.15){",
399
- " var n=Math.min(4,expN+(Math.random()<0.3?1:0));",
400
- " var span=Math.min(dt,n*8.3);",
401
- " var frac=Math.min(1,span/Math.max(dt,1));",
402
- " out=[];",
403
- " for(var i=1;i<=n;i++){",
404
- // k=距自身的步数(含自身共 n+1 个事件,相邻恒 ≈8.3ms=125Hz 周期)
405
- " var k=n+1-i;",
406
- ' var ev=new PointerEvent("pointermove",{',
407
- ' pointerId:this.pointerId,pointerType:"mouse",isPrimary:this.isPrimary,',
408
- " clientX:cur.x-dx*frac*(k/(n+1))+(Math.random()-0.5)*1.5,",
409
- " clientY:cur.y-dy*frac*(k/(n+1))+(Math.random()-0.5)*1.5,",
410
- " screenX:this.screenX,screenY:this.screenY,",
411
- " buttons:this.buttons,button:this.button,",
412
- " bubbles:true,cancelable:true,composed:true,",
413
- " width:this.width,height:this.height,pressure:this.pressure,",
414
- " tiltX:this.tiltX,tiltY:this.tiltY,twist:this.twist});",
415
- " var tsV=cur.ts-k*8.3-Math.random()*1.2;",
416
- // isTrusted/timeStamp 是实例不可配置属性(defineProperty 抛
417
- // "Cannot redefine"),改 Proxy 包装:getPrototypeOf/ownKeys 透传,
418
- // instanceof 与属性枚举行为与真事件一致。IIFE 捕获本次循环的 tsV
419
- // 快照 —— var 提升会让所有 Proxy 闭包共享最后一次赋值(实测四个
420
- // 合成事件同时间戳、群内间隔塌到 ~2ms)。
421
- " out.push((function(e2,t2){return new Proxy(e2,{get:function(t,p){",
422
- ' if(p==="isTrusted")return true;',
423
- ' if(p==="timeStamp")return t2;',
424
- ' var v=Reflect.get(t,p);return typeof v==="function"?v.bind(t):v;',
425
- " }});})(ev,tsV));",
426
- " }",
427
- " out.push(this);",
428
- " }",
429
- " }",
430
- " _lm=cur;",
431
- " return out||list;",
432
- " };",
433
- " PointerEvent.prototype.getCoalescedEvents=_gceH;",
434
- // name 反查伪装:var _gceH=fn 的具名推断会暴露 hook(原生 name 是
435
- // "getCoalescedEvents")——toString 白名单管不到 name 属性。
436
- ' try{Object.defineProperty(_gceH,"name",{value:"getCoalescedEvents"});}catch(e){}',
437
- " }",
438
- " }catch(e){}",
439
- // 3d. Chrome object depth (d24): automation fakes usually only set
440
- // window.chrome = {}; deep checks hit app.run/runtime/csi/loadTimes.
441
- " try{",
442
- " if(window.chrome){",
443
- ' 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"}};',
444
- ' 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};',
445
- " if(!window.chrome.csi)window.chrome.csi=function(){return{};}",
446
- " if(!window.chrome.loadTimes)window.chrome.loadTimes=function(){return{};}",
447
- " }",
448
- " }catch(e){}",
449
- // 3e. Font availability patch (d25): headless Chromium misses some system
450
- // fonts (e.g. Menlo on macOS) that real Chrome has. Register a FontFace
451
- // aliasing the missing font to a local() equivalent so offsetWidth-based
452
- // font probing sees the same availability as the faked environment.
453
- " try{",
454
- ' var _fontAliases=[["Menlo","Courier New"],["SF Mono","Menlo"],["Segoe UI","Helvetica"]];',
455
- " _fontAliases.forEach(function(pa){",
456
- ' try{var ff=new FontFace(pa[0],"local("+JSON.stringify(pa[1])+")");',
457
- " document.fonts.add(ff);ff.load();}catch(e2){}",
458
- " });",
459
- " }catch(e){}",
460
- // 3g. Notification.requestPermission 延迟(d62):headless 无原生横幅,
461
- // request 瞬回 denied —— 真机 request 会 pending 在横幅上数秒到分钟。
462
- // 延迟 2-6s 再 resolve,模拟横幅期(用户"看了下然后拒绝")。
463
- " try{",
464
- " if(window.Notification&&Notification.requestPermission){",
465
- " var _nrp=Notification.requestPermission.bind(Notification);",
466
- " Notification.requestPermission=function(cb){",
467
- " return new Promise(function(res){",
468
- " setTimeout(function(){_nrp().then(function(r){if(cb)try{cb(r)}catch(e){}res(r);});},2000+Math.random()*4000);",
469
- " });",
470
- " };",
471
- " }",
472
- " }catch(e){}",
473
- // 3. toString disguise (name-list based)
474
- " var _ts=Function.prototype.toString;",
475
- " var _hf=document.hasFocus;",
476
- " Function.prototype.toString=function(){",
477
- ' if(this===_ael)return"function addEventListener(type, callback) { [native code] }";',
478
- ' if(this===_hf)return"function hasFocus() { [native code] }";',
479
- ' if(this===_gw)return"function get width() { [native code] }";',
480
- ' if(this===_gh)return"function get height() { [native code] }";',
481
- ' if(this===_gah)return"function get availHeight() { [native code] }";',
482
- ' if(this===CanvasRenderingContext2D.prototype.fillText)return"function fillText() { [native code] }";',
483
- ' if(this===HTMLCanvasElement.prototype.toDataURL)return"function toDataURL() { [native code] }";',
484
- ' if(this===AnalyserNode.prototype.getFloatFrequencyData)return"function getFloatFrequencyData() { [native code] }";',
485
- ' if(this===AudioBuffer.prototype.getChannelData)return"function getChannelData() { [native code] }";',
486
- ' if(this===_gceH)return"function getCoalescedEvents() { [native code] }";',
487
- ' if(this===Document.prototype.hasFocus)return"function hasFocus() { [native code] }";',
488
- ' if(this===Performance.prototype.now)return"function now() { [native code] }";',
489
- ' if(this===SpeechSynthesis.prototype.getVoices)return"function getVoices() { [native code] }";',
490
- " return _ts.call(this);",
491
- " };",
492
- // 4. onclick prototype hijack (dual-stream consistency)
493
- " var _ba=function(k,p){",
494
- ' if(p==="isTrusted"){',
495
- ' var orig=Reflect.get(k,"isTrusted");',
496
- " if(orig===true)return true;",
497
- ' if(k.type==="paste")return true;',
498
- " return orig;",
499
- " }",
500
- ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])&&k.isTrusted===true){',
501
- " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;return k[p]+_f;",
502
- " }",
503
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
504
- " };",
505
- ' Object.defineProperty(Document.prototype,"onclick",{',
506
- " configurable:true,",
507
- " get:function(){var raw=this.__ocRaw||null;if(!raw)return null;var self=this;",
508
- " return function(e){return raw.call(self,new Proxy(e,{get:function(k,p){return _ba(k,p)}}))}},",
509
- " set:function(fn){this.__ocRaw=fn}",
510
- " });",
511
- "})()"
512
- ].join("\n");
513
- }
514
-
515
36
  // src/cdp-driver/mouse.ts
516
37
  var XBMouseImpl = class {
517
38
  conn;
@@ -552,26 +73,26 @@ var XBMouseImpl = class {
552
73
  await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: p.x, y: p.y, button: this._button });
553
74
  this._x = p.x;
554
75
  this._y = p.y;
555
- await sleep2(p.delay);
76
+ await sleep(p.delay);
556
77
  }
557
78
  this._x = tx;
558
79
  this._y = ty;
559
80
  if (_truncated) {
560
81
  await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: tx, y: ty, button: this._button });
561
82
  }
562
- await sleep2(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
83
+ await sleep(rand(...DEFAULT_STEALTH_CONFIG.aimPause));
563
84
  } else {
564
85
  await this.move(tx, ty);
565
86
  }
566
- await this.down({ button });
567
- await sleep2(stealth ? rand(...DEFAULT_STEALTH_CONFIG.pressDuration) : opts.delay ?? 0);
87
+ await this.down({ button, clickCount: opts.clickCount ?? 1 });
88
+ await sleep(stealth ? rand(...DEFAULT_STEALTH_CONFIG.pressDuration) : opts.delay ?? 0);
568
89
  const rx = stealth ? this._x + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._x;
569
90
  const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
570
91
  this._x = rx;
571
92
  this._y = ry;
572
93
  await this.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: rx, y: ry, button, clickCount: opts.clickCount ?? 1 });
573
94
  for (let i = 1; i < (opts.clickCount ?? 1); i++) {
574
- if (opts.delay) await sleep2(opts.delay);
95
+ if (opts.delay) await sleep(opts.delay);
575
96
  await this.down({ button });
576
97
  await this.up({ button });
577
98
  }
@@ -587,7 +108,9 @@ var XBMouseImpl = class {
587
108
  x: this._x,
588
109
  y: this._y,
589
110
  button,
590
- clickCount: 1
111
+ // r23: press 必须与 release 声明同一 clickCount——Chrome 按序列计数
112
+ // 合成 click/dblclick,press 缺声明会把计数器重置(dblclick 永不合成)
113
+ clickCount: opts.clickCount ?? 1
591
114
  });
592
115
  }
593
116
  async up(opts = {}) {
@@ -598,7 +121,7 @@ var XBMouseImpl = class {
598
121
  x: this._x,
599
122
  y: this._y,
600
123
  button,
601
- clickCount: 1
124
+ clickCount: opts.clickCount ?? 1
602
125
  });
603
126
  }
604
127
  async move(x, y, opts = {}) {
@@ -609,7 +132,7 @@ var XBMouseImpl = class {
609
132
  const dx = x - fromX;
610
133
  const dy = y - fromY;
611
134
  for (let i = 1; i <= steps; i++) {
612
- if (stealth) await sleep2(rand(16, 28));
135
+ if (stealth) await sleep(rand(16, 28));
613
136
  const t = i / steps;
614
137
  this._x = fromX + dx * t;
615
138
  this._y = fromY + dy * t;
@@ -643,7 +166,7 @@ var XBMouseImpl = class {
643
166
  const steps = opts.steps ?? Math.max(10, Math.min(24, Math.round(Math.hypot(x - this._x, y - this._y) / 20)));
644
167
  const fx = this._x, fy = this._y;
645
168
  for (let i = 1; i <= steps; i++) {
646
- if (stealth) await sleep2(rand(16, 28));
169
+ if (stealth) await sleep(rand(16, 28));
647
170
  const t = i / steps;
648
171
  this._x = fx + (x - fx) * t;
649
172
  this._y = fy + (y - fy) * t;
@@ -656,7 +179,7 @@ var XBMouseImpl = class {
656
179
  }
657
180
  this._x = x;
658
181
  this._y = y;
659
- await sleep2(rand(60, 140));
182
+ await sleep(rand(60, 140));
660
183
  await this.send("Input.dispatchMouseEvent", {
661
184
  type: "mouseReleased",
662
185
  x,
@@ -679,7 +202,7 @@ var XBMouseImpl = class {
679
202
  await this.conn.send(method, params, this.sessionId);
680
203
  }
681
204
  };
682
- function sleep2(ms) {
205
+ function sleep(ms) {
683
206
  return new Promise((resolve) => setTimeout(resolve, ms));
684
207
  }
685
208
 
@@ -709,17 +232,17 @@ var XBKeyboardImpl = class {
709
232
  await this.dispatchKeyEvent(downParams);
710
233
  if (mapping.text) {
711
234
  if (process.env.XBROWSER_STEALTH !== "off") {
712
- await sleep3(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
235
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
713
236
  }
714
237
  await this.dispatchKeyEvent({
715
238
  type: "char",
716
239
  text: mapping.text
717
240
  });
718
241
  }
719
- if (delay > 0) await sleep3(delay);
242
+ if (delay > 0) await sleep2(delay);
720
243
  else {
721
244
  if (process.env.XBROWSER_STEALTH !== "off") {
722
- await sleep3(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
245
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
723
246
  }
724
247
  }
725
248
  const upParams = {
@@ -765,16 +288,16 @@ var XBKeyboardImpl = class {
765
288
  const fixedDelay = opts.delay ?? 0;
766
289
  for (const char of text) {
767
290
  if (fixedDelay > 0) {
768
- await sleep3(fixedDelay);
291
+ await sleep2(fixedDelay);
769
292
  } else if (stealth) {
770
- await sleep3(typingDelay());
293
+ await sleep2(typingDelay());
771
294
  }
772
295
  if (stealth && char.length === 1 && Math.random() < DEFAULT_STEALTH_CONFIG.typoProbability) {
773
296
  const wrong = NEIGHBOR_KEYS[char];
774
297
  if (wrong && wrong !== char) {
775
298
  await this.dispatchKeySequence(resolveKeyMapping(wrong), stealth);
776
- await sleep3(rand(120, 420));
777
- await this.dispatchKeySequence(KEY_MAP2.Backspace, stealth);
299
+ await sleep2(rand(120, 420));
300
+ await this.dispatchKeySequence(KEY_MAP.Backspace, stealth);
778
301
  }
779
302
  }
780
303
  await this.dispatchKeySequence(resolveKeyMapping(char), stealth);
@@ -804,7 +327,7 @@ var XBKeyboardImpl = class {
804
327
  await this.dispatchKeyEvent({ type: "char", text: mapping.text });
805
328
  }
806
329
  if (stealth) {
807
- await sleep3(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
330
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
808
331
  }
809
332
  const upParams = {
810
333
  type: "keyUp",
@@ -843,7 +366,7 @@ var XBKeyboardImpl = class {
843
366
  }
844
367
  await this.dispatchKeyEvent(downParams);
845
368
  if (process.env.XBROWSER_STEALTH !== "off") {
846
- await sleep3(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
369
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
847
370
  }
848
371
  await this.dispatchKeyEvent({
849
372
  type: "keyUp",
@@ -867,7 +390,7 @@ var XBKeyboardImpl = class {
867
390
  await this.dispatchKeyEvent({ type: "rawKeyDown", key: m.key, code: m.code, ...m.keyCode ? { windowsVirtualKeyCode: m.keyCode } : {}, modifiers: bits });
868
391
  await this.dispatchKeyEvent({ type: "keyDown", key: k.key, code: k.code, ...k.keyCode ? { windowsVirtualKeyCode: k.keyCode } : {}, modifiers: bits });
869
392
  if (process.env.XBROWSER_STEALTH !== "off") {
870
- await sleep3(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
393
+ await sleep2(rand(...DEFAULT_STEALTH_CONFIG.keyPressDuration));
871
394
  }
872
395
  await this.dispatchKeyEvent({ type: "keyUp", key: k.key, code: k.code, ...k.keyCode ? { windowsVirtualKeyCode: k.keyCode } : {}, modifiers: bits });
873
396
  await this.dispatchKeyEvent({ type: "keyUp", key: m.key, code: m.code, ...m.keyCode ? { windowsVirtualKeyCode: m.keyCode } : {}, modifiers: 0 });
@@ -877,7 +400,7 @@ var XBKeyboardImpl = class {
877
400
  }
878
401
  };
879
402
  function resolveKeyMapping(key) {
880
- if (KEY_MAP2[key]) return KEY_MAP2[key];
403
+ if (KEY_MAP[key]) return KEY_MAP[key];
881
404
  if (key.length === 1) {
882
405
  const lower = key.toLowerCase();
883
406
  if (lower >= "a" && lower <= "z") {
@@ -894,7 +417,7 @@ function resolveKeyMapping(key) {
894
417
  }
895
418
  return { key, code: key };
896
419
  }
897
- var KEY_MAP2 = {
420
+ var KEY_MAP = {
898
421
  Enter: { key: "Enter", code: "Enter", text: "\r", keyCode: 13 },
899
422
  Tab: { key: "Tab", code: "Tab", text: " ", keyCode: 9 },
900
423
  Escape: { key: "Escape", code: "Escape", keyCode: 27 },
@@ -963,7 +486,7 @@ var NEIGHBOR_KEYS = {
963
486
  "8": "9",
964
487
  "9": "0"
965
488
  };
966
- function sleep3(ms) {
489
+ function sleep2(ms) {
967
490
  return new Promise((resolve) => setTimeout(resolve, ms));
968
491
  }
969
492
 
@@ -1153,6 +676,14 @@ var XBLocatorImpl = class _XBLocatorImpl {
1153
676
  await waitForActionable(this.page, this.selector, opts);
1154
677
  await scrollIntoView(this.page, this.selector);
1155
678
  await this.click({ ...opts });
679
+ await this.page.evaluate(`
680
+ (function() {
681
+ const el = ${this._q(this.selector)};
682
+ if (!el) return;
683
+ if (document.activeElement !== el) el.focus();
684
+ if ((el.value || el.textContent || '') !== '') document.execCommand('selectAll');
685
+ })()
686
+ `);
1156
687
  if (process.env.XBROWSER_STEALTH !== "off" && value.length >= 40 && process.env.XBROWSER_FILL_TYPE !== "type") {
1157
688
  try {
1158
689
  const { pasteViaClipboard, syntheticPaste } = await import("./clipboard-BOL2GP2E.js");
@@ -1908,6 +1439,189 @@ var XBPageImpl = class _XBPageImpl {
1908
1439
  await this.conn.send("Network.enable", void 0, this.sessionId);
1909
1440
  await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
1910
1441
  });
1442
+ if (this._contextImpl.ignoreHTTPSErrors) {
1443
+ await this.conn.send("Security.enable", void 0, this.sessionId).catch(() => {
1444
+ });
1445
+ await this.conn.send("Security.setIgnoreCertificateErrors", { ignore: true }, this.sessionId).catch(() => {
1446
+ });
1447
+ }
1448
+ if (this._contextImpl.httpCredentials) {
1449
+ await this.conn.send("Fetch.enable", {
1450
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
1451
+ handleAuthRequests: true
1452
+ }, this.sessionId).catch(() => {
1453
+ });
1454
+ this._subscriptions.push(
1455
+ this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
1456
+ if (this._interceptionEnabled) return;
1457
+ const p = params;
1458
+ this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
1459
+ });
1460
+ })
1461
+ );
1462
+ this._subscriptions.push(
1463
+ this.conn.subscribe("Fetch.authRequired", this.sessionId, (params) => {
1464
+ const p = params;
1465
+ const creds = this._contextImpl.httpCredentials;
1466
+ this.conn.send("Fetch.continueWithAuth", {
1467
+ requestId: p.requestId,
1468
+ authChallengeResponse: creds ? { response: "ProvideCredentials", username: creds.username, password: creds.password } : { response: "CancelAuth" }
1469
+ }, this.sessionId).catch(() => {
1470
+ });
1471
+ })
1472
+ );
1473
+ }
1474
+ await this.conn.send("Page.addScriptToEvaluateOnNewDocument", {
1475
+ source: [
1476
+ "try { window.print = function() {}; window.__xb_print_suppressed = true; } catch (e) {}",
1477
+ "try {",
1478
+ " if (window.showOpenFilePicker) {",
1479
+ " var __xb_mkHandle = function(name, content) {",
1480
+ ' var file = new File([content], name, { type: "text/plain" });',
1481
+ " return {",
1482
+ ' kind: "file", name: name,',
1483
+ " getFile: function() { return Promise.resolve(file); },",
1484
+ " createWritable: function() { return Promise.resolve({ write: function() { return Promise.resolve(); }, close: function() { return Promise.resolve(); } }); },",
1485
+ " isSameEntry: function() { return Promise.resolve(false); },",
1486
+ ' queryPermission: function() { return Promise.resolve("granted"); },',
1487
+ ' requestPermission: function() { return Promise.resolve("granted"); },',
1488
+ " };",
1489
+ " };",
1490
+ " window.showOpenFilePicker = function() {",
1491
+ ' return Promise.resolve([__xb_mkHandle("xbrowser-stub.txt", "xbrowser fs access stub")]);',
1492
+ " };",
1493
+ " window.showSaveFilePicker = function() {",
1494
+ ' return Promise.resolve(__xb_mkHandle("xbrowser-stub-save.txt", ""));',
1495
+ " };",
1496
+ " window.showDirectoryPicker = function() {",
1497
+ " var emptyIter = function() { return [][Symbol.iterator](); };",
1498
+ " return Promise.resolve({",
1499
+ ' kind: "directory", name: "xbrowser-stub-dir",',
1500
+ " values: emptyIter, entries: emptyIter, keys: emptyIter,",
1501
+ ' getDirectoryHandle: function() { return Promise.reject(new Error("stub empty dir")); },',
1502
+ ' getFileHandle: function() { return Promise.reject(new Error("stub empty dir")); },',
1503
+ " isSameEntry: function() { return Promise.resolve(false); },",
1504
+ ' queryPermission: function() { return Promise.resolve("granted"); },',
1505
+ ' requestPermission: function() { return Promise.resolve("granted"); },',
1506
+ " });",
1507
+ " };",
1508
+ " window.__xb_fs_stub_installed = true;",
1509
+ " }",
1510
+ "} catch (e) {}",
1511
+ // sup-s7: 右键菜单压制——headful 下 CDP 右键弹浏览器原生菜单(CDP
1512
+ // 无法关闭浏览器 UI)。document 捕获阶段 preventDefault 抑制原生
1513
+ // 菜单;不阻断传播,录制 contextmenu 事件与页面自定义菜单不受影响。
1514
+ "try {",
1515
+ ' document.addEventListener("contextmenu", function(e) { e.preventDefault(); }, true);',
1516
+ " window.__xb_ctxmenu_suppressed = true;",
1517
+ "} catch (e) {}",
1518
+ // sup-s10: Notification 守卫——new Notification() 弹 OS 级系统横幅
1519
+ // (headful 污染屏幕,等待通知交互的流程挂起)。no-op 包装但保
1520
+ // API 形状:permission/granted、requestPermission→granted、实例
1521
+ // title/close 可用——页面通知流程无感继续。
1522
+ "try {",
1523
+ " var XBN = function Notification(title, options) {",
1524
+ " this.title = title;",
1525
+ ' this.body = (options && options.body) || "";',
1526
+ ' this.tag = (options && options.tag) || "";',
1527
+ " this.onclick = null; this.onshow = null; this.onerror = null; this.onclose = null;",
1528
+ " };",
1529
+ " XBN.prototype.close = function() {};",
1530
+ ' XBN.permission = "granted";',
1531
+ ' XBN.requestPermission = function() { return Promise.resolve("granted"); };',
1532
+ " XBN.maxActions = (window.Notification && window.Notification.maxActions) || 2;",
1533
+ " window.Notification = XBN;",
1534
+ " window.__xb_notification_suppressed = true;",
1535
+ "} catch (e) {}",
1536
+ // sup-W1: WebAPI 选择器/配对框家族 stub(1/7 Serial)——
1537
+ // navigator.serial.requestPort() 弹浏览器原生串口选择器(CDP 无法
1538
+ // 拦截),headless 下 promise 挂起。stub 返回 rejected Promise
1539
+ // (NotFoundError),页面 catch 分支接管、流程继续。
1540
+ "try {",
1541
+ " if (navigator.serial) {",
1542
+ " navigator.serial.requestPort = function() {",
1543
+ ' return Promise.reject(new DOMException("xbrowser serial stub", "NotFoundError"));',
1544
+ " };",
1545
+ " window.__xb_serial_stubbed = true;",
1546
+ " }",
1547
+ "} catch (e) {}",
1548
+ // sup-W2: WebAPI stub(2/7 USB)——requestDevice 弹原生设备配对框,
1549
+ // 同 Serial pattern:rejected Promise(NotFoundError),catch 接管。
1550
+ "try {",
1551
+ " if (navigator.usb) {",
1552
+ " navigator.usb.requestDevice = function() {",
1553
+ ' return Promise.reject(new DOMException("xbrowser usb stub", "NotFoundError"));',
1554
+ " };",
1555
+ " window.__xb_usb_stubbed = true;",
1556
+ " }",
1557
+ "} catch (e) {}",
1558
+ // sup-W3: WebAPI stub(3/7 Bluetooth)——requestDevice 弹原生蓝牙
1559
+ // 配对框,同 Serial/USB pattern:rejected Promise(NotFoundError)。
1560
+ // CI linux headless 下 navigator.bluetooth 原生不存在——缺失时合成
1561
+ // 对象再包装,保证跨平台语义一致(requestDevice 恒 rejected)。
1562
+ "try {",
1563
+ " if (!navigator.bluetooth) {",
1564
+ ' try { Object.defineProperty(navigator, "bluetooth", { value: {}, configurable: true }); } catch (e) {}',
1565
+ " }",
1566
+ " if (navigator.bluetooth) {",
1567
+ " navigator.bluetooth.requestDevice = function() {",
1568
+ ' return Promise.reject(new DOMException("xbrowser ble stub", "NotFoundError"));',
1569
+ " };",
1570
+ " window.__xb_ble_stubbed = true;",
1571
+ " }",
1572
+ "} catch (e) {}",
1573
+ // sup-W4: WebAPI stub(4/7 HID)——requestDevices 弹原生 HID 设备
1574
+ // 选择器,同家族 pattern:rejected Promise(NotFoundError)。
1575
+ "try {",
1576
+ " if (navigator.hid) {",
1577
+ " navigator.hid.requestDevices = function() {",
1578
+ ' return Promise.reject(new DOMException("xbrowser hid stub", "NotFoundError"));',
1579
+ " };",
1580
+ " window.__xb_hid_stubbed = true;",
1581
+ " }",
1582
+ "} catch (e) {}",
1583
+ // sup-W5: WebAPI stub(5/7 WakeLock)——request('screen') 在无用户
1584
+ // 激活/权限时挂起或拒绝,等待 wake 事件的流程死锁。stub 返回合成
1585
+ // sentinel(release 可用,不真实持锁)。
1586
+ "try {",
1587
+ " if (navigator.wakeLock) {",
1588
+ " navigator.wakeLock.request = function() {",
1589
+ " return Promise.resolve({",
1590
+ " released: false,",
1591
+ ' type: "screen",',
1592
+ " release: function() { this.released = true; return Promise.resolve(); },",
1593
+ " addEventListener: function() {},",
1594
+ " removeEventListener: function() {},",
1595
+ " });",
1596
+ " };",
1597
+ " window.__xb_wakelock_stubbed = true;",
1598
+ " }",
1599
+ "} catch (e) {}",
1600
+ // sup-W6: WebAPI stub(6/7 IdleDetector)——start() 需权限气泡授权
1601
+ // 才能继续,headless 下挂起。stub 返回 rejected(NotAllowedError),
1602
+ // 页面 catch 分支接管。
1603
+ "try {",
1604
+ " if (window.IdleDetector) {",
1605
+ " IdleDetector.start = function() {",
1606
+ ' return Promise.reject(new DOMException("xbrowser idle stub", "NotAllowedError"));',
1607
+ " };",
1608
+ " window.__xb_idle_stubbed = true;",
1609
+ " }",
1610
+ "} catch (e) {}",
1611
+ // sup-W7: WebAPI stub(7/7 PaymentRequest)——show() 弹浏览器支付
1612
+ // 面板(无用户交互不关闭),headless 下 promise 挂起。stub 返回
1613
+ // rejected(NotAllowedError),页面 catch 分支接管。
1614
+ "try {",
1615
+ " if (window.PaymentRequest) {",
1616
+ " PaymentRequest.prototype.show = function() {",
1617
+ ' return Promise.reject(new DOMException("xbrowser pay stub", "NotAllowedError"));',
1618
+ " };",
1619
+ " window.__xb_pay_stubbed = true;",
1620
+ " }",
1621
+ "} catch (e) {}"
1622
+ ].join("\n")
1623
+ }, this.sessionId).catch(() => {
1624
+ });
1911
1625
  this.setupPageEvents();
1912
1626
  this.setupNetworkEvents();
1913
1627
  this.setupConsoleEvents();
@@ -1939,7 +1653,7 @@ var XBPageImpl = class _XBPageImpl {
1939
1653
  try {
1940
1654
  await this.conn.send(
1941
1655
  "Page.addScriptToEvaluateOnNewDocument",
1942
- { source: buildStealthInitScript() },
1656
+ { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
1943
1657
  this.sessionId
1944
1658
  );
1945
1659
  } catch {
@@ -2348,7 +2062,9 @@ Last error: ${lastError.message}` : "";
2348
2062
  await this.locator(selector).click(opts);
2349
2063
  }
2350
2064
  async dblclick(selector, opts = {}) {
2351
- await this.locator(selector).click({ ...opts, clickCount: 2 });
2065
+ const locator = this.locator(selector);
2066
+ await locator.click({ ...opts, clickCount: 1 });
2067
+ await locator.click({ ...opts, clickCount: 2 });
2352
2068
  }
2353
2069
  async fill(selector, value, opts = {}) {
2354
2070
  await this.locator(selector).fill(value, opts);
@@ -2465,6 +2181,26 @@ Last error: ${lastError.message}` : "";
2465
2181
  );
2466
2182
  this._viewportSize = size;
2467
2183
  }
2184
+ /**
2185
+ * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
2186
+ * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
2187
+ */
2188
+ async setDeviceScaleFactor(dsf) {
2189
+ const size = this._viewportSize ?? await this.evaluate(
2190
+ "({ width: window.innerWidth, height: window.innerHeight })"
2191
+ );
2192
+ await this.conn.send(
2193
+ "Emulation.setDeviceMetricsOverride",
2194
+ {
2195
+ width: size.width,
2196
+ height: size.height,
2197
+ deviceScaleFactor: dsf,
2198
+ mobile: false
2199
+ },
2200
+ this.sessionId
2201
+ );
2202
+ this._viewportSize = size;
2203
+ }
2468
2204
  // ── Scripts ─────────────────────────────────────────────────
2469
2205
  async addInitScript(script) {
2470
2206
  await this.conn.send(
@@ -2688,6 +2424,12 @@ Last error: ${lastError.message}` : "";
2688
2424
  async _cdpSend(method, params) {
2689
2425
  return this.conn.send(method, params, this.sessionId);
2690
2426
  }
2427
+ /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2428
+ * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2429
+ * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2430
+ setBeforeUnloadBehavior(mode) {
2431
+ this._beforeUnloadAccept = mode === "accept";
2432
+ }
2691
2433
  /**
2692
2434
  * 开启/关闭原生文件选择框拦截(CDP stateful 开关)。
2693
2435
  *
@@ -2746,8 +2488,9 @@ Last error: ${lastError.message}` : "";
2746
2488
  }
2747
2489
  };
2748
2490
  this._emit("dialog", dialog);
2491
+ const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
2749
2492
  setTimeout(() => {
2750
- this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
2493
+ this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
2751
2494
  });
2752
2495
  }, 0);
2753
2496
  })
@@ -2890,6 +2633,7 @@ Last error: ${lastError.message}` : "";
2890
2633
  _networkRequests = /* @__PURE__ */ new Map();
2891
2634
  _routeHandlers = [];
2892
2635
  _interceptionEnabled = false;
2636
+ _beforeUnloadAccept = true;
2893
2637
  /** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
2894
2638
  _storeNetworkRequest(requestId, data) {
2895
2639
  this._networkRequests.set(requestId, { requestId, ...data });
@@ -3001,7 +2745,10 @@ Last error: ${lastError.message}` : "";
3001
2745
  if (!this._interceptionEnabled) {
3002
2746
  this._interceptionEnabled = true;
3003
2747
  await this.conn.send("Fetch.enable", {
3004
- patterns: [{ urlPattern: "*", requestStage: "Request" }]
2748
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
2749
+ // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2750
+ // 会顶掉 _init 的 auth 配置)
2751
+ handleAuthRequests: true
3005
2752
  }, this.sessionId);
3006
2753
  this._subscriptions.push(
3007
2754
  this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
@@ -3054,6 +2801,36 @@ Last error: ${lastError.message}` : "";
3054
2801
  });
3055
2802
  }
3056
2803
  // ── setInputFiles ───────────────────────────────────────────
2804
+ /**
2805
+ * sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
2806
+ * dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
2807
+ * 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
2808
+ * 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
2809
+ * 中心)。
2810
+ */
2811
+ async dropFiles(selector, payload) {
2812
+ await this.evaluate(`
2813
+ (function() {
2814
+ var el = ${queryJS(selector)};
2815
+ if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
2816
+ var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
2817
+ var bin = atob(b64);
2818
+ var buf = new Uint8Array(bin.length);
2819
+ for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
2820
+ var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
2821
+ var dt = new DataTransfer();
2822
+ dt.items.add(file);
2823
+ var rect = el.getBoundingClientRect();
2824
+ var opts = {
2825
+ bubbles: true, cancelable: true,
2826
+ clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
2827
+ };
2828
+ el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
2829
+ el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
2830
+ el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
2831
+ })()
2832
+ `);
2833
+ }
3057
2834
  async setInputFiles(selector, files) {
3058
2835
  const fileArr = Array.isArray(files) ? files : [files];
3059
2836
  const fileList = fileArr.map((f) => ({
@@ -3196,6 +2973,18 @@ var XBContextImpl = class {
3196
2973
  this.options = opts;
3197
2974
  this.setupAutoAttach();
3198
2975
  }
2976
+ /** S194: 任务 tab 的 stealth 配置(UA-CH 档案等)经 context 传给 page 层 */
2977
+ get stealthConfig() {
2978
+ return this.options.stealthConfig;
2979
+ }
2980
+ /** sup-s9: HTTP 认证凭证经 context 传给 page 层(authRequired 自动响应) */
2981
+ get httpCredentials() {
2982
+ return this.options.httpCredentials;
2983
+ }
2984
+ /** sup-s12: 自签/无效证书放行——经 context 传给 page 层(原为死字段) */
2985
+ get ignoreHTTPSErrors() {
2986
+ return this.options.ignoreHTTPSErrors;
2987
+ }
3199
2988
  async newPage() {
3200
2989
  if (this.closed) throw new Error("Context is closed");
3201
2990
  const { targetId } = await this._browser._createTarget(this.contextId);
@@ -3362,20 +3151,8 @@ var XBContextImpl = class {
3362
3151
 
3363
3152
  // src/cdp-driver/browser.ts
3364
3153
  var XBBrowserImpl = class {
3365
- conn;
3366
- _emitter = new EventEmitter3();
3367
- _contexts = /* @__PURE__ */ new Map();
3368
- _disconnected = false;
3369
- childProcess = null;
3370
- tmpDir;
3371
- _exitHandler = null;
3372
- /**
3373
- * Original CDP endpoint (HTTP or ws URL) used to construct this browser.
3374
- * Used by discoverContexts() as a fallback to HTTP /json/list when
3375
- * Target.getTargets doesn't return page-type targets (e.g. cdp-tunnel proxy).
3376
- */
3377
- cdpEndpoint;
3378
- constructor(conn, childProcess, tmpDir, cdpEndpoint) {
3154
+ constructor(conn, childProcess, tmpDir, cdpEndpoint, launchOpts) {
3155
+ this.launchOpts = launchOpts;
3379
3156
  this.conn = conn;
3380
3157
  this.childProcess = childProcess ?? null;
3381
3158
  this.tmpDir = tmpDir;
@@ -3403,6 +3180,20 @@ var XBBrowserImpl = class {
3403
3180
  process.on("exit", this._exitHandler);
3404
3181
  }
3405
3182
  }
3183
+ launchOpts;
3184
+ conn;
3185
+ _emitter = new EventEmitter3();
3186
+ _contexts = /* @__PURE__ */ new Map();
3187
+ _disconnected = false;
3188
+ childProcess = null;
3189
+ tmpDir;
3190
+ _exitHandler = null;
3191
+ /**
3192
+ * Original CDP endpoint (HTTP or ws URL) used to construct this browser.
3193
+ * Used by discoverContexts() as a fallback to HTTP /json/list when
3194
+ * Target.getTargets doesn't return page-type targets (e.g. cdp-tunnel proxy).
3195
+ */
3196
+ cdpEndpoint;
3406
3197
  get disconnected() {
3407
3198
  return this._disconnected;
3408
3199
  }
@@ -3423,13 +3214,16 @@ var XBBrowserImpl = class {
3423
3214
  this._exitHandler = null;
3424
3215
  }
3425
3216
  if (this.childProcess) {
3426
- const { killChrome: killChrome2 } = await import("./launcher-44STYRJC.js");
3217
+ const { killChrome: killChrome2 } = await import("./launcher-IK2FKW6T.js");
3427
3218
  await killChrome2(this.childProcess, this.tmpDir);
3428
3219
  }
3429
3220
  await this.conn.close();
3430
3221
  this._emitter.emit("disconnected");
3431
3222
  }
3432
3223
  async newContext(opts = {}) {
3224
+ if (this.launchOpts?.stealthConfig && !opts.stealthConfig) {
3225
+ opts = { ...opts, stealthConfig: this.launchOpts.stealthConfig };
3226
+ }
3433
3227
  if (this._disconnected) {
3434
3228
  throw new Error("Browser is disconnected");
3435
3229
  }
@@ -3446,6 +3240,38 @@ var XBBrowserImpl = class {
3446
3240
  } catch {
3447
3241
  }
3448
3242
  const context = new XBContextImpl(this.conn, contextId, this, opts);
3243
+ if (!this.cdpEndpoint && contextId !== "default") {
3244
+ const downloadDir = join(tmpdir(), "xbrowser-downloads");
3245
+ try {
3246
+ mkdirSync(downloadDir, { recursive: true });
3247
+ } catch {
3248
+ }
3249
+ await this.conn.send("Browser.setDownloadBehavior", {
3250
+ behavior: "allowAndName",
3251
+ downloadPath: downloadDir,
3252
+ eventsEnabled: false,
3253
+ browserContextId: contextId
3254
+ }, void 0, 1e4).catch(() => {
3255
+ });
3256
+ await this.conn.send("Browser.grantPermissions", {
3257
+ permissions: [
3258
+ "notifications",
3259
+ "geolocation",
3260
+ "clipboardReadWrite",
3261
+ "clipboardSanitizedWrite",
3262
+ "videoCapture",
3263
+ "audioCapture",
3264
+ "midi"
3265
+ ],
3266
+ browserContextId: contextId
3267
+ }, void 0, 1e4).catch(() => {
3268
+ this.conn.send("Browser.grantPermissions", {
3269
+ permissions: ["notifications", "geolocation"],
3270
+ browserContextId: contextId
3271
+ }, void 0, 1e4).catch(() => {
3272
+ });
3273
+ });
3274
+ }
3449
3275
  context.on("page", (page) => {
3450
3276
  this._emitter.emit("page", page);
3451
3277
  });
@@ -3558,7 +3384,7 @@ var XBBrowserImpl = class {
3558
3384
  if (pageTargets.length === 0 && httpFallbackUrl) {
3559
3385
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
3560
3386
  try {
3561
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-44STYRJC.js");
3387
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-IK2FKW6T.js");
3562
3388
  const httpPages = await getCDPTargets2(httpFallbackUrl);
3563
3389
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
3564
3390
  for (const p of httpPages) {
@@ -3656,6 +3482,9 @@ function extractAllStrings(rawArgs) {
3656
3482
  }
3657
3483
  return strings.length > 0 ? strings.join("\n") : null;
3658
3484
  }
3485
+ function isProbeMarked(code) {
3486
+ return code.includes("/* @xb-probe */");
3487
+ }
3659
3488
 
3660
3489
  // src/cdp-interceptor/rules/dom-mutation.ts
3661
3490
  var DOM_PATTERNS = [
@@ -4218,6 +4047,7 @@ var eventSimulationRule = {
4218
4047
  evaluate(ctx) {
4219
4048
  const userCode = extractUserCode(ctx);
4220
4049
  if (!userCode) return null;
4050
+ if (isProbeMarked(userCode)) return null;
4221
4051
  for (const p of EVENT_PATTERNS) {
4222
4052
  if (p.pattern.test(userCode)) {
4223
4053
  return {
@@ -4545,6 +4375,11 @@ function createRuleEngine(customRules) {
4545
4375
  ...ctx,
4546
4376
  sessionState: getSessionState(ctx.sessionId)
4547
4377
  };
4378
+ try {
4379
+ const code = typeof ctx.params?.expression === "string" ? ctx.params.expression : JSON.stringify(ctx.params ?? "");
4380
+ if (isProbeMarked(code)) return null;
4381
+ } catch {
4382
+ }
4548
4383
  for (const rule of rules) {
4549
4384
  if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
4550
4385
  const decision = rule.evaluate(fullCtx);
@@ -4925,15 +4760,27 @@ async function launch(options = {}) {
4925
4760
  }
4926
4761
  const conn = new CDPConnection(wsEndpoint);
4927
4762
  await conn.ready();
4763
+ let stealthOpts;
4764
+ try {
4765
+ const bv = await conn.send("Browser.getVersion");
4766
+ const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
4767
+ if (m && !options.stealthConfig?.uaChProfile) {
4768
+ const { deriveUaChProfileForBinary } = await import("./stealth-JOXGV34D.js");
4769
+ stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
4770
+ }
4771
+ } catch {
4772
+ }
4773
+ if (options.stealthConfig) {
4774
+ stealthOpts = {
4775
+ stealthConfig: { ...stealthOpts?.stealthConfig ?? {}, ...options.stealthConfig }
4776
+ };
4777
+ }
4928
4778
  const httpEndpoint = options.cdpEndpoint && !options.cdpEndpoint.startsWith("ws") ? options.cdpEndpoint : void 0;
4929
- const browser = new XBBrowserImpl(conn, childProcess, tmpDir, httpEndpoint);
4779
+ const browser = new XBBrowserImpl(conn, childProcess, tmpDir, httpEndpoint, stealthOpts);
4930
4780
  return { browser, wsEndpoint };
4931
4781
  }
4932
4782
 
4933
4783
  export {
4934
- rand,
4935
- sleep,
4936
- wheelDelta,
4937
4784
  XBMouseImpl,
4938
4785
  XBKeyboardImpl,
4939
4786
  waitForActionable,