@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,3 +1,11 @@
1
+ import {
2
+ DEFAULT_STEALTH_CONFIG,
3
+ bezierTrajectory,
4
+ buildStealthInitScript,
5
+ landingOffset,
6
+ rand,
7
+ typingDelay
8
+ } from "./chunk-GYB5BOSP.js";
1
9
  import {
2
10
  connectToCDP,
3
11
  errMsg,
@@ -5,13 +13,16 @@ import {
5
13
  getCDPTargets,
6
14
  killChrome,
7
15
  launchChrome
8
- } from "./chunk-IWVG4XYZ.js";
16
+ } from "./chunk-VCVDILH6.js";
9
17
  import {
10
18
  __require
11
19
  } from "./chunk-3RG5ZIWI.js";
12
20
 
13
21
  // src/cdp-driver/browser.ts
14
22
  import { EventEmitter as EventEmitter3 } from "events";
23
+ import { mkdirSync } from "fs";
24
+ import { join } from "path";
25
+ import { tmpdir } from "os";
15
26
 
16
27
  // src/cdp-driver/context.ts
17
28
  import { EventEmitter as EventEmitter2 } from "events";
@@ -19,488 +30,6 @@ import { EventEmitter as EventEmitter2 } from "events";
19
30
  // src/cdp-driver/page.ts
20
31
  import { EventEmitter } from "events";
21
32
 
