@xbrowser/cli 1.21.0 → 1.23.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 (43) hide show
  1. package/README.md +21 -3
  2. package/dist/{browser-CNBSH53B.js → browser-BVRFSUXU.js} +3 -2
  3. package/dist/{browser-C2VEOJC2.js → browser-DSYUAE7H.js} +5 -4
  4. package/dist/{browser-VZOOFLAH.js → browser-Q67BJTI2.js} +4 -3
  5. package/dist/{cdp-driver-KFX4A6WR.js → cdp-driver-DC7EIUG5.js} +4 -3
  6. package/dist/{cdp-driver-7Z6ZAT5E.js → cdp-driver-T7D6H2RW.js} +335 -546
  7. package/dist/{cdp-driver-26LGCHXV.js → cdp-driver-WWO2UZDR.js} +3 -2
  8. package/dist/{chunk-Z5RTK4GW.js → chunk-2Q3GQRUP.js} +2 -2
  9. package/dist/{chunk-CLYZPSDR.js → chunk-4OU37CXP.js} +354 -576
  10. package/dist/{chunk-HWWG2ISJ.js → chunk-7OP2ISEY.js} +353 -575
  11. package/dist/{chunk-PIWNMC36.js → chunk-A3MORKYR.js} +1 -1
  12. package/dist/{chunk-3FWLW7FS.js → chunk-A7NEA4PA.js} +39 -1
  13. package/dist/{chunk-OMU63E6J.js → chunk-FBQZ3PVD.js} +5 -8
  14. package/dist/chunk-GYB5BOSP.js +602 -0
  15. package/dist/{chunk-ESJYANQO.js → chunk-IFKJO2UR.js} +360 -582
  16. package/dist/{chunk-NODRQGOK.js → chunk-IR6C24P7.js} +97 -0
  17. package/dist/{chunk-TEXCXIBW.js → chunk-LPW6QS4M.js} +5 -8
  18. package/dist/{chunk-3KZ34AUC.js → chunk-MYH6FIBZ.js} +2 -1
  19. package/dist/{chunk-AVSTNODR.js → chunk-T4WTKBWI.js} +2 -2
  20. package/dist/{chunk-HBHOKZPN.js → chunk-V6KGBU5J.js} +97 -0
  21. package/dist/{chunk-IWVG4XYZ.js → chunk-VCVDILH6.js} +2 -1
  22. package/dist/{chunk-NKW4A74J.js → chunk-XTUAUFL3.js} +5 -8
  23. package/dist/cli.js +497 -252
  24. package/dist/daemon-main.js +25 -19
  25. package/dist/{human-interaction-Y5IDH6LD.js → human-interaction-57VYIR56.js} +1 -1
  26. package/dist/{human-interaction-ZUTR5AC2.js → human-interaction-67K43B4O.js} +1 -1
  27. package/dist/{human-interaction-4YR2N6R6.js → human-interaction-MXST5ZQM.js} +1 -1
  28. package/dist/index.d.ts +52 -4
  29. package/dist/index.js +500 -256
  30. package/dist/keep-awake-M4KJS4B4.js +29 -0
  31. package/dist/{launcher-44STYRJC.js → launcher-IK2FKW6T.js} +1 -1
  32. package/dist/{launcher-EXJHHAUL.js → launcher-LUOMMGZC.js} +1 -1
  33. package/dist/{plugin-singleton-FCNDN3FX.js → plugin-singleton-GJO7EZXB.js} +1 -1
  34. package/dist/{recovery-NXC35EQN.js → recovery-6RI2FE3E.js} +1 -1
  35. package/dist/{recovery-MDWAVXE4.js → recovery-LGY25LIM.js} +1 -1
  36. package/dist/{recovery-L5GLDX4O.js → recovery-LMJW537X.js} +1 -1
  37. package/dist/{session-recorder-SLDBENVF.js → session-recorder-563ISSJK.js} +1 -1
  38. package/dist/{session-recorder-3BEVWHOK.js → session-recorder-GEZVQBKW.js} +1 -1
  39. package/dist/session-replayer-N665T3G5.js +932 -0
  40. package/dist/stealth-2AA2FSNN.js +29 -0
  41. package/dist/stealth-JOXGV34D.js +29 -0
  42. package/package.json +11 -7
  43. package/dist/session-replayer-EVD4HZBB.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,533 +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