22
- // src/cdp-driver/stealth.ts
23
- var DEFAULT_STEALTH_CONFIG = {
24
- bezierCurvature: [0.35, 0.6],
25
- noiseAmplitude: 5.5,
26
- overshootRange: [6, 14],
27
- aimPause: [80, 280],
28
- pressDuration: [60, 140],
29
- releaseDrift: [0.8, 2.5],
30
- landingOffsetSmall: [0.3, 2.5],
31
- landingOffsetLarge: [1.5, 7],
32
- smallElementThreshold: 30,
33
- typingRhythm: {
34
- fastProb: 0.22,
35
- fastRange: [25, 60],
36
- normalRange: [50, 350],
37
- pauseProb: 0.18,
38
- pauseRange: [400, 1200]
39
- },
40
- keyPressDuration: [50, 110],
41
- typoProbability: 0.06,
42
- wheelPeak: 180,
43
- wheelDecayRate: 0.4
44
- };
45
- function rand(min, max) {
46
- return min + Math.random() * (max - min);
47
- }
48
- function cosineEase(t) {
49
- return 0.5 - 0.5 * Math.cos(Math.PI * t);
50
- }
51
- function bezierTrajectory(x0, y0, x1, y1, config = DEFAULT_STEALTH_CONFIG) {
52
- const dist = Math.hypot(x1 - x0, y1 - y0);
53
- const n = Math.max(10, Math.min(28, Math.round(dist / 15)));
54
- const shortMove = dist < 120;
55
- const curvature = shortMove ? rand(2, 6) : Math.max(dist * rand(...config.bezierCurvature), rand(18, 35));
56
- const dir = Math.random() < 0.5 ? 1 : -1;
57
- const d = dist || 1;
58
- const dx = x1 - x0, dy = y1 - y0;
59
- const c1x = x0 + dx * 0.3 - dy / d * curvature * 0.5 * dir;
60
- const c1y = y0 + dy * 0.3 + dx / d * curvature * 0.5 * dir;
61
- const c2x = x0 + dx * 0.7 - dy / d * curvature * 0.8 * dir;
62
- const c2y = y0 + dy * 0.7 + dx / d * curvature * 0.8 * dir;
63
- const points = [];
64
- for (let i = 1; i <= n; i++) {
65
- const t = cosineEase(i / n);
66
- const mt = 1 - t;
67
- let px = mt ** 3 * x0 + 3 * mt ** 2 * t * c1x + 3 * mt * t ** 2 * c2x + t ** 3 * x1;
68
- let py = mt ** 3 * y0 + 3 * mt ** 2 * t * c1y + 3 * mt * t ** 2 * c2y + t ** 3 * y1;
69
- const amp = shortMove ? Math.min(2, config.noiseAmplitude) : config.noiseAmplitude;
70
- px += rand(-amp, amp);
71
- py += rand(-amp, amp);
72
- points.push({ x: px, y: py, delay: rand(9, 16) });
73
- }
74
- if (!shortMove) {
75
- const over = rand(...config.overshootRange);
76
- const ox = x1 + dx / d * over + rand(-2, 2);
77
- const oy = y1 + dy / d * over + rand(-2, 2);
78
- points.push({ x: ox, y: oy, delay: rand(14, 30) });
79
- points.push({
80
- x: x1 + dx / d * over * 0.4,
81
- y: y1 + dy / d * over * 0.4,
82
- delay: rand(14, 30)
83
- });
84
- }
85
- points.push({ x: x1 + rand(-1, 1), y: y1 + rand(-1, 1), delay: rand(14, 30) });
86
- return points;
87
- }
88
- function landingOffset(width, height, config = DEFAULT_STEALTH_CONFIG) {
89
- const isSmall = Math.min(width, height) < config.smallElementThreshold;
90
- const range = isSmall ? config.landingOffsetSmall : config.landingOffsetLarge;
91
- const dx = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
92
- const dy = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
93
- return { dx, dy };
94
- }
95
- function typingDelay(config = DEFAULT_STEALTH_CONFIG) {
96
- const roll = Math.random();
97
- const r = config.typingRhythm;
98
- if (roll < r.pauseProb) return rand(...r.pauseRange);
99
- if (roll < r.pauseProb + r.fastProb) return rand(...r.fastRange);
100
- return rand(...r.normalRange);
101
- }
102
- var KEY_MAP = {};
103
- for (let i = 97; i <= 122; i++) {
104
- const ch = String.fromCharCode(i);
105
- KEY_MAP[ch] = { key: ch, code: "Key" + ch.toUpperCase(), vk: i - 32 };
106
- }
107
- for (let i = 65; i <= 90; i++) {
108
- const ch = String.fromCharCode(i);
109
- KEY_MAP[ch] = { key: ch, code: "Key" + ch, vk: i, shift: true };
110
- }
111
- for (let i = 48; i <= 57; i++) {
112
- const ch = String.fromCharCode(i);
113
- KEY_MAP[ch] = { key: ch, code: "Digit" + ch, vk: i };
114
- }
115
- Object.assign(KEY_MAP, {
116
- " ": { key: " ", code: "Space", vk: 32 },
117
- ".": { key: ".", code: "Period", vk: 190 },
118
- "-": { key: "-", code: "Minus", vk: 189 },
119
- "@": { key: "@", code: "Digit2", vk: 50, shift: true },
120
- "_": { key: "_", code: "Minus", vk: 189, shift: true }
121
- });
122
- function buildStealthInitScript() {
123
- return [
124
- "(function(){",
125
- ' window.__xbStealthVer="57";',
126
- // 1. AEL event proxy
127
- " var o=EventTarget.prototype.addEventListener;",
128
- " var fc=new InputDeviceCapabilities({firesTouchEvents:false});",
129
- " var _ael=function(t,f){",
130
- " var op=arguments[2];",
131
- ' if(typeof f!=="function")return o.call(this,t,f,op);',
132
- " var w=function(e){",
133
- " if(!e)return f.call(this,e);",
134
- " return f.call(this,new Proxy(e,{get:function(k,p){",
135
- ' if(p==="sourceCapabilities")return fc;',
136
- // S124 修正(d67 攻防):恒 true 是"过度伪装"——站点自己的合成事件
137
- // 也变 true → 直接判定浏览器被篡改(比检测自动化更严重的指纹暴露)。
138
- // 正确策略:透传原始值(CDP Input 事件本来就是 true,JS 合成本来是 false)
139
- // + paste 定向伪装(合成的 paste 在真实场景都是 trusted 的键盘操作产物)
140
- ' if(p==="isTrusted"){',
141
- ' var orig=Reflect.get(k,"isTrusted");',
142
- " if(orig===true)return true;",
143
- ' if(k.type==="paste")return true;',
144
- " return orig;",
145
- " }",
146
- ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])){',
147
- " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;",
148
- " return k[p]+_f;",
149
- " }",
150
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
151
- " }}));",
152
- " };",
153
- " return o.call(this,t,w,op);",
154
- " };",
155
- " EventTarget.prototype.addEventListener=_ael;",
156
- // window.event isTrusted 伪装(S123):AEL 参数包装收不到 window.event
157
- // (它是原始 Event 对象的隐式引用)。定义 getter 拦截读取。
158
- " try{",
159
- ' var _weDesc=Object.getOwnPropertyDescriptor(Window.prototype,"event");',
160
- " if(_weDesc&&_weDesc.get){",
161
- " var _origWeGet=_weDesc.get;",
162
- ' Object.defineProperty(Window.prototype,"event",{',
163
- " configurable:true,",
164
- " get:function(){",
165
- " var ev=_origWeGet.call(this);",
166
- " if(!ev)return ev;",
167
- " return new Proxy(ev,{get:function(k,p){",
168
- ' if(p==="isTrusted"){',
169
- ' var orig=Reflect.get(k,"isTrusted");',
170
- " if(orig===true)return true;",
171
- ' if(k.type==="paste")return true;',
172
- " return orig;",
173
- " }",
174
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
175
- " }});",
176
- " }",
177
- " });",
178
- " }",
179
- " }catch(e){}",
180
- // 2. Screen override (prototype-level, not instance-level)
181
- " var _gw=function(){return 1728};",
182
- " var _gh=function(){return 1117};",
183
- " var _gah=function(){return 1092};",
184
- ' Object.defineProperty(Screen.prototype,"width",{get:_gw,configurable:true});',
185
- ' Object.defineProperty(Screen.prototype,"height",{get:_gh,configurable:true});',
186
- ' Object.defineProperty(Screen.prototype,"availWidth",{get:_gw,configurable:true});',
187
- ' Object.defineProperty(Screen.prototype,"availHeight",{get:_gah,configurable:true});',
188
- // S174: UA Headless 标记清洗——headless launch 的 UA 含 HeadlessChrome/xxx
189
- // (最高频检测面),同步清洗 userAgent/appVersion/userAgentData(brands+高熵值)。
190
- // 原型+实例双层覆写(S172 模式)。
191
- " try{",
192
- ' var fixUA=function(ua){return String(ua).replace("HeadlessChrome","Chrome");};',
193
- ' 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;});};',
194
- ' var _nuad=Object.getOwnPropertyDescriptor(Navigator.prototype,"userAgentData");',
195
- " var wrapUAD=function(uad){",
196
- " if(!uad||uad.__xbUA)return uad;",
197
- " try{",
198
- ' Object.defineProperty(uad,"brands",{get:function(){return fixBrands(_nuad.get.call(navigator).brands);},configurable:true});',
199
- " var _ghev=uad.getHighEntropyValues.bind(uad);",
200
- " uad.getHighEntropyValues=function(hints){return _ghev(hints).then(function(v){",
201
- ' 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]);}',
202
- " return o;});};",
203
- " uad.__xbUA=true;",
204
- " }catch(e){}",
205
- " return uad;",
206
- " };",
207
- ' var _nua=Object.getOwnPropertyDescriptor(Navigator.prototype,"userAgent");',
208
- " if(_nua&&_nua.get){",
209
- " var _nuag=function(){return fixUA(_nua.get.call(this));};",
210
- ' _nuag.toString=function(){return "function get userAgent() { [native code] }";};',
211
- ' Object.defineProperty(Navigator.prototype,"userAgent",{get:_nuag,configurable:true});',
212
- " }",
213
- ' Object.defineProperty(navigator,"userAgent",{get:function(){return fixUA(_nua?_nua.get.call(this):"");},configurable:true});',
214
- " if(_nuad&&_nuad.get){",
215
- " var _nuadg=function(){return wrapUAD(_nuad.get.call(this));};",
216
- ' _nuadg.toString=function(){return "function get userAgentData() { [native code] }";};',
217
- ' Object.defineProperty(Navigator.prototype,"userAgentData",{get:_nuadg,configurable:true});',
218
- " }",
219
- " }catch(e){}",
220
- // hasFocus 与 visibilityState 联动(d29):恒 true 在 hidden 标签下暴露
221
- // —— 真实浏览器失焦/后台时 hasFocus=false
222
- // S172: 原型层覆写——实例赋值可被 Document.prototype.hasFocus.call(document) 逃逸
223
- ' Document.prototype.hasFocus=function(){return document.visibilityState==="visible";};',
224
- // 4. Canvas/WebGL fingerprint: per-session stable noise (d20).
225
- // Headless software raster differs subtly from Chrome GPU raster —
226
- // toDataURL hashes fingerprint the rasterizer. Inject a stable
227
- // (per-page-load) subpixel shift into fillText so hashes look like a
228
- // distinct-but-consistent real GPU, and hide the HEADLESS tell in
229
- // WebGL renderer strings.
230
- " var _seed=Math.floor(Math.random()*2147483647);",
231
- " var _prng=function(){_seed=(_seed*48271)%2147483647;return _seed/2147483647;};",
232
- " var _dx=(_prng()*0.4-0.2).toFixed(3)*1, _dy=(_prng()*0.4-0.2).toFixed(3)*1;",
233
- " var _fillText=CanvasRenderingContext2D.prototype.fillText;",
234
- " CanvasRenderingContext2D.prototype.fillText=function(t,x,y,m){",
235
- " return _fillText.call(this,t,x+_dx,y+_dy,m);",
236
- " };",
237
- " var _toDataURL=HTMLCanvasElement.prototype.toDataURL;",
238
- " HTMLCanvasElement.prototype.toDataURL=function(){",
239
- ' var ctx=this.getContext("2d");',
240
- " if(ctx){var d=ctx.getImageData(0,0,Math.min(this.width,2),Math.min(this.height,2));",
241
- " for(var i=0;i<d.data.length;i+=4){if(d.data[i+3]>0){d.data[i]^=1;break;}}",
242
- " ctx.putImageData(d,0,0);}",
243
- " return _toDataURL.apply(this,arguments);",
244
- " };",
245
- " try{",
246
- " var _gl=HTMLCanvasElement.prototype.getContext;",
247
- " HTMLCanvasElement.prototype.getContext=function(t,o){",
248
- " var c=_gl.call(this,t,o);",
249
- ' if(c&&(t==="webgl"||t==="experimental-webgl")&&c.getParameter){',
250
- " var _gp=c.getParameter.bind(c);",
251
- " c.getParameter=function(p){",
252
- " var v=_gp(p);",
253
- ' if(typeof v==="string"&&/SwiftShader|Software|Rasterizer|Headless/i.test(v))',
254
- ' return "ANGLE (Apple, ANGLE Metal Renderer: Apple M2 Max, Unspecified Version)";',
255
- " return v;};}",
256
- " return c;};",
257
- " }catch(e){}",
258
- // 5. AudioContext fingerprint: per-load stable micro-noise on channel
259
- // data (d21). DSP sum differences between headless software audio and
260
- // real hardware audio are a classic fingerprint — add ±1e-7 level
261
- // noise (inaudible, changes the sum hash).
262
- " try{",
263
- " var _gcd=AudioBuffer.prototype.getChannelData;",
264
- " AudioBuffer.prototype.getChannelData=function(ch){",
265
- " var d=_gcd.call(this,ch);",
266
- ' var key="__xb_audio_"+ch;',
267
- " if(!this[key]){",
268
- " this[key]=true;",
269
- " for(var i=0;i<d.length;i+=997){d[i]=d[i]+(_prng()-0.5)*2e-7;}",
270
- " }",
271
- " return d;",
272
- " };",
273
- " var _gffd=AnalyserNode.prototype.getFloatFrequencyData;",
274
- " AnalyserNode.prototype.getFloatFrequencyData=function(arr){",
275
- " _gffd.call(this,arr);",
276
- " for(var i=0;i<arr.length;i+=31){arr[i]=arr[i]+(_prng()-0.5)*0.01;}",
277
- " };",
278
- " var _gfbd=AnalyserNode.prototype.getByteFrequencyData;",
279
- " AnalyserNode.prototype.getByteFrequencyData=function(arr){",
280
- " _gfbd.call(this,arr);",
281
- " for(var i=0;i<arr.length;i+=31){arr[i]=(arr[i]+((_prng()*3)|0))&255;}",
282
- " };",
283
- " }catch(e){}",
284
- // 3b. Font metrics + speechSynthesis + battery (d22): headless tells
285
- " try{",
286
- ' var _tmw=Object.getOwnPropertyDescriptor(TextMetrics.prototype,"width");',
287
- " if(_tmw&&_tmw.get){",
288
- " // S172: \u539F\u578B\u5C42\u8986\u5199\u2014\u2014\u5B9E\u4F8B(m)\u8986\u5199\u53EF\u88AB TextMetrics.prototype.width getter \u9003\u9038",
289
- ' Object.defineProperty(TextMetrics.prototype,"width",{get:function(){return _tmw.get.call(this)+_dx*0.01;},configurable:true});',
290
- " }",
291
- " }catch(e){}",
292
- " try{",
293
- ' var _fakeVoices=["Alex","Daniel","Karen","Moira","Ralph","Samantha","Ting-Ting","Mei-Jia","Sinji","Yunda"];',
294
- // S172: 原型层覆写——实例赋值可被 SpeechSynthesis.prototype.getVoices.call() 逃逸
295
- " var _sv=SpeechSynthesis.prototype.getVoices;",
296
- " SpeechSynthesis.prototype.getVoices=function(){",
297
- " var real=_sv.call(this);",
298
- " if(real&&real.length>50)return real;",
299
- // 注意阈值从 0 改 50:iframe 原生约 10 个 —— 原阈值下 iframe 返回原生 10 个
300
- // 而不是伪装 180(d33 暴露)。>50 = 主文档伪装列表已生效,其余返回伪装。
301
- ' 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};});',
302
- " };",
303
- // d33 修复:iframe 的 speechSynthesis 是独立实例(主文档 hook 不可达)——
304
- // 轮询同源 iframe,对其 contentWindow 的原型同样 patch(S172: 原型层,防逃逸)
305
- " try{",
306
- " var _piv=function(){",
307
- ' var frs=document.querySelectorAll("iframe");',
308
- " for(var i=0;i<frs.length;i++){try{",
309
- " var cw=frs[i].contentWindow;",
310
- " if(!cw||!cw.speechSynthesis||cw.speechSynthesis.__xbP)continue;",
311
- " cw.speechSynthesis.__xbP=true;",
312
- " var _sv2=cw.SpeechSynthesis.prototype.getVoices;",
313
- " cw.SpeechSynthesis.prototype.getVoices=function(){var r=_sv2.call(this);if(r&&r.length>50)return r;",
314
- ' 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};});};',
315
- " }catch(e2){}}",
316
- " };",
317
- " setInterval(_piv,2000);",
318
- " var _mo=new MutationObserver(function(muts){",
319
- " for(var k=0;k<muts.length;k++){var ns=muts[k].addedNodes;",
320
- ' for(var q=0;q<ns.length;q++){if(ns[q].tagName==="IFRAME")setTimeout(_piv,20);}}',
321
- " });",
322
- " _mo.observe(document.documentElement,{childList:true,subtree:true});",
323
- " }catch(e){}",
324
- " }catch(e){}",
325
- " try{",
326
- " var _gb=navigator.getBattery.bind(navigator);",
327
- " navigator.getBattery=function(){",
328
- " return _gb().then(function(b){",
329
- ' Object.defineProperty(b,"charging",{get:function(){return true;},configurable:true});',
330
- " return b;});",
331
- " };",
332
- " }catch(e){}",
333
- // 3c. WebRTC local IP leak guard (d23): headless STUN candidates can
334
- // expose host IPs; mDNS-only candidates are the modern Chrome default.
335
- " try{",
336
- " var _oc=RTCPeerConnection.prototype.createOffer;",
337
- " RTCPeerConnection.prototype.createOffer=function(){",
338
- " var p=_oc.apply(this,arguments);",
339
- " var self=this;",
340
- " return p.then(function(offer){",
341
- ' offer.sdp=offer.sdp.split(String.fromCharCode(10)).filter(function(l){return l.indexOf("typ host")<0}).join(String.fromCharCode(10));',
342
- " return offer;});",
343
- " };",
344
- " }catch(e){}",
345
- // 3d-2. performance.now precision clamp (d34): full-precision timestamps
346
- // (11 decimals) differ from site-isolation-clamped real Chrome (~100μs).
347
- " try{",
348
- " var _pn=Performance.prototype.now;",
349
- " // S172: \u539F\u578B\u5C42\u8986\u5199\u2014\u2014\u5B9E\u4F8B\u8D4B\u503C\u53EF\u88AB Performance.prototype.now.call(performance) \u9003\u9038",
350
- " Performance.prototype.now=function(){return Math.round(_pn.call(this)*10)/10;};",
351
- ' var _pto=Object.getOwnPropertyDescriptor(Performance.prototype,"timeOrigin");',
352
- " if(_pto&&_pto.get){",
353
- " // 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",
354
- " // \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",
355
- " // \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",
356
- " var _toff=Math.floor((_seed/2147483647)*600000-300000);",
357
- " var _tog=function(){return _pto.get.call(performance)+_toff;};",
358
- ' _tog.toString=function(){return "function get timeOrigin() { [native code] }";};',
359
- " // S172 \u5BA1\u8BA1\uFF1A\u5B9E\u4F8B\u8986\u5199\u53EF\u88AB\u539F\u578B getter \u9003\u9038\u2014\u2014\u539F\u578B\u5C42\u8986\u5199",
360
- ' Object.defineProperty(Performance.prototype,"timeOrigin",{get:_tog,configurable:true});',
361
- ' Object.defineProperty(performance,"timeOrigin",{get:_tog,configurable:true});',
362
- " }",
363
- " }catch(e){}",
364
- // 3f. getCoalescedEvents 合成(d47):真实鼠标 125Hz 采样被浏览器按帧合并,
365
- // 快速移动时 pointermove.getCoalescedEvents() 返回 2~6 个事件(群内
366
- // ≈8ms);CDP Input 逐事件派发不走合并管线,coalesced>1 恒为 0(结构性
367
- // 暴露,间隔模拟救不了——实测 Chrome 帧对齐时 CDP 连发事件被直接丢弃
368
- // 而非合并)。按 125Hz 物理插值合成 coalesced 群:期望样本数 = dt/8ms-1,
369
- // 合成事件用真 PointerEvent 构造 + 实例级 isTrusted/timeStamp 遮蔽。
370
- " try{",
371
- " if(window.PointerEvent&&PointerEvent.prototype.getCoalescedEvents){",
372
- " var _gce=PointerEvent.prototype.getCoalescedEvents;",
373
- " var _lm=null;",
374
- " var _gceH=function(){",
375
- " var list=_gce.call(this);",
376
- ' if(this.type!=="pointermove"||!this.isTrusted)return list;',
377
- " var cur={x:this.clientX,y:this.clientY,ts:this.timeStamp};",
378
- " var out=null;",
379
- " if((!list||list.length<2)&&_lm){",
380
- " var dt=cur.ts-_lm.ts,dx=cur.x-_lm.x,dy=cur.y-_lm.y;",
381
- // dt 长(帧丢弃后)不代表群覆盖整个 dt —— 真实 coalesced 群只覆盖
382
- // 最后一帧窗口(≤16.7ms,群内 ≈8ms=125Hz)。合成群从自身往回推 8ms
383
- // 链,位移取末端占比(span/dt,dt 远大于 span 时位移趋零=丢弃后实况)。
384
- " var expN=Math.floor(dt/8)-1;",
385
- // dt<12ms(不足一帧+采样周期)时真实浏览器不会产生合并群 ——
386
- // 单采样帧 coalesced=1,强行合成会出现 ~2ms 的超物理群内间隔。
387
- " if(expN>0&&dt>=12&&Math.random()>0.15){",
388
- " var n=Math.min(4,expN+(Math.random()<0.3?1:0));",
389
- " var span=Math.min(dt,n*8.3);",
390
- " var frac=Math.min(1,span/Math.max(dt,1));",
391
- " out=[];",
392
- " for(var i=1;i<=n;i++){",
393
- // k=距自身的步数(含自身共 n+1 个事件,相邻恒 ≈8.3ms=125Hz 周期)
394
- " var k=n+1-i;",
395
- ' var ev=new PointerEvent("pointermove",{',
396
- ' pointerId:this.pointerId,pointerType:"mouse",isPrimary:this.isPrimary,',
397
- " clientX:cur.x-dx*frac*(k/(n+1))+(Math.random()-0.5)*1.5,",
398
- " clientY:cur.y-dy*frac*(k/(n+1))+(Math.random()-0.5)*1.5,",
399
- " screenX:this.screenX,screenY:this.screenY,",
400
- " buttons:this.buttons,button:this.button,",
401
- " bubbles:true,cancelable:true,composed:true,",
402
- " width:this.width,height:this.height,pressure:this.pressure,",
403
- " tiltX:this.tiltX,tiltY:this.tiltY,twist:this.twist});",
404
- " var tsV=cur.ts-k*8.3-Math.random()*1.2;",
405
- // isTrusted/timeStamp 是实例不可配置属性(defineProperty 抛
406
- // "Cannot redefine"),改 Proxy 包装:getPrototypeOf/ownKeys 透传,
407
- // instanceof 与属性枚举行为与真事件一致。IIFE 捕获本次循环的 tsV
408
- // 快照 —— var 提升会让所有 Proxy 闭包共享最后一次赋值(实测四个
409
- // 合成事件同时间戳、群内间隔塌到 ~2ms)。
410
- " out.push((function(e2,t2){return new Proxy(e2,{get:function(t,p){",
411
- ' if(p==="isTrusted")return true;',
412
- ' if(p==="timeStamp")return t2;',
413
- ' var v=Reflect.get(t,p);return typeof v==="function"?v.bind(t):v;',
414
- " }});})(ev,tsV));",
415
- " }",
416
- " out.push(this);",
417
- " }",
418
- " }",
419
- " _lm=cur;",
420
- " return out||list;",
421
- " };",
422
- " PointerEvent.prototype.getCoalescedEvents=_gceH;",
423
- // name 反查伪装:var _gceH=fn 的具名推断会暴露 hook(原生 name 是
424
- // "getCoalescedEvents")——toString 白名单管不到 name 属性。
425
- ' try{Object.defineProperty(_gceH,"name",{value:"getCoalescedEvents"});}catch(e){}',
426
- " }",
427
- " }catch(e){}",
428
- // 3d. Chrome object depth (d24): automation fakes usually only set
429
- // window.chrome = {}; deep checks hit app.run/runtime/csi/loadTimes.
430
- " try{",
431
- " if(window.chrome){",
432
- ' 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"}};',
433
- ' 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};',
434
- " if(!window.chrome.csi)window.chrome.csi=function(){return{};}",
435
- " if(!window.chrome.loadTimes)window.chrome.loadTimes=function(){return{};}",
436
- " }",
437
- " }catch(e){}",
438
- // 3e. Font availability patch (d25): headless Chromium misses some system
439
- // fonts (e.g. Menlo on macOS) that real Chrome has. Register a FontFace
440
- // aliasing the missing font to a local() equivalent so offsetWidth-based
441
- // font probing sees the same availability as the faked environment.
442
- " try{",
443
- ' var _fontAliases=[["Menlo","Courier New"],["SF Mono","Menlo"],["Segoe UI","Helvetica"]];',
444
- " _fontAliases.forEach(function(pa){",
445
- ' try{var ff=new FontFace(pa[0],"local("+JSON.stringify(pa[1])+")");',
446
- " document.fonts.add(ff);ff.load();}catch(e2){}",
447
- " });",
448
- " }catch(e){}",
449
- // 3g. Notification.requestPermission 延迟(d62):headless 无原生横幅,
450
- // request 瞬回 denied —— 真机 request 会 pending 在横幅上数秒到分钟。
451
- // 延迟 2-6s 再 resolve,模拟横幅期(用户"看了下然后拒绝")。
452
- " try{",
453
- " if(window.Notification&&Notification.requestPermission){",
454
- " var _nrp=Notification.requestPermission.bind(Notification);",
455
- " Notification.requestPermission=function(cb){",
456
- " return new Promise(function(res){",
457
- " setTimeout(function(){_nrp().then(function(r){if(cb)try{cb(r)}catch(e){}res(r);});},2000+Math.random()*4000);",
458
- " });",
459
- " };",
460
- " }",
461
- " }catch(e){}",
462
- // 3. toString disguise (name-list based)
463
- " var _ts=Function.prototype.toString;",
464
- " var _hf=document.hasFocus;",
465
- " Function.prototype.toString=function(){",
466
- ' if(this===_ael)return"function addEventListener(type, callback) { [native code] }";',
467
- ' if(this===_hf)return"function hasFocus() { [native code] }";',
468
- ' if(this===_gw)return"function get width() { [native code] }";',
469
- ' if(this===_gh)return"function get height() { [native code] }";',
470
- ' if(this===_gah)return"function get availHeight() { [native code] }";',
471
- ' if(this===CanvasRenderingContext2D.prototype.fillText)return"function fillText() { [native code] }";',
472
- ' if(this===HTMLCanvasElement.prototype.toDataURL)return"function toDataURL() { [native code] }";',
473
- ' if(this===AnalyserNode.prototype.getFloatFrequencyData)return"function getFloatFrequencyData() { [native code] }";',
474
- ' if(this===AudioBuffer.prototype.getChannelData)return"function getChannelData() { [native code] }";',
475
- ' if(this===_gceH)return"function getCoalescedEvents() { [native code] }";',
476
- ' if(this===Document.prototype.hasFocus)return"function hasFocus() { [native code] }";',
477
- ' if(this===Performance.prototype.now)return"function now() { [native code] }";',
478
- ' if(this===SpeechSynthesis.prototype.getVoices)return"function getVoices() { [native code] }";',
479
- " return _ts.call(this);",
480
- " };",
481
- // 4. onclick prototype hijack (dual-stream consistency)
482
- " var _ba=function(k,p){",
483
- ' if(p==="isTrusted"){',
484
- ' var orig=Reflect.get(k,"isTrusted");',
485
- " if(orig===true)return true;",
486
- ' if(k.type==="paste")return true;',
487
- " return orig;",
488
- " }",
489
- ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])&&k.isTrusted===true){',
490
- " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;return k[p]+_f;",
491
- " }",
492
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
493
- " };",
494
- ' Object.defineProperty(Document.prototype,"onclick",{',
495
- " configurable:true,",
496
- " get:function(){var raw=this.__ocRaw||null;if(!raw)return null;var self=this;",
497
- " return function(e){return raw.call(self,new Proxy(e,{get:function(k,p){return _ba(k,p)}}))}},",
498
- " set:function(fn){this.__ocRaw=fn}",
499
- " });",
500
- "})()"
501
- ].join("\n");
502
- }
503
-
504
33
  // src/cdp-driver/mouse.ts
505
34
  var XBMouseImpl = class {
506
35
  conn;
@@ -552,7 +81,7 @@ var XBMouseImpl = class {
552
81
  } else {
553
82
  await this.move(tx, ty);
554
83
  }
555
- await this.down({ button });
84
+ await this.down({ button, clickCount: opts.clickCount ?? 1 });
556
85
  await sleep(stealth ? rand(...DEFAULT_STEALTH_CONFIG.pressDuration) : opts.delay ?? 0);
557
86
  const rx = stealth ? this._x + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._x;
558
87
  const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
@@ -576,7 +105,9 @@ var XBMouseImpl = class {
576
105
  x: this._x,
577
106
  y: this._y,
578
107
  button,
579
- clickCount: 1
108
+ // r23: press 必须与 release 声明同一 clickCount——Chrome 按序列计数
109
+ // 合成 click/dblclick,press 缺声明会把计数器重置(dblclick 永不合成)
110
+ clickCount: opts.clickCount ?? 1
580
111
  });
581
112
  }
582
113
  async up(opts = {}) {
@@ -587,7 +118,7 @@ var XBMouseImpl = class {
587
118
  x: this._x,
588
119
  y: this._y,
589
120
  button,
590
- clickCount: 1
121
+ clickCount: opts.clickCount ?? 1
591
122
  });