- // S191: macOS arm64 + Chrome 151 真实采样(来源:登录桥只读通道)
25
- uaChProfile: {
26
- brands: [
27
- { brand: "Not=A?Brand", version: "99" },
28
- { brand: "Google Chrome", version: "151" },
29
- { brand: "Chromium", version: "151" }
30
- ],
31
- platform: "macOS",
32
- platformVersion: "26.2.0",
33
- architecture: "arm",
34
- bitness: "64",
35
- model: "",
36
- uaFullVersion: "151.0.7922.175",
37
- fullVersionList: [
38
- { brand: "Not=A?Brand", version: "99.0.0.0" },
39
- { brand: "Google Chrome", version: "151.0.7922.175" },
40
- { brand: "Chromium", version: "151.0.7922.175" }
41
- ]
42
- },
43
- bezierCurvature: [0.35, 0.6],
44
- noiseAmplitude: 5.5,
45
- overshootRange: [6, 14],
46
- aimPause: [80, 280],
47
- pressDuration: [60, 140],
48
- releaseDrift: [0.8, 2.5],
49
- landingOffsetSmall: [0.3, 2.5],
50
- landingOffsetLarge: [1.5, 7],
51
- smallElementThreshold: 30,
52
- typingRhythm: {
53
- fastProb: 0.22,
54
- fastRange: [25, 60],
55
- normalRange: [50, 350],
56
- pauseProb: 0.18,
57
- pauseRange: [400, 1200]
58
- },
59
- keyPressDuration: [50, 110],
60
- typoProbability: 0.06,
61
- wheelPeak: 180,
62
- wheelDecayRate: 0.4
63
- };
64
- function rand(min, max) {
65
- return min + Math.random() * (max - min);
66
- }
67
- function cosineEase(t) {
68
- return 0.5 - 0.5 * Math.cos(Math.PI * t);
69
- }
70
- function bezierTrajectory(x0, y0, x1, y1, config = DEFAULT_STEALTH_CONFIG) {
71
- const dist = Math.hypot(x1 - x0, y1 - y0);
72
- const n = Math.max(10, Math.min(28, Math.round(dist / 15)));
73
- const shortMove = dist < 120;
74
- const curvature = shortMove ? rand(2, 6) : Math.max(dist * rand(...config.bezierCurvature), rand(18, 35));
75
- const dir = Math.random() < 0.5 ? 1 : -1;
76
- const d = dist || 1;
77
- const dx = x1 - x0, dy = y1 - y0;
78
- const c1x = x0 + dx * 0.3 - dy / d * curvature * 0.5 * dir;
79
- const c1y = y0 + dy * 0.3 + dx / d * curvature * 0.5 * dir;
80
- const c2x = x0 + dx * 0.7 - dy / d * curvature * 0.8 * dir;
81
- const c2y = y0 + dy * 0.7 + dx / d * curvature * 0.8 * dir;
82
- const points = [];
83
- for (let i = 1; i <= n; i++) {
84
- const t = cosineEase(i / n);
85
- const mt = 1 - t;
86
- let px = mt ** 3 * x0 + 3 * mt ** 2 * t * c1x + 3 * mt * t ** 2 * c2x + t ** 3 * x1;
87
- let py = mt ** 3 * y0 + 3 * mt ** 2 * t * c1y + 3 * mt * t ** 2 * c2y + t ** 3 * y1;
88
- const amp = shortMove ? Math.min(2, config.noiseAmplitude) : config.noiseAmplitude;
89
- px += rand(-amp, amp);
90
- py += rand(-amp, amp);
91
- points.push({ x: px, y: py, delay: rand(9, 16) });
92
- }
93
- if (!shortMove) {
94
- const over = rand(...config.overshootRange);
95
- const ox = x1 + dx / d * over + rand(-2, 2);
96
- const oy = y1 + dy / d * over + rand(-2, 2);
97
- points.push({ x: ox, y: oy, delay: rand(14, 30) });
98
- points.push({
99
- x: x1 + dx / d * over * 0.4,
100
- y: y1 + dy / d * over * 0.4,
101
- delay: rand(14, 30)
102
- });
103
- }
104
- points.push({ x: x1 + rand(-1, 1), y: y1 + rand(-1, 1), delay: rand(14, 30) });
105
- return points;
106
- }
107
- function landingOffset(width, height, config = DEFAULT_STEALTH_CONFIG) {
108
- const isSmall = Math.min(width, height) < config.smallElementThreshold;
109
- const range = isSmall ? config.landingOffsetSmall : config.landingOffsetLarge;
110
- const dx = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
111
- const dy = rand(...range) * (Math.random() < 0.5 ? -1 : 1);
112
- return { dx, dy };
113
- }
114
- function typingDelay(config = DEFAULT_STEALTH_CONFIG) {
115
- const roll = Math.random();
116
- const r = config.typingRhythm;
117
- if (roll < r.pauseProb) return rand(...r.pauseRange);
118
- if (roll < r.pauseProb + r.fastProb) return rand(...r.fastRange);
119
- return rand(...r.normalRange);
120
- }
121
- var KEY_MAP = {};
122
- for (let i = 97; i <= 122; i++) {
123
- const ch = String.fromCharCode(i);
124
- KEY_MAP[ch] = { key: ch, code: "Key" + ch.toUpperCase(), vk: i - 32 };
125
- }
126
- for (let i = 65; i <= 90; i++) {
127
- const ch = String.fromCharCode(i);
128
- KEY_MAP[ch] = { key: ch, code: "Key" + ch, vk: i, shift: true };
129
- }
130
- for (let i = 48; i <= 57; i++) {
131
- const ch = String.fromCharCode(i);
132
- KEY_MAP[ch] = { key: ch, code: "Digit" + ch, vk: i };
133
- }
134
- Object.assign(KEY_MAP, {
135
- " ": { key: " ", code: "Space", vk: 32 },
136
- ".": { key: ".", code: "Period", vk: 190 },
137
- "-": { key: "-", code: "Minus", vk: 189 },
138
- "@": { key: "@", code: "Digit2", vk: 50, shift: true },
139
- "_": { key: "_", code: "Minus", vk: 189, shift: true }
140
- });
141
- function buildStealthInitScript(config = DEFAULT_STEALTH_CONFIG) {
142
- const prof = config.uaChProfile;
143
- const profJson = prof ? JSON.stringify(prof) : "null";
144
- return [
145
- "(function(){",
146
- ' window.__xbStealthVer="57";',
147
- " window.__xbUaChProf=" + profJson + ";",
148
- // 1. AEL event proxy
149
- " var o=EventTarget.prototype.addEventListener;",
150
- " var fc=new InputDeviceCapabilities({firesTouchEvents:false});",
151
- " var _ael=function(t,f){",
152
- " var op=arguments[2];",
153
- ' if(typeof f!=="function")return o.call(this,t,f,op);',
154
- " var w=function(e){",
155
- " if(!e)return f.call(this,e);",
156
- " return f.call(this,new Proxy(e,{get:function(k,p){",
157
- ' if(p==="sourceCapabilities")return fc;',
158
- // S124 修正(d67 攻防):恒 true 是"过度伪装"——站点自己的合成事件
159
- // 也变 true → 直接判定浏览器被篡改(比检测自动化更严重的指纹暴露)。
160
- // 正确策略:透传原始值(CDP Input 事件本来就是 true,JS 合成本来是 false)
161
- // + paste 定向伪装(合成的 paste 在真实场景都是 trusted 的键盘操作产物)
162
- ' if(p==="isTrusted"){',
163
- ' var orig=Reflect.get(k,"isTrusted");',
164
- " if(orig===true)return true;",
165
- ' if(k.type==="paste")return true;',
166
- " return orig;",
167
- " }",
168
- ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])){',
169
- " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;",
170
- " return k[p]+_f;",
171
- " }",
172
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
173
- " }}));",
174
- " };",
175
- " return o.call(this,t,w,op);",
176
- " };",
177
- " EventTarget.prototype.addEventListener=_ael;",
178
- // window.event isTrusted 伪装(S123):AEL 参数包装收不到 window.event
179
- // (它是原始 Event 对象的隐式引用)。定义 getter 拦截读取。
180
- " try{",
181
- ' var _weDesc=Object.getOwnPropertyDescriptor(Window.prototype,"event");',
182
- " if(_weDesc&&_weDesc.get){",
183
- " var _origWeGet=_weDesc.get;",
184
- ' Object.defineProperty(Window.prototype,"event",{',
185
- " configurable:true,",
186
- " get:function(){",
187
- " var ev=_origWeGet.call(this);",
188
- " if(!ev)return ev;",
189
- " return new Proxy(ev,{get:function(k,p){",
190
- ' if(p==="isTrusted"){',
191
- ' var orig=Reflect.get(k,"isTrusted");',
192
- " if(orig===true)return true;",
193
- ' if(k.type==="paste")return true;',
194
- " return orig;",
195
- " }",
196
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
197
- " }});",
198
- " }",
199
- " });",
200
- " }",
201
- " }catch(e){}",
202
- // 2. Screen override (prototype-level, not instance-level)
203
- " var _gw=function(){return 1728};",
204
- " var _gh=function(){return 1117};",
205
- " var _gah=function(){return 1092};",
206
- ' Object.defineProperty(Screen.prototype,"width",{get:_gw,configurable:true});',
207
- ' Object.defineProperty(Screen.prototype,"height",{get:_gh,configurable:true});',
208
- ' Object.defineProperty(Screen.prototype,"availWidth",{get:_gw,configurable:true});',
209
- ' Object.defineProperty(Screen.prototype,"availHeight",{get:_gah,configurable:true});',
210
- // S174: UA Headless 标记清洗——headless launch 的 UA 含 HeadlessChrome/xxx
211
- // (最高频检测面),同步清洗 userAgent/appVersion/userAgentData(brands+高熵值)。
212
- // 原型+实例双层覆写(S172 模式)。
213
- " try{",
214
- ' var fixUA=function(ua){return String(ua).replace("HeadlessChrome","Chrome");};',
215
- ' 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;});};',
216
- ' var _nuad=Object.getOwnPropertyDescriptor(Navigator.prototype,"userAgentData");',
217
- " var wrapUAD=function(uad){",
218
- " if(!uad||uad.__xbUA)return uad;",
219
- " try{",
220
- ' Object.defineProperty(uad,"brands",{get:function(){return fixBrands(_nuad.get.call(navigator).brands);},configurable:true});',
221
- " var _ghev=uad.getHighEntropyValues.bind(uad);",
222
- " uad.getHighEntropyValues=function(hints){return _ghev(hints).then(function(v){",
223
- ' 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]);}',
224
- " return o;});};",
225
- " uad.__xbUA=true;",
226
- " }catch(e){}",
227
- " return uad;",
228
- " };",
229
- ' var _nua=Object.getOwnPropertyDescriptor(Navigator.prototype,"userAgent");',
230
- " if(_nua&&_nua.get){",
231
- " var _nuag=function(){return fixUA(_nua.get.call(this));};",
232
- ' _nuag.toString=function(){return "function get userAgent() { [native code] }";};',
233
- ' Object.defineProperty(Navigator.prototype,"userAgent",{get:_nuag,configurable:true});',
234
- " }",
235
- ' Object.defineProperty(navigator,"userAgent",{get:function(){return fixUA(_nua?_nua.get.call(this):"");},configurable:true});',
236
- " if(_nuad&&_nuad.get){",
237
- " var _nuadg=function(){return wrapUAD(_nuad.get.call(this));};",
238
- ' _nuadg.toString=function(){return "function get userAgentData() { [native code] }";};',
239
- ' Object.defineProperty(Navigator.prototype,"userAgentData",{get:_nuadg,configurable:true});',
240
- " }",
241
- // S190: userAgentData 垫片——headless Chrome 151 不暴露 UA-CH API,
242
- // 缺失本身即 headless 指纹。从 UA 派生 brands/platform 垫片 + getHighEntropyValues。
243
- " if(!navigator.userAgentData && window.__xbUaChProf){",
244
- " var prof = window.__xbUaChProf;",
245
- " var uad={",
246
- ' brands:prof.brands.map(function(b){return {brand:b.brand,version:b.version.split(".")[0]}}),',
247
- " mobile:false,",
248
- " platform:prof.platform,",
249
- " getHighEntropyValues:function(hints){",
250
- " return Promise.resolve().then(function(){",
251
- " var all={brands:uad.brands,mobile:false,platform:prof.platform,",
252
- " platformVersion:prof.platformVersion,architecture:prof.architecture,bitness:prof.bitness,model:prof.model,",
253
- " uaFullVersion:prof.uaFullVersion,",
254
- " fullVersionList:prof.fullVersionList};",
255
- " var out={};",
256
- " (hints||[]).forEach(function(h){if(h in all)out[h]=all[h]});",
257
- " return out;",
258
- " });",
259
- " },",
260
- " toJSON:function(){return{brands:uad.brands,mobile:false,platform:prof.platform}}",
261
- " };",
262
- ' Object.defineProperty(navigator,"userAgentData",{get:function(){return uad},configurable:true});',
263
- " }",
264
- " }catch(e){}",
265
- // hasFocus 与 visibilityState 联动(d29):恒 true 在 hidden 标签下暴露
266
- // —— 真实浏览器失焦/后台时 hasFocus=false
267
- // S172: 原型层覆写——实例赋值可被 Document.prototype.hasFocus.call(document) 逃逸
268
- ' Document.prototype.hasFocus=function(){return document.visibilityState==="visible";};',
269
- // 4. Canvas/WebGL fingerprint: per-session stable noise (d20).
270
- // Headless software raster differs subtly from Chrome GPU raster —
271
- // toDataURL hashes fingerprint the rasterizer. Inject a stable
272
- // (per-page-load) subpixel shift into fillText so hashes look like a
273
- // distinct-but-consistent real GPU, and hide the HEADLESS tell in
274
- // WebGL renderer strings.
275
- " var _seed=Math.floor(Math.random()*2147483647);",
276
- " var _prng=function(){_seed=(_seed*48271)%2147483647;return _seed/2147483647;};",
277
- " var _dx=(_prng()*0.4-0.2).toFixed(3)*1, _dy=(_prng()*0.4-0.2).toFixed(3)*1;",
278
- " var _fillText=CanvasRenderingContext2D.prototype.fillText;",
279
- " CanvasRenderingContext2D.prototype.fillText=function(t,x,y,m){",
280
- " return _fillText.call(this,t,x+_dx,y+_dy,m);",
281
- " };",
282
- " var _toDataURL=HTMLCanvasElement.prototype.toDataURL;",
283
- " HTMLCanvasElement.prototype.toDataURL=function(){",
284
- ' var ctx=this.getContext("2d");',
285
- " if(ctx){var d=ctx.getImageData(0,0,Math.min(this.width,2),Math.min(this.height,2));",
286
- " for(var i=0;i<d.data.length;i+=4){if(d.data[i+3]>0){d.data[i]^=1;break;}}",
287
- " ctx.putImageData(d,0,0);}",
288
- " return _toDataURL.apply(this,arguments);",
289
- " };",
290
- " try{",
291
- " var _gl=HTMLCanvasElement.prototype.getContext;",
292
- " HTMLCanvasElement.prototype.getContext=function(t,o){",
293
- " var c=_gl.call(this,t,o);",
294
- ' if(c&&(t==="webgl"||t==="experimental-webgl")&&c.getParameter){',
295
- " var _gp=c.getParameter.bind(c);",
296
- " c.getParameter=function(p){",
297
- " var v=_gp(p);",
298
- ' if(typeof v==="string"&&/SwiftShader|Software|Rasterizer|Headless/i.test(v))',
299
- ' return "ANGLE (Apple, ANGLE Metal Renderer: Apple M2 Max, Unspecified Version)";',
300
- " return v;};}",
301
- " return c;};",
302
- " }catch(e){}",
303
- // 5. AudioContext fingerprint: per-load stable micro-noise on channel
304
- // data (d21). DSP sum differences between headless software audio and
305
- // real hardware audio are a classic fingerprint — add ±1e-7 level
306
- // noise (inaudible, changes the sum hash).
307
- " try{",
308
- " var _gcd=AudioBuffer.prototype.getChannelData;",
309
- " AudioBuffer.prototype.getChannelData=function(ch){",
310
- " var d=_gcd.call(this,ch);",
311
- ' var key="__xb_audio_"+ch;',
312
- " if(!this[key]){",
313
- " this[key]=true;",
314
- " for(var i=0;i<d.length;i+=997){d[i]=d[i]+(_prng()-0.5)*2e-7;}",
315
- " }",
316
- " return d;",
317
- " };",
318
- " var _gffd=AnalyserNode.prototype.getFloatFrequencyData;",
319
- " AnalyserNode.prototype.getFloatFrequencyData=function(arr){",
320
- " _gffd.call(this,arr);",
321
- " for(var i=0;i<arr.length;i+=31){arr[i]=arr[i]+(_prng()-0.5)*0.01;}",
322
- " };",
323
- " var _gfbd=AnalyserNode.prototype.getByteFrequencyData;",
324
- " AnalyserNode.prototype.getByteFrequencyData=function(arr){",
325
- " _gfbd.call(this,arr);",
326
- " for(var i=0;i<arr.length;i+=31){arr[i]=(arr[i]+((_prng()*3)|0))&255;}",
327
- " };",
328
- " }catch(e){}",
329
- // 3b. Font metrics + speechSynthesis + battery (d22): headless tells
330
- " try{",
331
- ' var _tmw=Object.getOwnPropertyDescriptor(TextMetrics.prototype,"width");',
332
- " if(_tmw&&_tmw.get){",
333
- " // S172: \u539F\u578B\u5C42\u8986\u5199\u2014\u2014\u5B9E\u4F8B(m)\u8986\u5199\u53EF\u88AB TextMetrics.prototype.width getter \u9003\u9038",
334
- ' Object.defineProperty(TextMetrics.prototype,"width",{get:function(){return _tmw.get.call(this)+_dx*0.01;},configurable:true});',
335
- " }",
336
- " }catch(e){}",
337
- " try{",
338
- ' var _fakeVoices=["Alex","Daniel","Karen","Moira","Ralph","Samantha","Ting-Ting","Mei-Jia","Sinji","Yunda"];',
339
- // S172: 原型层覆写——实例赋值可被 SpeechSynthesis.prototype.getVoices.call() 逃逸
340
- " var _sv=SpeechSynthesis.prototype.getVoices;",
341
- " SpeechSynthesis.prototype.getVoices=function(){",
342
- " var real=_sv.call(this);",
343
- " if(real&&real.length>50)return real;",
344
- // 注意阈值从 0 改 50:iframe 原生约 10 个 —— 原阈值下 iframe 返回原生 10 个
345
- // 而不是伪装 180(d33 暴露)。>50 = 主文档伪装列表已生效,其余返回伪装。
346
- ' 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};});',
347
- " };",
348
- // d33 修复:iframe 的 speechSynthesis 是独立实例(主文档 hook 不可达)——
349
- // 轮询同源 iframe,对其 contentWindow 的原型同样 patch(S172: 原型层,防逃逸)
350
- " try{",
351
- " var _piv=function(){",
352
- ' var frs=document.querySelectorAll("iframe");',
353
- " for(var i=0;i<frs.length;i++){try{",
354
- " var cw=frs[i].contentWindow;",
355
- " if(!cw||!cw.speechSynthesis||cw.speechSynthesis.__xbP)continue;",
356
- " cw.speechSynthesis.__xbP=true;",
357
- " var _sv2=cw.SpeechSynthesis.prototype.getVoices;",
358
- " cw.SpeechSynthesis.prototype.getVoices=function(){var r=_sv2.call(this);if(r&&r.length>50)return r;",
359
- ' 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};});};',
360
- " }catch(e2){}}",
361
- " };",
362
- " setInterval(_piv,2000);",
363
- " var _mo=new MutationObserver(function(muts){",
364
- " for(var k=0;k<muts.length;k++){var ns=muts[k].addedNodes;",
365
- ' for(var q=0;q<ns.length;q++){if(ns[q].tagName==="IFRAME")setTimeout(_piv,20);}}',
366
- " });",
367
- " _mo.observe(document.documentElement,{childList:true,subtree:true});",
368
- " }catch(e){}",
369
- " }catch(e){}",
370
- " try{",
371
- " var _gb=navigator.getBattery.bind(navigator);",
372
- " navigator.getBattery=function(){",
373
- " return _gb().then(function(b){",
374
- ' Object.defineProperty(b,"charging",{get:function(){return true;},configurable:true});',
375
- " return b;});",
376
- " };",
377
- " }catch(e){}",
378
- // 3c. WebRTC local IP leak guard (d23): headless STUN candidates can
379
- // expose host IPs; mDNS-only candidates are the modern Chrome default.
380
- " try{",
381
- " var _oc=RTCPeerConnection.prototype.createOffer;",
382
- " RTCPeerConnection.prototype.createOffer=function(){",
383
- " var p=_oc.apply(this,arguments);",
384
- " var self=this;",
385
- " return p.then(function(offer){",
386
- ' offer.sdp=offer.sdp.split(String.fromCharCode(10)).filter(function(l){return l.indexOf("typ host")<0}).join(String.fromCharCode(10));',
387
- " return offer;});",
388
- " };",
389
- " }catch(e){}",
390
- // 3d-2. performance.now precision clamp (d34): full-precision timestamps
391
- // (11 decimals) differ from site-isolation-clamped real Chrome (~100μs).
392
- " try{",
393
- " var _pn=Performance.prototype.now;",
394
- " // S172: \u539F\u578B\u5C42\u8986\u5199\u2014\u2014\u5B9E\u4F8B\u8D4B\u503C\u53EF\u88AB Performance.prototype.now.call(performance) \u9003\u9038",
395
- " Performance.prototype.now=function(){return Math.round(_pn.call(this)*10)/10;};",
396
- ' var _pto=Object.getOwnPropertyDescriptor(Performance.prototype,"timeOrigin");',
397
- " if(_pto&&_pto.get){",
398
- " // 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",
399
- " // \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",
400
- " // \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",
401
- " var _toff=Math.floor((_seed/2147483647)*600000-300000);",
402
- " var _tog=function(){return _pto.get.call(performance)+_toff;};",
403
- ' _tog.toString=function(){return "function get timeOrigin() { [native code] }";};',
404
- " // S172 \u5BA1\u8BA1\uFF1A\u5B9E\u4F8B\u8986\u5199\u53EF\u88AB\u539F\u578B getter \u9003\u9038\u2014\u2014\u539F\u578B\u5C42\u8986\u5199",
405
- ' Object.defineProperty(Performance.prototype,"timeOrigin",{get:_tog,configurable:true});',
406
- ' Object.defineProperty(performance,"timeOrigin",{get:_tog,configurable:true});',
407
- " }",
408
- " }catch(e){}",
409
- // 3f. getCoalescedEvents 合成(d47):真实鼠标 125Hz 采样被浏览器按帧合并,
410
- // 快速移动时 pointermove.getCoalescedEvents() 返回 2~6 个事件(群内
411
- // ≈8ms);CDP Input 逐事件派发不走合并管线,coalesced>1 恒为 0(结构性
412
- // 暴露,间隔模拟救不了——实测 Chrome 帧对齐时 CDP 连发事件被直接丢弃
413
- // 而非合并)。按 125Hz 物理插值合成 coalesced 群:期望样本数 = dt/8ms-1,
414
- // 合成事件用真 PointerEvent 构造 + 实例级 isTrusted/timeStamp 遮蔽。
415
- " try{",
416
- " if(window.PointerEvent&&PointerEvent.prototype.getCoalescedEvents){",
417
- " var _gce=PointerEvent.prototype.getCoalescedEvents;",
418
- " var _lm=null;",
419
- " var _gceH=function(){",
420
- " var list=_gce.call(this);",
421
- ' if(this.type!=="pointermove"||!this.isTrusted)return list;',
422
- " var cur={x:this.clientX,y:this.clientY,ts:this.timeStamp};",
423
- " var out=null;",
424
- " if((!list||list.length<2)&&_lm){",
425
- " var dt=cur.ts-_lm.ts,dx=cur.x-_lm.x,dy=cur.y-_lm.y;",
426
- // dt 长(帧丢弃后)不代表群覆盖整个 dt —— 真实 coalesced 群只覆盖
427
- // 最后一帧窗口(≤16.7ms,群内 ≈8ms=125Hz)。合成群从自身往回推 8ms
428
- // 链,位移取末端占比(span/dt,dt 远大于 span 时位移趋零=丢弃后实况)。
429
- " var expN=Math.floor(dt/8)-1;",
430
- // dt<12ms(不足一帧+采样周期)时真实浏览器不会产生合并群 ——
431
- // 单采样帧 coalesced=1,强行合成会出现 ~2ms 的超物理群内间隔。
432
- " if(expN>0&&dt>=12&&Math.random()>0.15){",
433
- " var n=Math.min(4,expN+(Math.random()<0.3?1:0));",
434
- " var span=Math.min(dt,n*8.3);",
435
- " var frac=Math.min(1,span/Math.max(dt,1));",
436
- " out=[];",
437
- " for(var i=1;i<=n;i++){",
438
- // k=距自身的步数(含自身共 n+1 个事件,相邻恒 ≈8.3ms=125Hz 周期)
439
- " var k=n+1-i;",
440
- ' var ev=new PointerEvent("pointermove",{',
441
- ' pointerId:this.pointerId,pointerType:"mouse",isPrimary:this.isPrimary,',
442
- " clientX:cur.x-dx*frac*(k/(n+1))+(Math.random()-0.5)*1.5,",
443
- " clientY:cur.y-dy*frac*(k/(n+1))+(Math.random()-0.5)*1.5,",
444
- " screenX:this.screenX,screenY:this.screenY,",
445
- " buttons:this.buttons,button:this.button,",
446
- " bubbles:true,cancelable:true,composed:true,",
447
- " width:this.width,height:this.height,pressure:this.pressure,",
448
- " tiltX:this.tiltX,tiltY:this.tiltY,twist:this.twist});",
449
- " var tsV=cur.ts-k*8.3-Math.random()*1.2;",
450
- // isTrusted/timeStamp 是实例不可配置属性(defineProperty 抛
451
- // "Cannot redefine"),改 Proxy 包装:getPrototypeOf/ownKeys 透传,
452
- // instanceof 与属性枚举行为与真事件一致。IIFE 捕获本次循环的 tsV
453
- // 快照 —— var 提升会让所有 Proxy 闭包共享最后一次赋值(实测四个
454
- // 合成事件同时间戳、群内间隔塌到 ~2ms)。
455
- " out.push((function(e2,t2){return new Proxy(e2,{get:function(t,p){",
456
- ' if(p==="isTrusted")return true;',
457
- ' if(p==="timeStamp")return t2;',
458
- ' var v=Reflect.get(t,p);return typeof v==="function"?v.bind(t):v;',
459
- " }});})(ev,tsV));",
460
- " }",
461
- " out.push(this);",
462
- " }",
463
- " }",
464
- " _lm=cur;",
465
- " return out||list;",
466
- " };",
467
- " PointerEvent.prototype.getCoalescedEvents=_gceH;",
468
- // name 反查伪装:var _gceH=fn 的具名推断会暴露 hook(原生 name 是
469
- // "getCoalescedEvents")——toString 白名单管不到 name 属性。
470
- ' try{Object.defineProperty(_gceH,"name",{value:"getCoalescedEvents"});}catch(e){}',
471
- " }",
472
- " }catch(e){}",
473
- // 3d. Chrome object depth (d24): automation fakes usually only set
474
- // window.chrome = {}; deep checks hit app.run/runtime/csi/loadTimes.
475
- " try{",
476
- " if(window.chrome){",
477
- ' 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"}};',
478
- ' 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};',
479
- " if(!window.chrome.csi)window.chrome.csi=function(){return{};}",
480
- " if(!window.chrome.loadTimes)window.chrome.loadTimes=function(){return{};}",
481
- " }",
482
- " }catch(e){}",
483
- // 3e. Font availability patch (d25): headless Chromium misses some system
484
- // fonts (e.g. Menlo on macOS) that real Chrome has. Register a FontFace
485
- // aliasing the missing font to a local() equivalent so offsetWidth-based
486
- // font probing sees the same availability as the faked environment.
487
- " try{",
488
- ' var _fontAliases=[["Menlo","Courier New"],["SF Mono","Menlo"],["Segoe UI","Helvetica"]];',
489
- " _fontAliases.forEach(function(pa){",
490
- ' try{var ff=new FontFace(pa[0],"local("+JSON.stringify(pa[1])+")");',
491
- " document.fonts.add(ff);ff.load();}catch(e2){}",
492
- " });",
493
- " }catch(e){}",
494
- // 3g. Notification.requestPermission 延迟(d62):headless 无原生横幅,
495
- // request 瞬回 denied —— 真机 request 会 pending 在横幅上数秒到分钟。
496
- // 延迟 2-6s 再 resolve,模拟横幅期(用户"看了下然后拒绝")。
497
- " try{",
498
- " if(window.Notification&&Notification.requestPermission){",
499
- " var _nrp=Notification.requestPermission.bind(Notification);",
500
- " Notification.requestPermission=function(cb){",
501
- " return new Promise(function(res){",
502
- " setTimeout(function(){_nrp().then(function(r){if(cb)try{cb(r)}catch(e){}res(r);});},2000+Math.random()*4000);",
503
- " });",
504
- " };",
505
- " }",
506
- " }catch(e){}",
507
- // 3. toString disguise (name-list based)
508
- " var _ts=Function.prototype.toString;",
509
- " var _hf=document.hasFocus;",
510
- " Function.prototype.toString=function(){",
511
- ' if(this===_ael)return"function addEventListener(type, callback) { [native code] }";',
512
- ' if(this===_hf)return"function hasFocus() { [native code] }";',
513
- ' if(this===_gw)return"function get width() { [native code] }";',
514
- ' if(this===_gh)return"function get height() { [native code] }";',
515
- ' if(this===_gah)return"function get availHeight() { [native code] }";',
516
- ' if(this===CanvasRenderingContext2D.prototype.fillText)return"function fillText() { [native code] }";',
517
- ' if(this===HTMLCanvasElement.prototype.toDataURL)return"function toDataURL() { [native code] }";',
518
- ' if(this===AnalyserNode.prototype.getFloatFrequencyData)return"function getFloatFrequencyData() { [native code] }";',
519
- ' if(this===AudioBuffer.prototype.getChannelData)return"function getChannelData() { [native code] }";',
520
- ' if(this===_gceH)return"function getCoalescedEvents() { [native code] }";',
521
- ' if(this===Document.prototype.hasFocus)return"function hasFocus() { [native code] }";',
522
- ' if(this===Performance.prototype.now)return"function now() { [native code] }";',
523
- ' if(this===SpeechSynthesis.prototype.getVoices)return"function getVoices() { [native code] }";',
524
- " return _ts.call(this);",
525
- " };",
526
- // 4. onclick prototype hijack (dual-stream consistency)
527
- " var _ba=function(k,p){",
528
- ' if(p==="isTrusted"){',
529
- ' var orig=Reflect.get(k,"isTrusted");',
530
- " if(orig===true)return true;",
531
- ' if(k.type==="paste")return true;',
532
- " return orig;",
533
- " }",
534
- ' if((p==="clientX"||p==="clientY")&&k.type==="click"&&Number.isInteger(k[p])&&k.isTrusted===true){',
535
- " var _f=((k.timeStamp||Date.now())%89)/89*0.7+0.15;return k[p]+_f;",
536
- " }",
537
- ' var v=Reflect.get(k,p);return typeof v==="function"?v.bind(k):v;',
538
- " };",
539
- ' Object.defineProperty(Document.prototype,"onclick",{',
540
- " configurable:true,",
541
- " get:function(){var raw=this.__ocRaw||null;if(!raw)return null;var self=this;",
542
- " return function(e){return raw.call(self,new Proxy(e,{get:function(k,p){return _ba(k,p)}}))}},",
543
- " set:function(fn){this.__ocRaw=fn}",
544
- " });",
545
- "})()"
546
- ].join("\n");
547
- }
548
-
549
33
  // src/cdp-driver/mouse.ts