592
123
  }
593
124
  async move(x, y, opts = {}) {
@@ -763,7 +294,7 @@ var XBKeyboardImpl = class {
763
294
  if (wrong && wrong !== char) {
764
295
  await this.dispatchKeySequence(resolveKeyMapping(wrong), stealth);
765
296
  await sleep2(rand(120, 420));
766
- await this.dispatchKeySequence(KEY_MAP2.Backspace, stealth);
297
+ await this.dispatchKeySequence(KEY_MAP.Backspace, stealth);
767
298
  }
768
299
  }
769
300
  await this.dispatchKeySequence(resolveKeyMapping(char), stealth);
@@ -866,7 +397,7 @@ var XBKeyboardImpl = class {
866
397
  }
867
398
  };
868
399
  function resolveKeyMapping(key) {
869
- if (KEY_MAP2[key]) return KEY_MAP2[key];
400
+ if (KEY_MAP[key]) return KEY_MAP[key];
870
401
  if (key.length === 1) {
871
402
  const lower = key.toLowerCase();
872
403
  if (lower >= "a" && lower <= "z") {
@@ -883,7 +414,7 @@ function resolveKeyMapping(key) {
883
414
  }
884
415
  return { key, code: key };
885
416
  }
886
- var KEY_MAP2 = {
417
+ var KEY_MAP = {
887
418
  Enter: { key: "Enter", code: "Enter", text: "\r", keyCode: 13 },
888
419
  Tab: { key: "Tab", code: "Tab", text: " ", keyCode: 9 },
889
420
  Escape: { key: "Escape", code: "Escape", keyCode: 27 },
@@ -1244,6 +775,14 @@ var XBLocatorImpl = class _XBLocatorImpl {
1244
775
  await waitForActionable(this.page, this.selector, opts);
1245
776
  await scrollIntoView(this.page, this.selector);
1246
777
  await this.click({ ...opts });
778
+ await this.page.evaluate(`
779
+ (function() {
780
+ const el = ${this._q(this.selector)};
781
+ if (!el) return;
782
+ if (document.activeElement !== el) el.focus();
783
+ if ((el.value || el.textContent || '') !== '') document.execCommand('selectAll');
784
+ })()
785
+ `);
1247
786
  if (process.env.XBROWSER_STEALTH !== "off" && value.length >= 40 && process.env.XBROWSER_FILL_TYPE !== "type") {
1248
787
  try {
1249
788
  const { pasteViaClipboard, syntheticPaste } = await import("./clipboard-XRP54ENE.js");
@@ -1999,6 +1538,189 @@ var XBPageImpl = class _XBPageImpl {
1999
1538
  await this.conn.send("Network.enable", void 0, this.sessionId);
2000
1539
  await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
2001
1540
  });
1541
+ if (this._contextImpl.ignoreHTTPSErrors) {
1542
+ await this.conn.send("Security.enable", void 0, this.sessionId).catch(() => {
1543
+ });
1544
+ await this.conn.send("Security.setIgnoreCertificateErrors", { ignore: true }, this.sessionId).catch(() => {
1545
+ });
1546
+ }
1547
+ if (this._contextImpl.httpCredentials) {
1548
+ await this.conn.send("Fetch.enable", {
1549
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
1550
+ handleAuthRequests: true
1551
+ }, this.sessionId).catch(() => {
1552
+ });
1553
+ this._subscriptions.push(
1554
+ this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
1555
+ if (this._interceptionEnabled) return;
1556
+ const p = params;
1557
+ this.conn.send("Fetch.continueRequest", { requestId: p.requestId }, this.sessionId).catch(() => {
1558
+ });
1559
+ })
1560
+ );
1561
+ this._subscriptions.push(
1562
+ this.conn.subscribe("Fetch.authRequired", this.sessionId, (params) => {
1563
+ const p = params;
1564
+ const creds = this._contextImpl.httpCredentials;
1565
+ this.conn.send("Fetch.continueWithAuth", {
1566
+ requestId: p.requestId,
1567
+ authChallengeResponse: creds ? { response: "ProvideCredentials", username: creds.username, password: creds.password } : { response: "CancelAuth" }
1568
+ }, this.sessionId).catch(() => {
1569
+ });
1570
+ })
1571
+ );
1572
+ }
1573
+ await this.conn.send("Page.addScriptToEvaluateOnNewDocument", {
1574
+ source: [
1575
+ "try { window.print = function() {}; window.__xb_print_suppressed = true; } catch (e) {}",
1576
+ "try {",
1577
+ " if (window.showOpenFilePicker) {",
1578
+ " var __xb_mkHandle = function(name, content) {",
1579
+ ' var file = new File([content], name, { type: "text/plain" });',
1580
+ " return {",
1581
+ ' kind: "file", name: name,',
1582
+ " getFile: function() { return Promise.resolve(file); },",
1583
+ " createWritable: function() { return Promise.resolve({ write: function() { return Promise.resolve(); }, close: function() { return Promise.resolve(); } }); },",
1584
+ " isSameEntry: function() { return Promise.resolve(false); },",
1585
+ ' queryPermission: function() { return Promise.resolve("granted"); },',
1586
+ ' requestPermission: function() { return Promise.resolve("granted"); },',
1587
+ " };",
1588
+ " };",
1589
+ " window.showOpenFilePicker = function() {",
1590
+ ' return Promise.resolve([__xb_mkHandle("xbrowser-stub.txt", "xbrowser fs access stub")]);',
1591
+ " };",
1592
+ " window.showSaveFilePicker = function() {",
1593
+ ' return Promise.resolve(__xb_mkHandle("xbrowser-stub-save.txt", ""));',
1594
+ " };",
1595
+ " window.showDirectoryPicker = function() {",
1596
+ " var emptyIter = function() { return [][Symbol.iterator](); };",
1597
+ " return Promise.resolve({",
1598
+ ' kind: "directory", name: "xbrowser-stub-dir",',
1599
+ " values: emptyIter, entries: emptyIter, keys: emptyIter,",
1600
+ ' getDirectoryHandle: function() { return Promise.reject(new Error("stub empty dir")); },',
1601
+ ' getFileHandle: function() { return Promise.reject(new Error("stub empty dir")); },',
1602
+ " isSameEntry: function() { return Promise.resolve(false); },",
1603
+ ' queryPermission: function() { return Promise.resolve("granted"); },',
1604
+ ' requestPermission: function() { return Promise.resolve("granted"); },',
1605
+ " });",
1606
+ " };",
1607
+ " window.__xb_fs_stub_installed = true;",
1608
+ " }",
1609
+ "} catch (e) {}",
1610
+ // sup-s7: 右键菜单压制——headful 下 CDP 右键弹浏览器原生菜单(CDP
1611
+ // 无法关闭浏览器 UI)。document 捕获阶段 preventDefault 抑制原生
1612
+ // 菜单;不阻断传播,录制 contextmenu 事件与页面自定义菜单不受影响。
1613
+ "try {",
1614
+ ' document.addEventListener("contextmenu", function(e) { e.preventDefault(); }, true);',
1615
+ " window.__xb_ctxmenu_suppressed = true;",
1616
+ "} catch (e) {}",
1617
+ // sup-s10: Notification 守卫——new Notification() 弹 OS 级系统横幅
1618
+ // (headful 污染屏幕,等待通知交互的流程挂起)。no-op 包装但保
1619
+ // API 形状:permission/granted、requestPermission→granted、实例
1620
+ // title/close 可用——页面通知流程无感继续。
1621
+ "try {",
1622
+ " var XBN = function Notification(title, options) {",
1623
+ " this.title = title;",
1624
+ ' this.body = (options && options.body) || "";',
1625
+ ' this.tag = (options && options.tag) || "";',
1626
+ " this.onclick = null; this.onshow = null; this.onerror = null; this.onclose = null;",
1627
+ " };",
1628
+ " XBN.prototype.close = function() {};",
1629
+ ' XBN.permission = "granted";',
1630
+ ' XBN.requestPermission = function() { return Promise.resolve("granted"); };',
1631
+ " XBN.maxActions = (window.Notification && window.Notification.maxActions) || 2;",
1632
+ " window.Notification = XBN;",
1633
+ " window.__xb_notification_suppressed = true;",
1634
+ "} catch (e) {}",
1635
+ // sup-W1: WebAPI 选择器/配对框家族 stub(1/7 Serial)——
1636
+ // navigator.serial.requestPort() 弹浏览器原生串口选择器(CDP 无法
1637
+ // 拦截),headless 下 promise 挂起。stub 返回 rejected Promise
1638
+ // (NotFoundError),页面 catch 分支接管、流程继续。
1639
+ "try {",
1640
+ " if (navigator.serial) {",
1641
+ " navigator.serial.requestPort = function() {",
1642
+ ' return Promise.reject(new DOMException("xbrowser serial stub", "NotFoundError"));',
1643
+ " };",
1644
+ " window.__xb_serial_stubbed = true;",
1645
+ " }",
1646
+ "} catch (e) {}",
1647
+ // sup-W2: WebAPI stub(2/7 USB)——requestDevice 弹原生设备配对框,
1648
+ // 同 Serial pattern:rejected Promise(NotFoundError),catch 接管。
1649
+ "try {",
1650
+ " if (navigator.usb) {",
1651
+ " navigator.usb.requestDevice = function() {",
1652
+ ' return Promise.reject(new DOMException("xbrowser usb stub", "NotFoundError"));',
1653
+ " };",
1654
+ " window.__xb_usb_stubbed = true;",
1655
+ " }",
1656
+ "} catch (e) {}",
1657
+ // sup-W3: WebAPI stub(3/7 Bluetooth)——requestDevice 弹原生蓝牙
1658
+ // 配对框,同 Serial/USB pattern:rejected Promise(NotFoundError)。
1659
+ // CI linux headless 下 navigator.bluetooth 原生不存在——缺失时合成
1660
+ // 对象再包装,保证跨平台语义一致(requestDevice 恒 rejected)。
1661
+ "try {",
1662
+ " if (!navigator.bluetooth) {",
1663
+ ' try { Object.defineProperty(navigator, "bluetooth", { value: {}, configurable: true }); } catch (e) {}',
1664
+ " }",
1665
+ " if (navigator.bluetooth) {",
1666
+ " navigator.bluetooth.requestDevice = function() {",
1667
+ ' return Promise.reject(new DOMException("xbrowser ble stub", "NotFoundError"));',
1668
+ " };",
1669
+ " window.__xb_ble_stubbed = true;",
1670
+ " }",
1671
+ "} catch (e) {}",
1672
+ // sup-W4: WebAPI stub(4/7 HID)——requestDevices 弹原生 HID 设备
1673
+ // 选择器,同家族 pattern:rejected Promise(NotFoundError)。
1674
+ "try {",
1675
+ " if (navigator.hid) {",
1676
+ " navigator.hid.requestDevices = function() {",
1677
+ ' return Promise.reject(new DOMException("xbrowser hid stub", "NotFoundError"));',
1678
+ " };",
1679
+ " window.__xb_hid_stubbed = true;",
1680
+ " }",
1681
+ "} catch (e) {}",
1682
+ // sup-W5: WebAPI stub(5/7 WakeLock)——request('screen') 在无用户
1683
+ // 激活/权限时挂起或拒绝,等待 wake 事件的流程死锁。stub 返回合成
1684
+ // sentinel(release 可用,不真实持锁)。
1685
+ "try {",
1686
+ " if (navigator.wakeLock) {",
1687
+ " navigator.wakeLock.request = function() {",
1688
+ " return Promise.resolve({",
1689
+ " released: false,",
1690
+ ' type: "screen",',
1691
+ " release: function() { this.released = true; return Promise.resolve(); },",
1692
+ " addEventListener: function() {},",
1693
+ " removeEventListener: function() {},",
1694
+ " });",
1695
+ " };",
1696
+ " window.__xb_wakelock_stubbed = true;",
1697
+ " }",
1698
+ "} catch (e) {}",
1699
+ // sup-W6: WebAPI stub(6/7 IdleDetector)——start() 需权限气泡授权
1700
+ // 才能继续,headless 下挂起。stub 返回 rejected(NotAllowedError),
1701
+ // 页面 catch 分支接管。
1702
+ "try {",
1703
+ " if (window.IdleDetector) {",
1704
+ " IdleDetector.start = function() {",
1705
+ ' return Promise.reject(new DOMException("xbrowser idle stub", "NotAllowedError"));',
1706
+ " };",
1707
+ " window.__xb_idle_stubbed = true;",
1708
+ " }",
1709
+ "} catch (e) {}",
1710
+ // sup-W7: WebAPI stub(7/7 PaymentRequest)——show() 弹浏览器支付
1711
+ // 面板(无用户交互不关闭),headless 下 promise 挂起。stub 返回
1712
+ // rejected(NotAllowedError),页面 catch 分支接管。
1713
+ "try {",
1714
+ " if (window.PaymentRequest) {",
1715
+ " PaymentRequest.prototype.show = function() {",
1716
+ ' return Promise.reject(new DOMException("xbrowser pay stub", "NotAllowedError"));',
1717
+ " };",
1718
+ " window.__xb_pay_stubbed = true;",
1719
+ " }",
1720
+ "} catch (e) {}"
1721
+ ].join("\n")
1722
+ }, this.sessionId).catch(() => {
1723
+ });
2002
1724
  this.setupPageEvents();
2003
1725
  this.setupNetworkEvents();
2004
1726
  this.setupConsoleEvents();
@@ -2030,7 +1752,7 @@ var XBPageImpl = class _XBPageImpl {
2030
1752
  try {
2031
1753
  await this.conn.send(
2032
1754
  "Page.addScriptToEvaluateOnNewDocument",
2033
- { source: buildStealthInitScript() },
1755
+ { source: buildStealthInitScript({ ...DEFAULT_STEALTH_CONFIG, ...this._contextImpl.stealthConfig ?? {} }) },
2034
1756
  this.sessionId
2035
1757
  );
2036
1758
  } catch {
@@ -2439,7 +2161,9 @@ Last error: ${lastError.message}` : "";
2439
2161
  await this.locator(selector).click(opts);
2440
2162
  }
2441
2163
  async dblclick(selector, opts = {}) {
2442
- await this.locator(selector).click({ ...opts, clickCount: 2 });
2164
+ const locator = this.locator(selector);
2165
+ await locator.click({ ...opts, clickCount: 1 });
2166
+ await locator.click({ ...opts, clickCount: 2 });
2443
2167
  }
2444
2168
  async fill(selector, value, opts = {}) {
2445
2169
  await this.locator(selector).fill(value, opts);
@@ -2556,6 +2280,26 @@ Last error: ${lastError.message}` : "";
2556
2280
  );
2557
2281
  this._viewportSize = size;
2558
2282
  }
2283
+ /**
2284
+ * env-E2: 缩放变异——deviceScaleFactor 切换(CSS 像素坐标空间不变,
2285
+ * 物理像素翻倍)。保留当前 CSS 视口尺寸,只换 DSF。
2286
+ */
2287
+ async setDeviceScaleFactor(dsf) {
2288
+ const size = this._viewportSize ?? await this.evaluate(
2289
+ "({ width: window.innerWidth, height: window.innerHeight })"
2290
+ );
2291
+ await this.conn.send(
2292
+ "Emulation.setDeviceMetricsOverride",
2293
+ {
2294
+ width: size.width,
2295
+ height: size.height,
2296
+ deviceScaleFactor: dsf,
2297
+ mobile: false
2298
+ },
2299
+ this.sessionId
2300
+ );
2301
+ this._viewportSize = size;
2302
+ }
2559
2303
  // ── Scripts ─────────────────────────────────────────────────
2560
2304
  async addInitScript(script) {
2561
2305
  await this.conn.send(
@@ -2779,6 +2523,12 @@ Last error: ${lastError.message}` : "";
2779
2523
  async _cdpSend(method, params) {
2780
2524
  return this.conn.send(method, params, this.sessionId);
2781
2525
  }
2526
+ /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2527
+ * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2528
+ * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2529
+ setBeforeUnloadBehavior(mode) {
2530
+ this._beforeUnloadAccept = mode === "accept";
2531
+ }
2782
2532
  /**
2783
2533
  * 开启/关闭原生文件选择框拦截(CDP stateful 开关)。
2784
2534
  *
@@ -2837,8 +2587,9 @@ Last error: ${lastError.message}` : "";
2837
2587
  }
2838
2588
  };
2839
2589
  this._emit("dialog", dialog);
2590
+ const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
2840
2591
  setTimeout(() => {
2841
- this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
2592
+ this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
2842
2593
  });
2843
2594
  }, 0);
2844
2595
  })