550
34
  var XBMouseImpl = class {
551
35
  conn;
@@ -597,7 +81,7 @@ var XBMouseImpl = class {
597
81
  } else {
598
82
  await this.move(tx, ty);
599
83
  }
600
- await this.down({ button });
84
+ await this.down({ button, clickCount: opts.clickCount ?? 1 });
601
85
  await sleep(stealth ? rand(...DEFAULT_STEALTH_CONFIG.pressDuration) : opts.delay ?? 0);
602
86
  const rx = stealth ? this._x + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._x;
603
87
  const ry = stealth ? this._y + rand(...DEFAULT_STEALTH_CONFIG.releaseDrift) * (Math.random() < 0.5 ? -1 : 1) : this._y;
@@ -621,7 +105,9 @@ var XBMouseImpl = class {
621
105
  x: this._x,
622
106
  y: this._y,
623
107
  button,
624
- clickCount: 1
108
+ // r23: press 必须与 release 声明同一 clickCount——Chrome 按序列计数
109
+ // 合成 click/dblclick,press 缺声明会把计数器重置(dblclick 永不合成)
110
+ clickCount: opts.clickCount ?? 1
625
111
  });
626
112
  }
627
113
  async up(opts = {}) {
@@ -632,7 +118,7 @@ var XBMouseImpl = class {
632
118
  x: this._x,
633
119
  y: this._y,
634
120
  button,
635
- clickCount: 1
121
+ clickCount: opts.clickCount ?? 1
636
122
  });
637
123
  }
638
124
  async move(x, y, opts = {}) {
@@ -808,7 +294,7 @@ var XBKeyboardImpl = class {
808
294
  if (wrong && wrong !== char) {
809
295
  await this.dispatchKeySequence(resolveKeyMapping(wrong), stealth);
810
296
  await sleep2(rand(120, 420));
811
- await this.dispatchKeySequence(KEY_MAP2.Backspace, stealth);
297
+ await this.dispatchKeySequence(KEY_MAP.Backspace, stealth);
812
298
  }
813
299
  }
814
300
  await this.dispatchKeySequence(resolveKeyMapping(char), stealth);
@@ -911,7 +397,7 @@ var XBKeyboardImpl = class {
911
397
  }
912
398
  };
913
399
  function resolveKeyMapping(key) {
914
- if (KEY_MAP2[key]) return KEY_MAP2[key];
400
+ if (KEY_MAP[key]) return KEY_MAP[key];
915
401
  if (key.length === 1) {
916
402
  const lower = key.toLowerCase();
917
403
  if (lower >= "a" && lower <= "z") {
@@ -928,7 +414,7 @@ function resolveKeyMapping(key) {
928
414
  }
929
415
  return { key, code: key };
930
416
  }
931
- var KEY_MAP2 = {
417
+ var KEY_MAP = {
932
418
  Enter: { key: "Enter", code: "Enter", text: "\r", keyCode: 13 },
933
419
  Tab: { key: "Tab", code: "Tab", text: " ", keyCode: 9 },
934
420
  Escape: { key: "Escape", code: "Escape", keyCode: 27 },
@@ -1289,6 +775,14 @@ var XBLocatorImpl = class _XBLocatorImpl {
1289
775
  await waitForActionable(this.page, this.selector, opts);
1290
776
  await scrollIntoView(this.page, this.selector);
1291
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
+ `);
1292
786
  if (process.env.XBROWSER_STEALTH !== "off" && value.length >= 40 && process.env.XBROWSER_FILL_TYPE !== "type") {
1293
787
  try {
1294
788
  const { pasteViaClipboard, syntheticPaste } = await import("./clipboard-XRP54ENE.js");
@@ -2044,6 +1538,189 @@ var XBPageImpl = class _XBPageImpl {
2044
1538
  await this.conn.send("Network.enable", void 0, this.sessionId);
2045
1539
  await this.conn.send("DOM.enable", void 0, this.sessionId).catch(() => {
2046
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
+ });
2047
1724
  this.setupPageEvents();
2048
1725
  this.setupNetworkEvents();
2049
1726
  this.setupConsoleEvents();
@@ -2484,7 +2161,9 @@ Last error: ${lastError.message}` : "";
2484
2161
  await this.locator(selector).click(opts);
2485
2162
  }
2486
2163
  async dblclick(selector, opts = {}) {
2487
- 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 });
2488
2167
  }
2489
2168
  async fill(selector, value, opts = {}) {
2490
2169
  await this.locator(selector).fill(value, opts);
@@ -2601,6 +2280,26 @@ Last error: ${lastError.message}` : "";
2601
2280
  );
2602
2281
  this._viewportSize = size;
2603
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
+ }
2604
2303
  // ── Scripts ─────────────────────────────────────────────────
2605
2304
  async addInitScript(script) {
2606
2305
  await this.conn.send(
@@ -2824,6 +2523,12 @@ Last error: ${lastError.message}` : "";
2824
2523
  async _cdpSend(method, params) {
2825
2524
  return this.conn.send(method, params, this.sessionId);
2826
2525
  }
2526
+ /** sup-s11: beforeunload 自动应答语义——'accept'(默认,离开页面,与录制
2527
+ * 意图一致)或 'dismiss'(取消导航留守原页,尽力而为:此构建上 CDP
2528
+ * accept:false 对浏览器侧导航的取消语义不稳定,不保证)。 */
2529
+ setBeforeUnloadBehavior(mode) {
2530
+ this._beforeUnloadAccept = mode === "accept";
2531
+ }
2827
2532
  /**
2828
2533
  * 开启/关闭原生文件选择框拦截(CDP stateful 开关)。
2829
2534
  *
@@ -2882,8 +2587,9 @@ Last error: ${lastError.message}` : "";
2882
2587
  }
2883
2588
  };
2884
2589
  this._emit("dialog", dialog);
2590
+ const autoAccept = p.type === "beforeunload" ? this._beforeUnloadAccept : false;
2885
2591
  setTimeout(() => {
2886
- this.conn.send("Page.handleJavaScriptDialog", { accept: false }, this.sessionId).catch(() => {
2592
+ this.conn.send("Page.handleJavaScriptDialog", { accept: autoAccept }, this.sessionId).catch(() => {
2887
2593
  });
2888
2594
  }, 0);
2889
2595
  })
@@ -3026,6 +2732,7 @@ Last error: ${lastError.message}` : "";
3026
2732
  _networkRequests = /* @__PURE__ */ new Map();
3027
2733
  _routeHandlers = [];
3028
2734
  _interceptionEnabled = false;
2735
+ _beforeUnloadAccept = true;
3029
2736
  /** Store network data — called by browser.ts installNetworkCapture or internal event handlers */
3030
2737
  _storeNetworkRequest(requestId, data) {
3031
2738
  this._networkRequests.set(requestId, { requestId, ...data });
@@ -3137,7 +2844,10 @@ Last error: ${lastError.message}` : "";
3137
2844
  if (!this._interceptionEnabled) {
3138
2845
  this._interceptionEnabled = true;
3139
2846
  await this.conn.send("Fetch.enable", {
3140
- patterns: [{ urlPattern: "*", requestStage: "Request" }]
2847
+ patterns: [{ urlPattern: "*", requestStage: "Request" }],
2848
+ // sup-s9: 保留认证自动响应(Fetch.enable 为替换语义,不带此参数
2849
+ // 会顶掉 _init 的 auth 配置)
2850
+ handleAuthRequests: true
3141
2851
  }, this.sessionId);
3142
2852
  this._subscriptions.push(
3143
2853
  this.conn.subscribe("Fetch.requestPaused", this.sessionId, (params) => {
@@ -3190,6 +2900,36 @@ Last error: ${lastError.message}` : "";
3190
2900
  });
3191
2901
  }
3192
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
+ }
3193
2933
  async setInputFiles(selector, files) {
3194
2934
  const fileArr = Array.isArray(files) ? files : [files];
3195
2935
  const fileList = fileArr.map((f) => ({
@@ -3336,6 +3076,14 @@ var XBContextImpl = class {
3336
3076
  get stealthConfig() {
3337
3077
  return this.options.stealthConfig;
3338
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
+ }
3339
3087
  async newPage() {
3340
3088
  if (this.closed) throw new Error("Context is closed");
3341
3089
  const { targetId } = await this._browser._createTarget(this.contextId);
@@ -3565,7 +3313,7 @@ var XBBrowserImpl = class {
3565
3313
  this._exitHandler = null;
3566
3314
  }
3567
3315
  if (this.childProcess) {
3568
- const { killChrome: killChrome2 } = await import("./launcher-EXJHHAUL.js");
3316
+ const { killChrome: killChrome2 } = await import("./launcher-LUOMMGZC.js");
3569
3317
  await killChrome2(this.childProcess, this.tmpDir);
3570
3318
  }
3571
3319
  await this.conn.close();
@@ -3591,6 +3339,38 @@ var XBBrowserImpl = class {
3591
3339
  } catch {
3592
3340
  }
3593
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
+ }
3594
3374
  context.on("page", (page) => {
3595
3375
  this._emitter.emit("page", page);
3596
3376
  });
@@ -3703,7 +3483,7 @@ var XBBrowserImpl = class {
3703
3483
  if (pageTargets.length === 0 && httpFallbackUrl) {
3704
3484
  console.log(`[discoverContexts] Target.getTargets returned ${targetInfos.length} targets (0 page type). Falling back to HTTP /json/list at ${httpFallbackUrl}`);
3705
3485
  try {
3706
- const { getCDPTargets: getCDPTargets2 } = await import("./launcher-EXJHHAUL.js");
3486
+ const { getCDPTargets: getCDPTargets2 } = await import("./launcher-LUOMMGZC.js");
3707
3487
  const httpPages = await getCDPTargets2(httpFallbackUrl);
3708
3488
  console.log(`[discoverContexts] HTTP /json/list returned ${httpPages.length} pages`);
3709
3489
  for (const p of httpPages) {
@@ -5079,14 +4859,23 @@ async function launch(options = {}) {
5079
4859
  }
5080
4860
  const conn = new CDPConnection(wsEndpoint);
5081
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
+ }
5082
4877
  const httpEndpoint = options.cdpEndpoint && !options.cdpEndpoint.startsWith("ws") ? options.cdpEndpoint : void 0;
5083
- const browser = new XBBrowserImpl(
5084
- conn,
5085
- childProcess,
5086
- tmpDir,
5087
- httpEndpoint,
5088
- options.stealthConfig ? { stealthConfig: options.stealthConfig } : void 0
5089
- );
4878
+ const browser = new XBBrowserImpl(conn, childProcess, tmpDir, httpEndpoint, stealthOpts);
5090
4879
  return { browser, wsEndpoint };
5091
4880
  }
5092
4881
  export {