@@ -2981,6 +2732,7 @@ Last error: ${lastError.message}` : "";
2981
2732
  _networkRequests = /* @__PURE__ */ new Map();
2982
2733
  _routeHandlers = [];
2983
2734
  _interceptionEnabled = false;
2735
+ _beforeUnloadAccept = true;
2984
2736
  /** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
2985
2737
  _storeNetworkRequest(requestId, data) {
2986
2738
  this._networkRequests.set(requestId, { requestId, ...data });
@@ -3092,7 +2844,10 @@ Last error: ${lastError.message}` : "";
3092
2844
  if (!this._interceptionEnabled) {
3093
2845
  this._interceptionEnabled = true;
3094
2846
  await this.conn.send("Fetch.enable", {
3095
- patterns: [{ urlPattern: "*", requestStage: "Request" }]
2847
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
2848
+ // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2849
+ // 会顶掉 _init 的 auth 配置)
2850
+ handleAuthRequests: true
3096
2851
  }, this.sessionId);
3097
2852
  this._subscriptions.push(
3098
2853
  this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
@@ -3145,6 +2900,36 @@ Last error: ${lastError.message}` : "";
3145
2900
  });
3146
2901
  }
3147
2902
  // ── setInputFiles ───────────────────────────────────────────
2903
+ /**
2904
+ * sup-s4: Dropzone 拖拽上传模拟——Dropzone/Uppy/自绘上传区只监听
2905
+ * dragover/drop(无 input[type=file] 可点),真实用户靠 OS 文件拖入
2906
+ * 触发,自动化无法产生 OS 拖拽。页内构造 DataTransfer+File,按拖放
2907
+ * 协议派发 dragenter/dragover/drop(bubbles+cancelable,坐标取目标
2908
+ * 中心)。
2909
+ */
2910
+ async dropFiles(selector, payload) {
2911
+ await this.evaluate(`
2912
+ (function() {
2913
+ var el = ${queryJS(selector)};
2914
+ if (!el) throw new Error('drop target not found: ' + ${JSON.stringify(selector)});
2915
+ var b64 = ${JSON.stringify(payload.buffer.toString("base64"))};
2916
+ var bin = atob(b64);
2917
+ var buf = new Uint8Array(bin.length);
2918
+ for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
2919
+ var file = new File([buf], ${JSON.stringify(payload.name)}, { type: ${JSON.stringify(payload.mimeType)} });
2920
+ var dt = new DataTransfer();
2921
+ dt.items.add(file);
2922
+ var rect = el.getBoundingClientRect();
2923
+ var opts = {
2924
+ bubbles: true, cancelable: true,
2925
+ clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2,
2926
+ };
2927
+ el.dispatchEvent(new DragEvent('dragenter', Object.assign({ dataTransfer: dt }, opts)));
2928
+ el.dispatchEvent(new DragEvent('dragover', Object.assign({ dataTransfer: dt }, opts)));
2929
+ el.dispatchEvent(new DragEvent('drop', Object.assign({ dataTransfer: dt }, opts)));
2930
+ })()
2931
+ `);
2932
+ }
3148
2933
  async setInputFiles(selector, files) {
3149
2934
  const fileArr = Array.isArray(files) ? files : [files];
3150
2935
  const fileList = fileArr.map((f) => ({
@@ -3287,6 +3072,18 @@ var XBContextImpl = class {
3287
3072
  this.options = opts;
3288
3073
  this.setupAutoAttach();
3289
3074
  }
3075
+ /** S194: 任务 tab 的 stealth 配置(UA-CH 档案等)经 context 传给 page 层 */
3076
+ get stealthConfig() {
3077
+ return this.options.stealthConfig;
3078
+ }
3079
+ /** sup-s9: HTTP 认证凭证经 context 传给 page 层(authRequired 自动响应) */
3080
+ get httpCredentials() {
3081
+ return this.options.httpCredentials;
3082
+ }
3083
+ /** sup-s12: 自签/无效证书放行——经 context 传给 page 层(原为死字段) */
3084
+ get ignoreHTTPSErrors() {
3085
+ return this.options.ignoreHTTPSErrors;
3086
+ }
3290
3087
  async newPage() {
3291
3088
  if (this.closed) throw new Error("Context is closed");
3292
3089
  const { targetId } = await this._browser._createTarget(this.contextId);
@@ -3453,20 +3250,8 @@ var XBContextImpl = class {
3453
3250
 
3454
3251
  // src/cdp-driver/browser.ts
3455
3252
  var XBBrowserImpl = class {
3456
- conn;
3457
- _emitter = new EventEmitter3();
3458
- _contexts = /* @__PURE__ */ new Map();
3459
- _disconnected = false;
3460
- childProcess = null;
3461
- tmpDir;
3462
- _exitHandler = null;
3463
- /**
3464
- * Original CDP endpoint (HTTP or ws URL) used to construct this browser.
3465
- * Used by discoverContexts() as a fallback to HTTP /json/list when
3466
- * Target.getTargets doesn't return page-type targets (e.g. cdp-tunnel proxy).
3467
- */
3468
- cdpEndpoint;
3469
- constructor(conn, childProcess, tmpDir, cdpEndpoint) {
3253
+ constructor(conn, childProcess, tmpDir, cdpEndpoint, launchOpts) {
3254
+ this.launchOpts = launchOpts;
3470
3255
  this.conn = conn;
3471
3256
  this.childProcess = childProcess ?? null;
3472
3257
  this.tmpDir = tmpDir;
@@ -3494,6 +3279,20 @@ var XBBrowserImpl = class {
3494
3279
  process.on("exit", this._exitHandler);
3495
3280
  }
3496
3281
  }
3282
+ launchOpts;
3283
+ conn;
3284
+ _emitter = new EventEmitter3();
3285
+ _contexts = /* @__PURE__ */ new Map();
3286
+ _disconnected = false;
3287
+ childProcess = null;
3288
+ tmpDir;
3289
+ _exitHandler = null;
3290
+ /**
3291
+ * Original CDP endpoint (HTTP or ws URL) used to construct this browser.
3292
+ * Used by discoverContexts() as a fallback to HTTP /json/list when
3293
+ * Target.getTargets doesn't return page-type targets (e.g. cdp-tunnel proxy).
3294
+ */
3295
+ cdpEndpoint;
3497
3296
  get disconnected() {
3498
3297
  return this._disconnected;
3499
3298
  }
@@ -3514,13 +3313,16 @@ var XBBrowserImpl = class {
3514
3313
  this._exitHandler = null;
3515
3314
  }
3516
3315
  if (this.childProcess) {
3517
- const { killChrome: killChrome2 } = await import("./launcher-EXJHHAUL.js");
3316
+ const { killChrome: killChrome2 } = await import("./launcher-LUOMMGZC.js");
3518
3317
  await killChrome2(this.childProcess, this.tmpDir);
3519
3318
  }
3520
3319
  await this.conn.close();
3521
3320
  this._emitter.emit("disconnected");
3522
3321
  }
3523
3322
  async newContext(opts = {}) {
3323
+ if (this.launchOpts?.stealthConfig && !opts.stealthConfig) {
3324
+ opts = { ...opts, stealthConfig: this.launchOpts.stealthConfig };
3325
+ }
3524
3326
  if (this._disconnected) {
3525
3327
  throw new Error("Browser is disconnected");
3526
3328
  }
@@ -3537,6 +3339,38 @@ var XBBrowserImpl = class {
3537
3339
  } catch {
3538
3340
  }
3539
3341
  const context = new XBContextImpl(this.conn, contextId, this, opts);
3342
+ if (!this.cdpEndpoint && contextId !== "default") {
3343
+ const downloadDir = join(tmpdir(), "xbrowser-downloads");
3344
+ try {
3345
+ mkdirSync(downloadDir, { recursive: true });
3346
+ } catch {
3347
+ }
3348
+ await this.conn.send("Browser.setDownloadBehavior", {
3349
+ behavior: "allowAndName",
3350
+ downloadPath: downloadDir,
3351
+ eventsEnabled: false,
3352
+ browserContextId: contextId
3353
+ }, void 0, 1e4).catch(() => {
3354
+ });
3355
+ await this.conn.send("Browser.grantPermissions", {
3356
+ permissions: [
3357
+ "notifications",
3358
+ "geolocation",
3359
+ "clipboardReadWrite",
3360
+ "clipboardSanitizedWrite",
3361
+ "videoCapture",
3362
+ "audioCapture",
3363
+ "midi"
3364
+ ],
3365
+ browserContextId: contextId
3366
+ }, void 0, 1e4).catch(() => {
3367
+ this.conn.send("Browser.grantPermissions", {
3368
+ permissions: ["notifications", "geolocation"],
3369
+ browserContextId: contextId
3370
+ }, void 0, 1e4).catch(() => {
3371
+ });
3372
+ });
3373
+ }
3540
3374
  context.on("page", (page) => {
3541
3375
  this._emitter.emit("page", page);
3542
3376
  });
@@ -3649,7 +3483,7 @@ var XBBrowserImpl = class {
3649
3483
  if (pageTargets.length === 0 && httpFallbackUrl) {
3650
3484
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
3651
3485
  try {
3652
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-EXJHHAUL.js");
3486
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-LUOMMGZC.js");
3653
3487
  const httpPages = await getCDPTargets2(httpFallbackUrl);
3654
3488
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
3655
3489
  for (const p of httpPages) {
@@ -3747,6 +3581,9 @@ function extractAllStrings(rawArgs) {
3747
3581
  }
3748
3582
  return strings.length > 0 ? strings.join("\n") : null;
3749
3583
  }
3584
+ function isProbeMarked(code) {
3585
+ return code.includes("/* @xb-probe */");
3586
+ }
3750
3587
 
3751
3588
  // src/cdp-interceptor/rules/dom-mutation.ts
3752
3589
  var DOM_PATTERNS = [
@@ -4309,6 +4146,7 @@ var eventSimulationRule = {
4309
4146
  evaluate(ctx) {
4310
4147
  const userCode = extractUserCode(ctx);
4311
4148
  if (!userCode) return null;
4149
+ if (isProbeMarked(userCode)) return null;
4312
4150
  for (const p of EVENT_PATTERNS) {
4313
4151
  if (p.pattern.test(userCode)) {
4314
4152
  return {
@@ -4636,6 +4474,11 @@ function createRuleEngine(customRules) {
4636
4474
  ...ctx,
4637
4475
  sessionState: getSessionState(ctx.sessionId)
4638
4476
  };
4477
+ try {
4478
+ const code = typeof ctx.params?.expression === "string" ? ctx.params.expression : JSON.stringify(ctx.params ?? "");
4479
+ if (isProbeMarked(code)) return null;
4480
+ } catch {
4481
+ }
4639
4482
  for (const rule of rules) {
4640
4483
  if (rule.canHandle && !rule.canHandle(fullCtx)) continue;
4641
4484
  const decision = rule.evaluate(fullCtx);
@@ -5016,8 +4859,23 @@ async function launch(options = {}) {
5016
4859
  }
5017
4860
  const conn = new CDPConnection(wsEndpoint);
5018
4861
  await conn.ready();
4862
+ let stealthOpts;
4863
+ try {
4864
+ const bv = await conn.send("Browser.getVersion");
4865
+ const m = bv.product.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
4866
+ if (m && !options.stealthConfig?.uaChProfile) {
4867
+ const { deriveUaChProfileForBinary } = await import("./stealth-2AA2FSNN.js");
4868
+ stealthOpts = { stealthConfig: { uaChProfile: deriveUaChProfileForBinary(m[0], m[1]) } };
4869
+ }
4870
+ } catch {
4871
+ }
4872
+ if (options.stealthConfig) {
4873
+ stealthOpts = {
4874
+ stealthConfig: { ...stealthOpts?.stealthConfig ?? {}, ...options.stealthConfig }
4875
+ };
4876
+ }
5019
4877
  const httpEndpoint = options.cdpEndpoint && !options.cdpEndpoint.startsWith("ws") ? options.cdpEndpoint : void 0;
5020
- const browser = new XBBrowserImpl(conn, childProcess, tmpDir, httpEndpoint);
4878
+ const browser = new XBBrowserImpl(conn, childProcess, tmpDir, httpEndpoint, stealthOpts);
5021
4879
  return { browser, wsEndpoint };
5022
4880
  }
5023
4881
  export {