@xkwdstore/agent 2.0.2 → 2.0.4

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.
package/src/stealth.js CHANGED
@@ -1,1251 +1,1251 @@
1
- 'use strict';
2
-
3
- /**
4
- * Comprehensive stealth init script builder.
5
- *
6
- * Returns a string of JavaScript that is injected via
7
- * `context.addInitScript(scriptStr)` — runs on every page and iframe
8
- * before any page script executes.
9
- *
10
- * All spoofing is parameterized by the per-account fingerprint profile
11
- * so each account has a unique, internally-consistent fingerprint.
12
- */
13
-
14
- /**
15
- * Build the init script string for a given fingerprint profile.
16
- * @param {object} fp - Fingerprint profile from fingerprint.js
17
- * @returns {string} JavaScript source to inject
18
- */
19
- function buildStealthScript(fp) {
20
- // We serialize the fingerprint values into the script so they're
21
- // available inside the browser context without closures.
22
- const script = `
23
- (function () {
24
- 'use strict';
25
-
26
- var FP = ${JSON.stringify(fp)};
27
-
28
- // ── 1. Remove navigator.webdriver ──────────────────────────────────────
29
- try {
30
- Object.defineProperty(navigator, 'webdriver', { get: () => false, configurable: true });
31
- } catch (e) {}
32
-
33
- // ── 2. (removed) browser runtime stub ───────────────────────────────────
34
- // The agent only ever launches Firefox, where non-Firefox runtime objects
35
- // are undefined. Any previous stub was dead code and is kept out to avoid
36
- // confusion.
37
-
38
- // ── 3. navigator.plugins + mimeTypes (Chrome-style) ───────────────────
39
- if (typeof navigator.plugins !== 'undefined') {
40
- var fakePlugins = [
41
- { name: 'PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
42
- { name: 'Chrome PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
43
- { name: 'Chromium PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
44
- { name: 'Microsoft Edge PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
45
- { name: 'WebKit built-in PDF', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
46
- ];
47
- var fakeMimeTypes = [
48
- { type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format' },
49
- { type: 'application/x-pdf', suffixes: 'pdf', description: 'Portable Document Format' },
50
- { type: 'application/x-nacl', suffixes: '', description: 'Native Client Executable' },
51
- ];
52
- try {
53
- Object.defineProperty(navigator, 'plugins', {
54
- get: function () {
55
- var arr = fakePlugins.map(function (p) {
56
- return Object.assign({}, p, { length: fakeMimeTypes.length });
57
- });
58
- arr.length = fakePlugins.length;
59
- arr.item = function (i) { return arr[i] || null; };
60
- arr.namedItem = function (n) { return arr.find(function (p) { return p.name === n; }) || null; };
61
- arr.refresh = function () {};
62
- return arr;
63
- },
64
- configurable: true,
65
- });
66
- } catch (e) {}
67
- try {
68
- Object.defineProperty(navigator, 'mimeTypes', {
69
- get: function () {
70
- var arr = fakeMimeTypes.map(function (m) {
71
- return Object.assign({}, m, { enabledPlugin: fakePlugins[0] });
72
- });
73
- arr.length = fakeMimeTypes.length;
74
- arr.item = function (i) { return arr[i] || null; };
75
- arr.namedItem = function (n) { return arr.find(function (m) { return m.type === n; }) || null; };
76
- return arr;
77
- },
78
- configurable: true,
79
- });
80
- } catch (e) {}
81
- } // end if not Firefox
82
-
83
- // ── 4. navigator.languages (from fingerprint) ──────────────────────────
84
- try {
85
- Object.defineProperty(navigator, 'languages', {
86
- get: function () { return FP.languages.slice(); },
87
- configurable: true,
88
- });
89
- } catch (e) {}
90
-
91
- // ── 5. navigator.platform ──────────────────────────────────────────────
92
- try {
93
- Object.defineProperty(navigator, 'platform', {
94
- get: function () { return FP.platform; },
95
- configurable: true,
96
- });
97
- } catch (e) {}
98
-
99
- // ── 6. navigator.hardwareConcurrency ───────────────────────────────────
100
- try {
101
- Object.defineProperty(navigator, 'hardwareConcurrency', {
102
- get: function () { return FP.hardwareConcurrency; },
103
- configurable: true,
104
- });
105
- } catch (e) {}
106
-
107
- // ── 7. navigator.deviceMemory ──────────────────────────────────────────
108
- try {
109
- Object.defineProperty(navigator, 'deviceMemory', {
110
- get: function () { return FP.deviceMemory; },
111
- configurable: true,
112
- });
113
- } catch (e) {}
114
-
115
- // ── 8. navigator.userAgentData (Sec-CH-UA client hints) ────────────────
116
- try {
117
- if (navigator.userAgentData) {
118
- var origGetHighEntropyValues = navigator.userAgentData.getHighEntropyValues.bind(navigator.userAgentData);
119
- navigator.userAgentData.getHighEntropyValues = function (hints) {
120
- return origGetHighEntropyValues(hints).then(function (orig) {
121
- orig.platform = FP.userAgentDataPlatform;
122
- orig.platformVersion = '10.0.0';
123
- orig.architecture = 'x86';
124
- orig.bitness = '64';
125
- orig.model = '';
126
- orig.uaFullVersion = (navigator.userAgent.match(/Chrome\\/([\\d.]+)/) || [])[1] || '149.0.0.0';
127
- return orig;
128
- });
129
- };
130
- }
131
- } catch (e) {}
132
-
133
- // ── 9. Screen properties ───────────────────────────────────────────────
134
- try {
135
- Object.defineProperty(screen, 'width', { get: function () { return FP.screen.width; }, configurable: true });
136
- Object.defineProperty(screen, 'height', { get: function () { return FP.screen.height; }, configurable: true });
137
- Object.defineProperty(screen, 'availWidth', { get: function () { return FP.screen.width; }, configurable: true });
138
- Object.defineProperty(screen, 'availHeight', { get: function () { return FP.screen.height - 40; }, configurable: true });
139
- Object.defineProperty(screen, 'colorDepth', { get: function () { return 24; }, configurable: true });
140
- Object.defineProperty(screen, 'pixelDepth', { get: function () { return 24; }, configurable: true });
141
- } catch (e) {}
142
-
143
- // ── 10. Permissions API (comprehensive) ────────────────────────────────
144
- try {
145
- var origQuery = navigator.permissions ? navigator.permissions.query.bind(navigator.permissions) : null;
146
- if (origQuery) {
147
- var permStates = {
148
- 'notifications': (typeof Notification !== 'undefined') ? Notification.permission : 'default',
149
- 'geolocation': 'prompt',
150
- 'camera': 'prompt',
151
- 'microphone': 'prompt',
152
- 'clipboard-read': 'prompt',
153
- 'clipboard-write': 'granted',
154
- 'persistent-storage': 'prompt',
155
- };
156
- navigator.permissions.query = function (parameters) {
157
- var name = parameters && parameters.name;
158
- if (permStates.hasOwnProperty(name)) {
159
- return Promise.resolve({ state: permStates[name], onchange: null });
160
- }
161
- return origQuery(parameters);
162
- };
163
- }
164
- } catch (e) {}
165
-
166
- // ── 11. WebGL vendor/renderer spoofing (per-account) ───────────────────
167
- try {
168
- var spoofWebGL = function (proto) {
169
- var origGetParameter = proto.getParameter;
170
- proto.getParameter = function (parameter) {
171
- // UNMASKED_VENDOR_WEBGL = 37445, UNMASKED_RENDERER_WEBGL = 37446
172
- if (parameter === 37445) return FP.gpu.vendor;
173
- if (parameter === 37446) return FP.gpu.renderer;
174
- return origGetParameter.call(this, parameter);
175
- };
176
- // Also spoof MAX_TEXTURE_SIZE and other params slightly for diversity
177
- var origGetExtension = proto.getExtension;
178
- proto.getExtension = function (name) {
179
- return origGetExtension.call(this, name);
180
- };
181
- };
182
- if (window.WebGLRenderingContext) spoofWebGL(WebGLRenderingContext.prototype);
183
- if (window.WebGL2RenderingContext) spoofWebGL(WebGL2RenderingContext.prototype);
184
- } catch (e) {}
185
-
186
- // ── 12. Canvas fingerprint noise ───────────────────────────────────────
187
- // Per-pixel noise driven by a seeded PRNG so the pattern is stable per
188
- // account but varies across pixels (both up and down). The old fixed-stride
189
- // "+1 at (i+seed)%7===0" was detectable because it only ever brightened.
190
- try {
191
- var seed = (FP.canvasNoiseSeed >>> 0) || 1;
192
- function cnvRand() {
193
- seed |= 0; seed = (seed + 0x6D2B79F5) | 0;
194
- var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
195
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
196
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
197
- }
198
- function applyCanvasNoise(data) {
199
- for (var i = 0; i < data.length; i += 4) {
200
- // ±2 per channel, pseudo-random, stable per-account
201
- data[i] = (data[i] + ((cnvRand() * 5) | 0) - 2) & 0xFF; // R
202
- data[i + 1] = (data[i + 1] + ((cnvRand() * 5) | 0) - 2) & 0xFF; // G
203
- data[i + 2] = (data[i + 2] + ((cnvRand() * 5) | 0) - 2) & 0xFF; // B
204
- // Alpha untouched
205
- }
206
- }
207
- var origToDataURL = HTMLCanvasElement.prototype.toDataURL;
208
- HTMLCanvasElement.prototype.toDataURL = function () {
209
- var ctx = this.getContext('2d');
210
- if (ctx && this.width > 0 && this.height > 0) {
211
- try {
212
- var imageData = ctx.getImageData(0, 0, Math.min(this.width, 16), Math.min(this.height, 16));
213
- applyCanvasNoise(imageData.data);
214
- ctx.putImageData(imageData, 0, 0);
215
- } catch (e) {}
216
- }
217
- return origToDataURL.apply(this, arguments);
218
- };
219
-
220
- var origGetImageData = CanvasRenderingContext2D.prototype.getImageData;
221
- CanvasRenderingContext2D.prototype.getImageData = function () {
222
- var imageData = origGetImageData.apply(this, arguments);
223
- try { applyCanvasNoise(imageData.data); } catch (e) {}
224
- return imageData;
225
- };
226
- } catch (e) {}
227
-
228
- // ── 13. AudioContext fingerprint noise ─────────────────────────────────
229
- // Larger, varied offsets per sample (driven by a per-account seeded PRNG)
230
- // so the noise is stable per account but not a detectable fixed tiny shift.
231
- try {
232
- var audioSeed = (FP.canvasNoiseSeed >>> 0) || 1;
233
- function audioRand() {
234
- audioSeed |= 0; audioSeed = (audioSeed + 0x6D2B79F5) | 0;
235
- var t = Math.imul(audioSeed ^ (audioSeed >>> 15), 1 | audioSeed);
236
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
237
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
238
- }
239
- var origCreateAnalyser = (window.OfflineAudioContext || window.webkitOfflineAudioContext);
240
- if (origCreateAnalyser) {
241
- var OrigOAC = window.OfflineAudioContext || window.webkitOfflineAudioContext;
242
- var origGetChannelData = AudioBuffer.prototype.getChannelData;
243
- AudioBuffer.prototype.getChannelData = function () {
244
- var data = origGetChannelData.apply(this, arguments);
245
- try {
246
- for (var i = 0; i < data.length; i++) {
247
- // Vary every Nth sample by a larger ±1e-4 offset, pseudo-random
248
- if (i % 50 === 0) data[i] = (data[i] + (audioRand() - 0.5) * 2e-4);
249
- }
250
- } catch (e) {}
251
- return data;
252
- };
253
- }
254
- } catch (e) {}
255
-
256
- // ── 14. WebRTC IP leak prevention (CRITICAL for proxy isolation) ──────
257
- // Firefox uses both RTCPeerConnection and mozRTCPeerConnection.
258
- // We must block ALL WebRTC to prevent the real IP from leaking.
259
- try {
260
- // Completely disable WebRTC by making RTCPeerConnection a no-op
261
- if (window.RTCPeerConnection) {
262
- var OrigRTC = window.RTCPeerConnection;
263
- window.RTCPeerConnection = function () {
264
- var args = arguments;
265
- if (args[0] && args[0].iceServers) {
266
- // Strip all ICE servers — no STUN, no TURN
267
- args[0].iceServers = [];
268
- }
269
- var pc = new OrigRTC(args[0], args[1]);
270
- // Block all ICE candidates — never emit local IP
271
- var origAddIceCandidate = pc.addIceCandidate.bind(pc);
272
- pc.addIceCandidate = function (candidate) {
273
- if (candidate && candidate.candidate) {
274
- // Drop ALL candidates (host, srflx, relay) to prevent IP leak
275
- return Promise.resolve();
276
- }
277
- return origAddIceCandidate(candidate);
278
- };
279
- // Scrub all local IPs from getStats()
280
- var origGetStats = pc.getStats ? pc.getStats.bind(pc) : null;
281
- if (origGetStats) {
282
- pc.getStats = function () {
283
- return origGetStats.apply(this, arguments).then(function (report) {
284
- try {
285
- report.forEach(function (stat) {
286
- if (stat && typeof stat === 'object') {
287
- if (typeof stat.ip === 'string') stat.ip = '0.0.0.0';
288
- if (typeof stat.address === 'string') stat.address = '0.0.0.0';
289
- if (typeof stat.relatedAddress === 'string') stat.relatedAddress = '0.0.0.0';
290
- if (typeof stat.localAddress === 'string') stat.localAddress = '0.0.0.0';
291
- if (typeof stat.remoteAddress === 'string') stat.remoteAddress = '0.0.0.0';
292
- }
293
- });
294
- } catch (e) {}
295
- return report;
296
- });
297
- };
298
- }
299
- // Strip host candidates from localDescription SDP
300
- try {
301
- var origLocalDesc = Object.getOwnPropertyDescriptor(pc, 'localDescription') ||
302
- Object.getOwnPropertyDescriptor(Object.getPrototypeOf(pc), 'localDescription');
303
- if (origLocalDesc && origLocalDesc.get) {
304
- var origLDGet = origLocalDesc.get;
305
- Object.defineProperty(pc, 'localDescription', {
306
- get: function () {
307
- var desc = origLDGet.call(this);
308
- if (desc && typeof desc.sdp === 'string') {
309
- desc = { type: desc.type, sdp: desc.sdp.replace(/a=candidate:[^\r\n]*\s(host|srflx)[^\r\n]*/gi, 'a=candidate:removed') };
310
- }
311
- return desc;
312
- },
313
- configurable: true,
314
- });
315
- }
316
- } catch (e) {}
317
- return pc;
318
- };
319
- window.RTCPeerConnection.prototype = OrigRTC.prototype;
320
- }
321
- // Also handle Firefox-specific mozRTCPeerConnection
322
- if (window.mozRTCPeerConnection) {
323
- var OrigMozRTC = window.mozRTCPeerConnection;
324
- window.mozRTCPeerConnection = function () {
325
- var args = arguments;
326
- if (args[0] && args[0].iceServers) {
327
- args[0].iceServers = [];
328
- }
329
- return new OrigMozRTC(args[0], args[1]);
330
- };
331
- window.mozRTCPeerConnection.prototype = OrigMozRTC.prototype;
332
- }
333
- // Also override webkitRTCPeerConnection if it exists
334
- if (window.webkitRTCPeerConnection && !window.RTCPeerConnection) {
335
- window.RTCPeerConnection = window.webkitRTCPeerConnection;
336
- }
337
- } catch (e) {}
338
-
339
- // ── 15. CDP / DevTools detection mitigation ────────────────────────────
340
- try {
341
- // Remove window.cdc_ properties (automation driver markers)
342
- Object.keys(window).forEach(function (k) {
343
- if (k.startsWith('cdc_') || k.startsWith('$cdc_')) {
344
- try { delete window[k]; } catch (e) {}
345
- }
346
- });
347
- // Override console.debug to prevent CDP detection via binding
348
- var origDebug = console.debug;
349
- console.debug = function () {
350
- // Check if called with a specific CDP detection marker
351
- if (arguments.length === 1 && typeof arguments[0] === 'string' && arguments[0].startsWith('cdp')) {
352
- return; // Swallow CDP probe
353
- }
354
- return origDebug.apply(console, arguments);
355
- };
356
- } catch (e) {}
357
-
358
- // ── 16. iframe contentWindow hardening ─────────────────────────────────
359
- try {
360
- var origContentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
361
- if (origContentWindow && origContentWindow.get) {
362
- var origGet = origContentWindow.get;
363
- Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', {
364
- get: function () {
365
- var w = origGet.call(this);
366
- if (w) {
367
- try { Object.defineProperty(w.navigator, 'webdriver', { get: () => false }); } catch (e) {}
368
- }
369
- return w;
370
- },
371
- configurable: true,
372
- });
373
- }
374
- } catch (e) {}
375
-
376
- // ── 17. Notification permission consistency ────────────────────────────
377
- try {
378
- if (window.Notification) {
379
- Object.defineProperty(Notification, 'permission', {
380
- get: function () { return 'default'; },
381
- configurable: true,
382
- });
383
- }
384
- } catch (e) {}
385
-
386
- // ── 18. Hairline feature detection fix ─────────────────────────────────
387
- try {
388
- // Some bot detection checks for the -webkit-hairline feature
389
- var origMatchMedia = window.matchMedia;
390
- window.matchMedia = function (query) {
391
- var result = origMatchMedia.call(this, query);
392
- if (query && query.indexOf('hairline') !== -1) {
393
- return { matches: false, media: query, addListener: function () {}, removeListener: function () {} };
394
- }
395
- return result;
396
- };
397
- } catch (e) {}
398
-
399
- // ── 19. navigator.connection (Network Information API) ─────────────────
400
- try {
401
- if (navigator.connection) {
402
- Object.defineProperty(navigator.connection, 'effectiveType', { get: function () { return FP.connection.effectiveType; }, configurable: true });
403
- Object.defineProperty(navigator.connection, 'downlink', { get: function () { return FP.connection.downlink; }, configurable: true });
404
- Object.defineProperty(navigator.connection, 'rtt', { get: function () { return FP.connection.rtt; }, configurable: true });
405
- Object.defineProperty(navigator.connection, 'saveData', { get: function () { return false; }, configurable: true });
406
- }
407
- } catch (e) {}
408
-
409
- // ── 20. navigator.getBattery() spoofing ───────────────────────────────
410
- try {
411
- if (navigator.getBattery) {
412
- navigator.getBattery = function () {
413
- return Promise.resolve({
414
- charging: FP.battery.charging,
415
- chargingTime: FP.battery.charging ? 1280 : Infinity,
416
- dischargingTime: FP.battery.charging ? Infinity : 12600,
417
- level: FP.battery.level,
418
- addEventListener: function () {},
419
- removeEventListener: function () {},
420
- });
421
- };
422
- }
423
- } catch (e) {}
424
-
425
- // ── 21. navigator.mediaDevices.enumerateDevices() spoofing ─────────────
426
- try {
427
- if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
428
- var origEnumerate = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
429
- navigator.mediaDevices.enumerateDevices = function () {
430
- return origEnumerate().then(function (realDevices) {
431
- // If real devices exist, keep them but randomize IDs
432
- if (realDevices && realDevices.length > 0) return realDevices;
433
- // Otherwise return fake devices based on fingerprint
434
- var fake = [];
435
- var counts = FP.mediaDevices;
436
- for (var i = 0; i < counts.audioinput; i++) fake.push({ kind: 'audioinput', deviceId: 'default', label: '', groupId: 'group' + i });
437
- for (var i = 0; i < counts.audiooutput; i++) fake.push({ kind: 'audiooutput', deviceId: 'default', label: '', groupId: 'group' + i });
438
- for (var i = 0; i < counts.videoinput; i++) fake.push({ kind: 'videoinput', deviceId: 'default', label: '', groupId: 'group' + i });
439
- return fake;
440
- });
441
- };
442
- }
443
- } catch (e) {}
444
-
445
- // ── 22. Font fingerprinting defense ─────────────────────────────────────
446
- try {
447
- if (document.fonts && document.fonts.check) {
448
- var origFontCheck = document.fonts.check.bind(document.fonts);
449
- document.fonts.check = function (font, text) {
450
- // Return true for common fonts, false for uncommon probe fonts
451
- var commonFonts = ['Arial', 'Helvetica', 'Times New Roman', 'Courier New', 'Georgia', 'Verdana', 'Tahoma', 'Trebuchet MS', 'Segoe UI', 'Calibri'];
452
- for (var i = 0; i < commonFonts.length; i++) {
453
- if (font && font.indexOf(commonFonts[i]) !== -1) return true;
454
- }
455
- return origFontCheck(font, text);
456
- };
457
- }
458
- } catch (e) {}
459
-
460
- // ── 23. Intl properties aligned with locale/timezone ───────────────────
461
- try {
462
- var origDateTimeFormat = window.Intl.DateTimeFormat;
463
- window.Intl.DateTimeFormat = function () {
464
- var args = Array.prototype.slice.call(arguments);
465
- if (!args[0]) args[0] = FP.locale;
466
- if (!args[1] || !args[1].timeZone) {
467
- args[1] = args[1] || {};
468
- args[1].timeZone = FP.timezone;
469
- }
470
- return new origDateTimeFormat(args[0], args[1]);
471
- };
472
- window.Intl.DateTimeFormat.prototype = origDateTimeFormat.prototype;
473
- } catch (e) {}
474
-
475
- // ── 24. window.outerWidth/outerHeight aligned with screen ───────────────
476
- try {
477
- Object.defineProperty(window, 'outerWidth', { get: function () { return FP.screen.width; }, configurable: true });
478
- Object.defineProperty(window, 'outerHeight', { get: function () { return FP.screen.height; }, configurable: true });
479
- } catch (e) {}
480
-
481
- // ── 25. navigator.maxTouchPoints (0 for desktop) ────────────────────────
482
- try {
483
- Object.defineProperty(navigator, 'maxTouchPoints', {
484
- get: function () { return FP.isMobile ? 5 : 0; },
485
- configurable: true,
486
- });
487
- } catch (e) {}
488
-
489
- // ── 26. navigator.oscpu (Firefox-specific) ──────────────────────────────
490
- try {
491
- Object.defineProperty(navigator, 'oscpu', {
492
- get: function () { return FP.oscpu; },
493
- configurable: true,
494
- });
495
- } catch (e) {}
496
-
497
- // ── 27. navigator.buildID (Firefox-specific) ────────────────────────────
498
- try {
499
- Object.defineProperty(navigator, 'buildID', {
500
- get: function () { return FP.buildID; },
501
- configurable: true,
502
- });
503
- } catch (e) {}
504
-
505
- // ── 28. screen.availLeft/availTop ───────────────────────────────────────
506
- try {
507
- Object.defineProperty(screen, 'availLeft', { get: function () { return 0; }, configurable: true });
508
- Object.defineProperty(screen, 'availTop', { get: function () { return 0; }, configurable: true });
509
- } catch (e) {}
510
-
511
- // ── 29. document.hasStorageAccess() ────────────────────────────────────
512
- try {
513
- if (document.hasStorageAccess) {
514
- var origHasStorageAccess = document.hasStorageAccess.bind(document);
515
- document.hasStorageAccess = function () {
516
- return Promise.resolve(true);
517
- };
518
- }
519
- } catch (e) {}
520
-
521
- // ── 30. navigator.serviceWorker consistency ────────────────────────────
522
- try {
523
- // Ensure serviceWorker exists (real browsers have it)
524
- if (!navigator.serviceWorker) {
525
- Object.defineProperty(navigator, 'serviceWorker', {
526
- get: function () { return { register: function () { return Promise.reject(); }, getRegistrations: function () { return Promise.resolve([]); } }; },
527
- configurable: true,
528
- });
529
- }
530
- } catch (e) {}
531
-
532
- // ── 31. window.history.length padding ──────────────────────────────────
533
- try {
534
- // Don't override history.length (read-only), but push some states
535
- // to make it look like the user has been browsing
536
- if (window.history.length < 3) {
537
- try { window.history.pushState({}, '', window.location.href); } catch (e) {}
538
- try { window.history.pushState({}, '', window.location.href); } catch (e) {}
539
- }
540
- } catch (e) {}
541
-
542
- // ── 32. Performance.now() timing jitter ────────────────────────────────
543
- try {
544
- // Per-account seeded PRNG (mulberry32) so jitter is stable per account but
545
- // pseudo-random across calls — a sinusoidal jitter (the old impl) is
546
- // detectable by sampling many calls. Jitter is ±0.02ms.
547
- var perfSeed = (FP.perfJitter || 1) >>> 0;
548
- var perfState = perfSeed;
549
- function perfRand() {
550
- perfState |= 0; perfState = (perfState + 0x6D2B79F5) | 0;
551
- var t = Math.imul(perfState ^ (perfState >>> 15), 1 | perfState);
552
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
553
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
554
- }
555
- var origNow = Performance.prototype.now;
556
- Performance.prototype.now = function () {
557
- var real = origNow.call(this);
558
- return real + (perfRand() - 0.5) * 0.04;
559
- };
560
- } catch (e) {}
561
-
562
- // ── 33. navigator.doNotTrack consistency ───────────────────────────────
563
- try {
564
- Object.defineProperty(navigator, 'doNotTrack', {
565
- get: function () { return '1'; },
566
- configurable: true,
567
- });
568
- } catch (e) {}
569
-
570
- // ── 34. window.devicePixelRatio aligned with fingerprint ───────────────
571
- try {
572
- Object.defineProperty(window, 'devicePixelRatio', {
573
- get: function () { return FP.devicePixelRatio || 1; },
574
- configurable: true,
575
- });
576
- } catch (e) {}
577
-
578
- // ── 35. SpeechSynthesis API consistency ────────────────────────────────
579
- try {
580
- if (window.speechSynthesis) {
581
- var origGetVoices = window.speechSynthesis.getVoices.bind(window.speechSynthesis);
582
- window.speechSynthesis.getVoices = function () {
583
- var voices = origGetVoices();
584
- if (voices && voices.length > 0) return voices;
585
- // Return a minimal set if none available
586
- return [
587
- { name: 'Microsoft David - English (United States)', lang: 'en-US', localService: true, default: true, voiceURI: 'Microsoft David' },
588
- { name: 'Microsoft Zira - English (United States)', lang: 'en-US', localService: true, default: false, voiceURI: 'Microsoft Zira' },
589
- ];
590
- };
591
- }
592
- } catch (e) {}
593
-
594
- // ── 36. navigator.vendor / navigator.product (Chrome-specific) ─────────
595
- try {
596
- Object.defineProperty(navigator, 'vendor', {
597
- get: function () { return 'Google Inc.'; },
598
- configurable: true,
599
- });
600
- Object.defineProperty(navigator, 'product', {
601
- get: function () { return 'Gecko'; },
602
- configurable: true,
603
- });
604
- Object.defineProperty(navigator, 'productSub', {
605
- get: function () { return '20030107'; },
606
- configurable: true,
607
- });
608
- } catch (e) {}
609
-
610
- // ── 36b. window.chrome object (CRITICAL — Chrome detection) ───────────
611
- // Sites check window.chrome to detect if browser is Chrome.
612
- // Playwright Chromium has a partial chrome object — fill it completely.
613
- try {
614
- if (!window.chrome) {
615
- window.chrome = {};
616
- }
617
- // runtime object — most commonly checked
618
- if (!window.chrome.runtime) {
619
- window.chrome.runtime = {
620
- OnInstalledReason: { CHROME_UPDATE: 'chrome_update', INSTALL: 'install', UPDATE: 'update' },
621
- OnRestartRequiredReason: { APP_UPDATE: 'app_update', OS_UPDATE: 'os_update', PERIODIC: 'periodic' },
622
- PlatformArch: { ARM: 'arm', ARM64: 'arm64', MIPS: 'mips', MIPS64: 'mips64', X86_32: 'x86-32', X86_64: 'x86-64' },
623
- PlatformNaclArch: { ARM: 'arm', MIPS: 'mips', MIPS64: 'mips64', X86_32: 'x86-32', X86_64: 'x86-64' },
624
- PlatformOs: { ANDROID: 'android', CROS: 'cros', LINUX: 'linux', MAC: 'mac', OPENBSD: 'openbsd', WIN: 'win' },
625
- RequestUpdateCheckStatus: { NO_UPDATE: 'no_update', THROTTLED: 'throttled', UPDATE_AVAILABLE: 'update_available' },
626
- connect: function () {},
627
- sendMessage: function () {},
628
- };
629
- }
630
- // app object
631
- if (!window.chrome.app) {
632
- window.chrome.app = {
633
- isInstalled: false,
634
- InstallState: { DISABLED: 'disabled', INSTALLED: 'installed', NOT_INSTALLED: 'not_installed' },
635
- RunningState: { CANNOT_RUN: 'cannot_run', READY_TO_RUN: 'ready_to_run', RUNNING: 'running' },
636
- getDetails: function () { return null; },
637
- getIsInstalled: function () { return false; },
638
- };
639
- }
640
- // csi and loadTimes (used by bot detection)
641
- if (!window.chrome.csi) {
642
- window.chrome.csi = function () { return { startE: Date.now(), onloadT: Date.now(), pageT: Math.random() * 5000 + 1000, tran: 15 }; };
643
- }
644
- if (!window.chrome.loadTimes) {
645
- window.chrome.loadTimes = function () {
646
- return {
647
- commitLoadTime: Date.now() / 1000 - Math.random() * 10,
648
- connectionInfo: 'h2',
649
- finishDocumentLoadTime: Date.now() / 1000 - Math.random() * 5,
650
- finishLoadTime: Date.now() / 1000 - Math.random() * 3,
651
- firstPaintAfterLoadTime: 0,
652
- firstPaintTime: Date.now() / 1000 - Math.random() * 8,
653
- navigationType: 'Other',
654
- npnNegotiatedProtocol: 'h2',
655
- requestTime: Date.now() / 1000 - Math.random() * 15,
656
- startDnsTime: Date.now() / 1000 - Math.random() * 14,
657
- startLoadTime: Date.now() / 1000 - Math.random() * 12,
658
- wasAlternateProtocolAvailable: false,
659
- wasFetchedViaSpdy: true,
660
- wasNpnNegotiated: true,
661
- };
662
- };
663
- }
664
- } catch (e) {}
665
-
666
- // ── 36c. Sec-CH-UA client hints (Chrome-specific anti-detection) ───────
667
- try {
668
- if (navigator.userAgentData) {
669
- // Override brands with Chrome-specific values
670
- Object.defineProperty(navigator.userAgentData, 'brands', {
671
- get: function () {
672
- return [
673
- { brand: 'Chromium', version: FP.chromeVersion || '125' },
674
- { brand: 'Google Chrome', version: FP.chromeVersion || '125' },
675
- { brand: 'Not.A/Brand', version: '99' },
676
- ];
677
- },
678
- configurable: true,
679
- });
680
- Object.defineProperty(navigator.userAgentData, 'mobile', {
681
- get: function () { return FP.isMobile || false; },
682
- configurable: true,
683
- });
684
- Object.defineProperty(navigator.userAgentData, 'platform', {
685
- get: function () { return FP.userAgentDataPlatform || 'Windows'; },
686
- configurable: true,
687
- });
688
- }
689
- } catch (e) {}
690
-
691
- // ── 36d. Remove Firefox-specific properties (not in Chrome) ───────────
692
- try {
693
- // Chrome doesn't have navigator.oscpu or navigator.buildID
694
- if (navigator.oscpu !== undefined) {
695
- Object.defineProperty(navigator, 'oscpu', {
696
- get: function () { return undefined; },
697
- configurable: true,
698
- });
699
- }
700
- if (navigator.buildID !== undefined) {
701
- Object.defineProperty(navigator, 'buildID', {
702
- get: function () { return undefined; },
703
- configurable: true,
704
- });
705
- }
706
- } catch (e) {}
707
-
708
- // ── 37. Geolocation API — block real location leak ─────────────────────
709
- try {
710
- if (navigator.geolocation) {
711
- var origGetCurrentPosition = navigator.geolocation.getCurrentPosition.bind(navigator.geolocation);
712
- var origWatchPosition = navigator.geolocation.watchPosition.bind(navigator.geolocation);
713
- // Return an error so sites can't get real GPS coordinates
714
- navigator.geolocation.getCurrentPosition = function (success, error) {
715
- if (error) error({ code: 1, message: 'User denied Geolocation' });
716
- };
717
- navigator.geolocation.watchPosition = function (success, error) {
718
- if (error) error({ code: 1, message: 'User denied Geolocation' });
719
- return 0;
720
- };
721
- }
722
- } catch (e) {}
723
-
724
- // ── 38. navigator.connection.effectiveType spoofing (extra) ───────────
725
- try {
726
- if (navigator.connection) {
727
- Object.defineProperty(navigator.connection, 'type', {
728
- get: function () { return 'wifi'; },
729
- configurable: true,
730
- });
731
- }
732
- } catch (e) {}
733
-
734
- // ── 39. (removed — Chrome NEEDS window.chrome, don't delete it) ────────
735
-
736
- // ── 40. navigator.credentials API — prevent credential leak ───────────
737
- try {
738
- if (navigator.credentials) {
739
- var origGet = navigator.credentials.get.bind(navigator.credentials);
740
- navigator.credentials.get = function () { return Promise.resolve(null); };
741
- }
742
- } catch (e) {}
743
-
744
- // ── 41. Disable WebRTC leak via mediaDevices (getDisplayMedia) ─────────
745
- try {
746
- if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
747
- var origGetDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
748
- navigator.mediaDevices.getDisplayMedia = function () {
749
- return Promise.reject(new Error('Permission denied'));
750
- };
751
- }
752
- } catch (e) {}
753
-
754
- // ── 37. navigator.cookieEnabled / navigator.onLine ────────────────────
755
- try {
756
- Object.defineProperty(navigator, 'cookieEnabled', {
757
- get: function () { return true; },
758
- configurable: true,
759
- });
760
- Object.defineProperty(navigator, 'onLine', {
761
- get: function () { return true; },
762
- configurable: true,
763
- });
764
- } catch (e) {}
765
-
766
- // ── 38. document.visibilityState / window focus events ───────────────
767
- // Twitter checks if the tab is active/focused — Playwright tabs can report 'hidden'
768
- try {
769
- Object.defineProperty(document, 'visibilityState', {
770
- get: function () { return 'visible'; },
771
- configurable: true,
772
- });
773
- Object.defineProperty(document, 'hidden', {
774
- get: function () { return false; },
775
- configurable: true,
776
- });
777
- Object.defineProperty(document, 'webkitVisibilityState', {
778
- get: function () { return 'visible'; },
779
- configurable: true,
780
- });
781
- Object.defineProperty(document, 'webkitHidden', {
782
- get: function () { return false; },
783
- configurable: true,
784
- });
785
- // Ensure hasFocus returns true
786
- document.hasFocus = function () { return true; };
787
- // Dispatch focus events to simulate active tab
788
- try { window.dispatchEvent(new Event('focus')); } catch (e) {}
789
- try { document.dispatchEvent(new Event('visibilitychange')); } catch (e) {}
790
- } catch (e) {}
791
-
792
- // ── 39. event.isTrusted enforcement ────────────────────────────────────
793
- // Twitter checks if click/keyboard events have isTrusted=true.
794
- // Playwright's mouse.click produces trusted events, but element.click() and
795
- // dispatchEvent() do not. Rather than blanket-patching HTMLElement.click
796
- // (which drops focus/activation behavior and breaks form submit), we only
797
- // intercept .click() and re-dispatch a MouseEvent when the browser would
798
- // otherwise produce an untrusted event. If the platform already produces a
799
- // trusted click (Playwright's .click() path), the original is preserved.
800
- try {
801
- var origElClick = HTMLElement.prototype.click;
802
- HTMLElement.prototype.click = function () {
803
- try {
804
- // Probe: synthesize a click event and check isTrusted. If the engine
805
- // already produces trusted clicks for programmatic .click(), bail.
806
- var probe = new MouseEvent('click', { bubbles: false, cancelable: false });
807
- if (probe.isTrusted) {
808
- return origElClick.call(this);
809
- }
810
- var rect = this.getBoundingClientRect();
811
- var x = rect.left + rect.width / 2;
812
- var y = rect.top + rect.height / 2;
813
- var evt = new MouseEvent('click', {
814
- bubbles: true, cancelable: true, view: window,
815
- clientX: x, clientY: y,
816
- });
817
- this.dispatchEvent(evt);
818
- } catch (e) {
819
- return origElClick.call(this);
820
- }
821
- };
822
- } catch (e) {}
823
-
824
- // ── 40. Date.prototype.getTimezoneOffset aligned with timezone ────────
825
- try {
826
- // Compute offset from the fingerprint timezone
827
- var tzOffset = (function () {
828
- try {
829
- var formatter = new Intl.DateTimeFormat('en-US', { timeZone: FP.timezone, timeZoneName: 'short' });
830
- var parts = formatter.formatToParts(new Date());
831
- var tzName = parts.find(function (p) { return p.type === 'timeZoneName'; });
832
- if (!tzName) return 0;
833
- // Approximate offset from common timezone abbreviations
834
- var offsets = {
835
- 'EST': 300, 'EDT': 240, 'CST': 360, 'CDT': 300, 'MST': 420, 'MDT': 360,
836
- 'PST': 480, 'PDT': 420, 'GMT': 0, 'BST': -60, 'CET': -60, 'CEST': -120,
837
- 'EET': -120, 'EEST': -180, 'MSK': -180, 'AST': 240, 'AKST': 540, 'AKDT': 480,
838
- 'HST': 600, 'JST': -540, 'KST': -540, 'IST': -330, 'PKT': -300,
839
- 'WIB': -420, 'ICT': -420, 'SGT': -480, 'HKT': -480, 'AST_AR': -180,
840
- };
841
- // Try to get offset by comparing local time with target timezone
842
- var now = new Date();
843
- var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
844
- var target = new Date(utc.toLocaleString('en-US', { timeZone: FP.timezone }));
845
- var localNow = new Date(utc.toLocaleString('en-US'));
846
- return Math.round((localNow - target) / 60000);
847
- } catch (e) { return 0; }
848
- })();
849
- Object.defineProperty(Date.prototype, 'getTimezoneOffset', {
850
- value: function () { return tzOffset; },
851
- configurable: true,
852
- });
853
- // Spoof Date.prototype.toString / toTimeString / toLocaleString so they
854
- // agree with the spoofed offset and timezone. Without this, a detector
855
- // can compare new Date().toString() (native tz) against the spoofed
856
- // getTimezoneOffset() and catch the mismatch.
857
- try {
858
- var origToString = Date.prototype.toString;
859
- var origToTimeString = Date.prototype.toTimeString;
860
- var origToLocaleString = Date.prototype.toLocaleString;
861
- var origToLocaleTimeString = Date.prototype.toLocaleTimeString;
862
- function shiftMs(d) {
863
- // milliseconds between native offset and spoofed offset
864
- var native = d.getTimezoneOffset ? 0 : 0; // native already overridden above, so tzOffset applies
865
- return -tzOffset * 60000; // shift so the displayed time reflects spoofed tz
866
- }
867
- Date.prototype.toString = function () {
868
- try {
869
- var shifted = new Date(this.getTime() + shiftMs(this));
870
- var s = origToString.call(shifted);
871
- // Replace the trailing parenthetical tz abbreviation with one derived from FP.timezone
872
- var tzAbbr = (function () {
873
- try {
874
- var parts = new Intl.DateTimeFormat('en-US', { timeZone: FP.timezone, timeZoneName: 'short' }).formatToParts(new Date());
875
- var tzn = parts.find(function (p) { return p.type === 'timeZoneName'; });
876
- return tzn ? tzn.value : '';
877
- } catch (e) { return ''; }
878
- })();
879
- return s.replace(/GMT[+-]\d{4}(?:\s+\([^)]+\))?/, 'GMT' + (tzOffset <= 0 ? '+' : '-') + String(Math.abs(tzOffset / 60 | 0)).padStart(2, '0') + String(Math.abs(tzOffset % 60)).padStart(2, '0') + (tzAbbr ? ' (' + tzAbbr + ')' : ''));
880
- } catch (e) { return origToString.call(this); }
881
- };
882
- Date.prototype.toTimeString = function () {
883
- try {
884
- var shifted = new Date(this.getTime() + shiftMs(this));
885
- return origToTimeString.call(shifted);
886
- } catch (e) { return origToTimeString.call(this); }
887
- };
888
- Date.prototype.toLocaleString = function () {
889
- try {
890
- var args = Array.prototype.slice.call(arguments);
891
- if (!args[0]) args[0] = FP.locale;
892
- if (!args[1]) args[1] = { timeZone: FP.timezone };
893
- else if (!args[1].timeZone) args[1].timeZone = FP.timezone;
894
- return origToLocaleString.apply(this, args);
895
- } catch (e) { return origToLocaleString.apply(this, arguments); }
896
- };
897
- Date.prototype.toLocaleTimeString = function () {
898
- try {
899
- var args = Array.prototype.slice.call(arguments);
900
- if (!args[0]) args[0] = FP.locale;
901
- if (!args[1]) args[1] = { timeZone: FP.timezone };
902
- else if (!args[1].timeZone) args[1].timeZone = FP.timezone;
903
- return origToLocaleTimeString.apply(this, args);
904
- } catch (e) { return origToLocaleTimeString.apply(this, arguments); }
905
- };
906
- } catch (e) {}
907
- // Also spoof Intl.DateTimeFormat().resolvedOptions().timeZone
908
- try {
909
- var origDTF = Intl.DateTimeFormat;
910
- var patchedDTF = function () {
911
- var result = new origDTF.apply(this, arguments);
912
- var origResolved = result.resolvedOptions.bind(result);
913
- result.resolvedOptions = function () {
914
- var opts = origResolved();
915
- opts.timeZone = FP.timezone;
916
- return opts;
917
- };
918
- return result;
919
- };
920
- patchedDTF.prototype = origDTF.prototype;
921
- window.Intl.DateTimeFormat = patchedDTF;
922
- } catch (e) {}
923
- } catch (e) {}
924
-
925
- // ── 41. window.screenX / window.screenY (window position on screen) ───
926
- try {
927
- Object.defineProperty(window, 'screenX', { get: function () { return 0; }, configurable: true });
928
- Object.defineProperty(window, 'screenY', { get: function () { return 0; }, configurable: true });
929
- Object.defineProperty(window, 'screenLeft', { get: function () { return 0; }, configurable: true });
930
- Object.defineProperty(window, 'screenTop', { get: function () { return 0; }, configurable: true });
931
- } catch (e) {}
932
-
933
- // ── 42. navigator.keyboard (layout map) ───────────────────────────────
934
- try {
935
- if (navigator.keyboard && navigator.keyboard.getLayoutMap) {
936
- var origGetLayoutMap = navigator.keyboard.getLayoutMap.bind(navigator.keyboard);
937
- navigator.keyboard.getLayoutMap = function () {
938
- return origGetLayoutMap().catch(function () {
939
- // Return a basic US keyboard layout map
940
- var layoutMap = new Map();
941
- var keys = ['KeyA','KeyB','KeyC','KeyD','KeyE','KeyF','KeyG','KeyH','KeyI','KeyJ','KeyK','KeyL','KeyM','KeyN','KeyO','KeyP','KeyQ','KeyR','KeyS','KeyT','KeyU','KeyV','KeyW','KeyX','KeyY','KeyZ'];
942
- var values = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
943
- for (var i = 0; i < keys.length; i++) layoutMap.set(keys[i], values[i]);
944
- return layoutMap;
945
- });
946
- };
947
- }
948
- } catch (e) {}
949
-
950
- // ── 43. navigator.scheduling ───────────────────────────────────────────
951
- try {
952
- if (!navigator.scheduling) {
953
- Object.defineProperty(navigator, 'scheduling', {
954
- get: function () {
955
- return { isInputPending: function () { return false; } };
956
- },
957
- configurable: true,
958
- });
959
- }
960
- } catch (e) {}
961
-
962
- // ── 44. navigator.globalPrivacyControl ────────────────────────────────
963
- try {
964
- Object.defineProperty(navigator, 'globalPrivacyControl', {
965
- get: function () { return false; },
966
- configurable: true,
967
- });
968
- } catch (e) {}
969
-
970
- // ── 45. CSS media queries (prefers-color-scheme, prefers-reduced-motion) ─
971
- try {
972
- var origMatchMediaOrig = window.matchMedia;
973
- var origMM = window.matchMedia;
974
- window.matchMedia = function (query) {
975
- var result = origMM.call(this, query);
976
- // Spoof prefers-color-scheme to 'light'
977
- if (query && query.indexOf('prefers-color-scheme') !== -1) {
978
- return { matches: query.indexOf('dark') === -1, media: query, addListener: function () {}, removeListener: function () {}, addEventListener: function () {}, removeEventListener: function () {}, dispatchEvent: function () { return false; } };
979
- }
980
- // Spoof prefers-reduced-motion to 'no-preference'
981
- if (query && query.indexOf('prefers-reduced-motion') !== -1) {
982
- return { matches: query.indexOf('reduce') === -1 ? false : false, media: query, addListener: function () {}, removeListener: function () {}, addEventListener: function () {}, removeEventListener: function () {}, dispatchEvent: function () { return false; } };
983
- }
984
- // Spoof prefers-contrast
985
- if (query && query.indexOf('prefers-contrast') !== -1) {
986
- return { matches: false, media: query, addListener: function () {}, removeListener: function () {}, addEventListener: function () {}, removeEventListener: function () {}, dispatchEvent: function () { return false; } };
987
- }
988
- return result;
989
- };
990
- } catch (e) {}
991
-
992
- // ── 46. navigator.storage estimate ─────────────────────────────────────
993
- try {
994
- if (navigator.storage && navigator.storage.estimate) {
995
- var origEstimate = navigator.storage.estimate.bind(navigator.storage);
996
- navigator.storage.estimate = function () {
997
- return origEstimate().catch(function () {
998
- return { usage: 50000000, quota: 2000000000 };
999
- });
1000
- };
1001
- }
1002
- } catch (e) {}
1003
-
1004
- // ── 47. navigator.credentials (PasswordCredential) ─────────────────────
1005
- try {
1006
- if (!navigator.credentials) {
1007
- Object.defineProperty(navigator, 'credentials', {
1008
- get: function () {
1009
- return { get: function () { return Promise.resolve(null); }, store: function () { return Promise.resolve(null); }, create: function () { return Promise.resolve(null); }, preventSilentAccess: function () { return Promise.resolve(); } };
1010
- },
1011
- configurable: true,
1012
- });
1013
- }
1014
- } catch (e) {}
1015
-
1016
- // ── 48. Error.stack trace sanitization ─────────────────────────────────
1017
- // Some detection scripts check if Error.stack contains Playwright/puppeteer references.
1018
- // On Firefox, Error.prototype.stack is a lazy accessor on the instance, not a getter
1019
- // on Error.prototype, so patching the prototype's descriptor no-ops. Instead we wrap
1020
- // Error's stack access by defining a getter on each new Error via the constructor, and
1021
- // also patch Error.prepareStackTrace where present (V8-style engines).
1022
-
1023
- try {
1024
- var sanitizeStack = function (stack) {
1025
- if (typeof stack === 'string') {
1026
- return stack.replace(/playwright|puppeteer|automation|__pw_|__playwright/gi, '');
1027
- }
1028
- if (stack && Array.isArray(stack)) {
1029
- return stack.map(function (frame) {
1030
- if (frame && typeof frame === 'object') {
1031
- try {
1032
- if (typeof frame.fileName === 'string') {
1033
- frame.fileName = frame.fileName.replace(/playwright|puppeteer|__pw_|__playwright/gi, '');
1034
- }
1035
- if (typeof frame.toString === 'function') {
1036
- var s = frame.toString();
1037
- if (/playwright|puppeteer|__pw_|__playwright/i.test(s)) {
1038
- // best-effort: rewrite the stringified form
1039
- frame.toString = function () { return s.replace(/playwright|puppeteer|__pw_|__playwright/gi, ''); };
1040
- }
1041
- }
1042
- } catch (e) {}
1043
- }
1044
- return frame;
1045
- });
1046
- }
1047
- return stack;
1048
- };
1049
-
1050
- // V8-style: hook prepareStackTrace (returns structured frames)
1051
- if (typeof Error.prepareStackTrace === 'function' || Error.prepareStackTrace === undefined) {
1052
- var origPrepare = Error.prepareStackTrace;
1053
- Error.prepareStackTrace = function (err, stack) {
1054
- var result = origPrepare ? origPrepare.call(this, err, stack) : stack;
1055
- return sanitizeStack(result);
1056
- };
1057
- }
1058
-
1059
- // Firefox-style: define a stack getter on the Error prototype that intercepts the
1060
- // lazy lookup. We redefine on Error.prototype with a getter that calls the original
1061
- // underlying value (read once, then sanitize). This works because Firefox falls back
1062
- // to the prototype getter when the own property hasn't been materialized yet.
1063
- var stackDesc = Object.getOwnPropertyDescriptor(Error.prototype, 'stack');
1064
- if (!stackDesc || stackDesc.get) {
1065
- var origStackGet = stackDesc ? stackDesc.get : null;
1066
- Object.defineProperty(Error.prototype, 'stack', {
1067
- get: function () {
1068
- var raw;
1069
- if (origStackGet) {
1070
- raw = origStackGet.call(this);
1071
- } else {
1072
- try { raw = this.__stack_cache__ || (this.__stack_cache__ = sanitizeStack(new Error().stack)); } catch (e) { raw = ''; }
1073
- }
1074
- return sanitizeStack(raw);
1075
- },
1076
- set: function (v) { this.__stack_cache__ = v; },
1077
- configurable: true,
1078
- });
1079
- }
1080
- } catch (e) {}
1081
-
1082
- // ── 49. navigator.appVersion aligned with UA ──────────────────────────
1083
- try {
1084
- var appVer = FP.userAgent.replace(/^Mozilla\\//, '');
1085
- Object.defineProperty(navigator, 'appVersion', {
1086
- get: function () { return appVer; },
1087
- configurable: true,
1088
- });
1089
- Object.defineProperty(navigator, 'appName', {
1090
- get: function () { return 'Netscape'; },
1091
- configurable: true,
1092
- });
1093
- } catch (e) {}
1094
-
1095
- // ── 50. document.characterSet ─────────────────────────────────────────
1096
- try {
1097
- Object.defineProperty(document, 'characterSet', {
1098
- get: function () { return 'UTF-8'; },
1099
- configurable: true,
1100
- });
1101
- Object.defineProperty(document, 'charset', {
1102
- get: function () { return 'UTF-8'; },
1103
- configurable: true,
1104
- });
1105
- } catch (e) {}
1106
-
1107
- // ── 51. Font measurement spoofing ──────────────────────────────────────
1108
- // Detection scripts measure text width with fallback fonts to detect installed fonts.
1109
- // We add slight noise to measureText/offsetWidth to break this technique.
1110
- try {
1111
- var origMeasureText = CanvasRenderingContext2D.prototype.measureText;
1112
- CanvasRenderingContext2D.prototype.measureText = function (text) {
1113
- var result = origMeasureText.call(this, text);
1114
- // Add tiny noise to width (±0.3px) — enough to break font detection, invisible to users
1115
- try {
1116
- var noise = (FP.canvasNoiseSeed % 7 - 3) * 0.1;
1117
- var origWidth = result.width;
1118
- Object.defineProperty(result, 'width', { get: function () { return origWidth + noise; }, configurable: true });
1119
- } catch (e) {}
1120
- return result;
1121
- };
1122
- // Also noise HTMLElement.offsetWidth/offsetHeight slightly for font detection
1123
- var origOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
1124
- if (origOffsetWidth && origOffsetWidth.get) {
1125
- var origOWGet = origOffsetWidth.get;
1126
- Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
1127
- get: function () {
1128
- var w = origOWGet.call(this);
1129
- // Only noise small elements (font detection uses small test spans)
1130
- if (w > 0 && w < 50) return Math.round(w + (FP.canvasNoiseSeed % 3 - 1) * 0.2);
1131
- return w;
1132
- },
1133
- configurable: true,
1134
- });
1135
- }
1136
- } catch (e) {}
1137
-
1138
- // ── 52. AudioContext full pipeline spoofing ────────────────────────────
1139
- try {
1140
- // Patch AnalyserNode.getFloatFrequencyData
1141
- if (window.AnalyserNode && AnalyserNode.prototype.getFloatFrequencyData) {
1142
- var origGetFloatFreq = AnalyserNode.prototype.getFloatFrequencyData;
1143
- AnalyserNode.prototype.getFloatFrequencyData = function (array) {
1144
- origGetFloatFreq.call(this, array);
1145
- // Add tiny noise to frequency data
1146
- for (var i = 0; i < array.length; i++) {
1147
- array[i] = array[i] + (Math.sin(i + FP.audioNoiseSeed * 1000) * 0.0001);
1148
- }
1149
- };
1150
- }
1151
- // Patch AnalyserNode.getByteFrequencyData
1152
- if (window.AnalyserNode && AnalyserNode.prototype.getByteFrequencyData) {
1153
- var origGetByteFreq = AnalyserNode.prototype.getByteFrequencyData;
1154
- AnalyserNode.prototype.getByteFrequencyData = function (array) {
1155
- origGetByteFreq.call(this, array);
1156
- for (var i = 0; i < array.length; i++) {
1157
- if (array[i] > 0) array[i] = Math.max(0, Math.min(255, array[i] + (FP.canvasNoiseSeed % 3 - 1)));
1158
- }
1159
- };
1160
- }
1161
- // Patch OscillatorNode frequency (deterministic per account)
1162
- if (window.OscillatorNode && OscillatorNode.prototype.frequency) {
1163
- var origFreqDesc = Object.getOwnPropertyDescriptor(OscillatorNode.prototype, 'frequency');
1164
- if (origFreqDesc && origFreqDesc.get) {
1165
- var origFreqGet = origFreqDesc.get;
1166
- try {
1167
- Object.defineProperty(OscillatorNode.prototype, 'frequency', {
1168
- get: function () {
1169
- var f = origFreqGet.call(this);
1170
- // Wrap the setter so a probe that reassigns frequency still
1171
- // lands on a value derived from the per-account seed.
1172
- var patched = parseFloat(f.value) + ((FP.audioNoiseSeed * 1000) % 0.001);
1173
- try { f.value = patched; } catch (e) {}
1174
- return f;
1175
- },
1176
- set: function (v) {
1177
- var origSet = (origFreqDesc && origFreqDesc.set) ? origFreqDesc.set : null;
1178
- if (origSet) origSet.call(this, v);
1179
- },
1180
- configurable: true,
1181
- });
1182
- } catch (e) {}
1183
- }
1184
- }
1185
- } catch (e) {}
1186
-
1187
- // ── 53. WebGL additional parameter spoofing ───────────────────────────
1188
- try {
1189
- var spoofWebGLParams = function (proto) {
1190
- var origGetParam = proto.getParameter;
1191
- proto.getParameter = function (parameter) {
1192
- // UNMASKED_VENDOR_WEBGL = 37445, UNMASKED_RENDERER_WEBGL = 37446
1193
- if (parameter === 37445) return FP.gpu.vendor;
1194
- if (parameter === 37446) return FP.gpu.renderer;
1195
- // MAX_TEXTURE_SIZE — vary slightly per account (4096-16384)
1196
- if (parameter === 3379) return 4096 + (FP.canvasNoiseSeed % 4) * 2048;
1197
- // MAX_VIEWPORT_DIMS — vary
1198
- if (parameter === 3386) return new Int32Array([4096 + (FP.canvasNoiseSeed % 4) * 2048, 4096 + (FP.canvasNoiseSeed % 4) * 2048]);
1199
- // MAX_VERTEX_ATTRIBS
1200
- if (parameter === 34921) return 16;
1201
- // MAX_VARYING_VECTORS
1202
- if (parameter === 36348) return 30;
1203
- // MAX_VERTEX_UNIFORM_VECTORS
1204
- if (parameter === 36347) return 4095;
1205
- // MAX_FRAGMENT_UNIFORM_VECTORS
1206
- if (parameter === 36349) return 1024;
1207
- // ALIASED_LINE_WIDTH_RANGE
1208
- if (parameter === 28460) return new Float32Array([1, 1 + (FP.canvasNoiseSeed % 10) * 0.1]);
1209
- // ALIASED_POINT_SIZE_RANGE
1210
- if (parameter === 33902) return new Float32Array([1, 1024]);
1211
- return origGetParam.call(this, parameter);
1212
- };
1213
- };
1214
- if (window.WebGLRenderingContext) spoofWebGLParams(WebGLRenderingContext.prototype);
1215
- if (window.WebGL2RenderingContext) spoofWebGLParams(WebGL2RenderingContext.prototype);
1216
- } catch (e) {}
1217
-
1218
- // ── 54. Playwright artifact cleanup ───────────────────────────────────
1219
- try {
1220
- // Remove Playwright/puppeteer injected properties
1221
- var playwrightProps = ['__playwright__', '__pw_', '__pwInitScripts', '__playwright__binding', '__playwright__driver'];
1222
- playwrightProps.forEach(function (prop) {
1223
- try {
1224
- if (window[prop] !== undefined) {
1225
- try { delete window[prop]; } catch (e) {
1226
- try { Object.defineProperty(window, prop, { value: undefined, configurable: true }); } catch (e2) {}
1227
- }
1228
- }
1229
- } catch (e) {}
1230
- });
1231
- // Also clean up any automation-related properties on document
1232
- try {
1233
- var docProps = Object.getOwnPropertyNames(document).filter(function (k) { return k.startsWith('__pw') || k.startsWith('__playwright'); });
1234
- docProps.forEach(function (p) { try { delete document[p]; } catch (e) {} });
1235
- } catch (e) {}
1236
- // Override Object.getOwnPropertyDescriptor to hide Playwright bindings
1237
- var origGetOwnPropDesc = Object.getOwnPropertyDescriptor;
1238
- Object.getOwnPropertyDescriptor = function (obj, prop) {
1239
- if (typeof prop === 'string' && (prop.startsWith('__pw') || prop.startsWith('__playwright'))) {
1240
- return undefined;
1241
- }
1242
- return origGetOwnPropDesc.apply(this, arguments);
1243
- };
1244
- } catch (e) {}
1245
-
1246
- })();
1247
- `;
1248
- return script;
1249
- }
1250
-
1
+ 'use strict';
2
+
3
+ /**
4
+ * Comprehensive stealth init script builder.
5
+ *
6
+ * Returns a string of JavaScript that is injected via
7
+ * `context.addInitScript(scriptStr)` — runs on every page and iframe
8
+ * before any page script executes.
9
+ *
10
+ * All spoofing is parameterized by the per-account fingerprint profile
11
+ * so each account has a unique, internally-consistent fingerprint.
12
+ */
13
+
14
+ /**
15
+ * Build the init script string for a given fingerprint profile.
16
+ * @param {object} fp - Fingerprint profile from fingerprint.js
17
+ * @returns {string} JavaScript source to inject
18
+ */
19
+ function buildStealthScript(fp) {
20
+ // We serialize the fingerprint values into the script so they're
21
+ // available inside the browser context without closures.
22
+ const script = `
23
+ (function () {
24
+ 'use strict';
25
+
26
+ var FP = ${JSON.stringify(fp)};
27
+
28
+ // ── 1. Remove navigator.webdriver ──────────────────────────────────────
29
+ try {
30
+ Object.defineProperty(navigator, 'webdriver', { get: () => false, configurable: true });
31
+ } catch (e) {}
32
+
33
+ // ── 2. (removed) browser runtime stub ───────────────────────────────────
34
+ // The agent only ever launches Firefox, where non-Firefox runtime objects
35
+ // are undefined. Any previous stub was dead code and is kept out to avoid
36
+ // confusion.
37
+
38
+ // ── 3. navigator.plugins + mimeTypes (Chrome-style) ───────────────────
39
+ if (typeof navigator.plugins !== 'undefined') {
40
+ var fakePlugins = [
41
+ { name: 'PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
42
+ { name: 'Chrome PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
43
+ { name: 'Chromium PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
44
+ { name: 'Microsoft Edge PDF Viewer', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
45
+ { name: 'WebKit built-in PDF', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
46
+ ];
47
+ var fakeMimeTypes = [
48
+ { type: 'application/pdf', suffixes: 'pdf', description: 'Portable Document Format' },
49
+ { type: 'application/x-pdf', suffixes: 'pdf', description: 'Portable Document Format' },
50
+ { type: 'application/x-nacl', suffixes: '', description: 'Native Client Executable' },
51
+ ];
52
+ try {
53
+ Object.defineProperty(navigator, 'plugins', {
54
+ get: function () {
55
+ var arr = fakePlugins.map(function (p) {
56
+ return Object.assign({}, p, { length: fakeMimeTypes.length });
57
+ });
58
+ arr.length = fakePlugins.length;
59
+ arr.item = function (i) { return arr[i] || null; };
60
+ arr.namedItem = function (n) { return arr.find(function (p) { return p.name === n; }) || null; };
61
+ arr.refresh = function () {};
62
+ return arr;
63
+ },
64
+ configurable: true,
65
+ });
66
+ } catch (e) {}
67
+ try {
68
+ Object.defineProperty(navigator, 'mimeTypes', {
69
+ get: function () {
70
+ var arr = fakeMimeTypes.map(function (m) {
71
+ return Object.assign({}, m, { enabledPlugin: fakePlugins[0] });
72
+ });
73
+ arr.length = fakeMimeTypes.length;
74
+ arr.item = function (i) { return arr[i] || null; };
75
+ arr.namedItem = function (n) { return arr.find(function (m) { return m.type === n; }) || null; };
76
+ return arr;
77
+ },
78
+ configurable: true,
79
+ });
80
+ } catch (e) {}
81
+ } // end if not Firefox
82
+
83
+ // ── 4. navigator.languages (from fingerprint) ──────────────────────────
84
+ try {
85
+ Object.defineProperty(navigator, 'languages', {
86
+ get: function () { return FP.languages.slice(); },
87
+ configurable: true,
88
+ });
89
+ } catch (e) {}
90
+
91
+ // ── 5. navigator.platform ──────────────────────────────────────────────
92
+ try {
93
+ Object.defineProperty(navigator, 'platform', {
94
+ get: function () { return FP.platform; },
95
+ configurable: true,
96
+ });
97
+ } catch (e) {}
98
+
99
+ // ── 6. navigator.hardwareConcurrency ───────────────────────────────────
100
+ try {
101
+ Object.defineProperty(navigator, 'hardwareConcurrency', {
102
+ get: function () { return FP.hardwareConcurrency; },
103
+ configurable: true,
104
+ });
105
+ } catch (e) {}
106
+
107
+ // ── 7. navigator.deviceMemory ──────────────────────────────────────────
108
+ try {
109
+ Object.defineProperty(navigator, 'deviceMemory', {
110
+ get: function () { return FP.deviceMemory; },
111
+ configurable: true,
112
+ });
113
+ } catch (e) {}
114
+
115
+ // ── 8. navigator.userAgentData (Sec-CH-UA client hints) ────────────────
116
+ try {
117
+ if (navigator.userAgentData) {
118
+ var origGetHighEntropyValues = navigator.userAgentData.getHighEntropyValues.bind(navigator.userAgentData);
119
+ navigator.userAgentData.getHighEntropyValues = function (hints) {
120
+ return origGetHighEntropyValues(hints).then(function (orig) {
121
+ orig.platform = FP.userAgentDataPlatform;
122
+ orig.platformVersion = '10.0.0';
123
+ orig.architecture = 'x86';
124
+ orig.bitness = '64';
125
+ orig.model = '';
126
+ orig.uaFullVersion = (navigator.userAgent.match(/Chrome\\/([\\d.]+)/) || [])[1] || '149.0.0.0';
127
+ return orig;
128
+ });
129
+ };
130
+ }
131
+ } catch (e) {}
132
+
133
+ // ── 9. Screen properties ───────────────────────────────────────────────
134
+ try {
135
+ Object.defineProperty(screen, 'width', { get: function () { return FP.screen.width; }, configurable: true });
136
+ Object.defineProperty(screen, 'height', { get: function () { return FP.screen.height; }, configurable: true });
137
+ Object.defineProperty(screen, 'availWidth', { get: function () { return FP.screen.width; }, configurable: true });
138
+ Object.defineProperty(screen, 'availHeight', { get: function () { return FP.screen.height - 40; }, configurable: true });
139
+ Object.defineProperty(screen, 'colorDepth', { get: function () { return 24; }, configurable: true });
140
+ Object.defineProperty(screen, 'pixelDepth', { get: function () { return 24; }, configurable: true });
141
+ } catch (e) {}
142
+
143
+ // ── 10. Permissions API (comprehensive) ────────────────────────────────
144
+ try {
145
+ var origQuery = navigator.permissions ? navigator.permissions.query.bind(navigator.permissions) : null;
146
+ if (origQuery) {
147
+ var permStates = {
148
+ 'notifications': (typeof Notification !== 'undefined') ? Notification.permission : 'default',
149
+ 'geolocation': 'prompt',
150
+ 'camera': 'prompt',
151
+ 'microphone': 'prompt',
152
+ 'clipboard-read': 'prompt',
153
+ 'clipboard-write': 'granted',
154
+ 'persistent-storage': 'prompt',
155
+ };
156
+ navigator.permissions.query = function (parameters) {
157
+ var name = parameters && parameters.name;
158
+ if (permStates.hasOwnProperty(name)) {
159
+ return Promise.resolve({ state: permStates[name], onchange: null });
160
+ }
161
+ return origQuery(parameters);
162
+ };
163
+ }
164
+ } catch (e) {}
165
+
166
+ // ── 11. WebGL vendor/renderer spoofing (per-account) ───────────────────
167
+ try {
168
+ var spoofWebGL = function (proto) {
169
+ var origGetParameter = proto.getParameter;
170
+ proto.getParameter = function (parameter) {
171
+ // UNMASKED_VENDOR_WEBGL = 37445, UNMASKED_RENDERER_WEBGL = 37446
172
+ if (parameter === 37445) return FP.gpu.vendor;
173
+ if (parameter === 37446) return FP.gpu.renderer;
174
+ return origGetParameter.call(this, parameter);
175
+ };
176
+ // Also spoof MAX_TEXTURE_SIZE and other params slightly for diversity
177
+ var origGetExtension = proto.getExtension;
178
+ proto.getExtension = function (name) {
179
+ return origGetExtension.call(this, name);
180
+ };
181
+ };
182
+ if (window.WebGLRenderingContext) spoofWebGL(WebGLRenderingContext.prototype);
183
+ if (window.WebGL2RenderingContext) spoofWebGL(WebGL2RenderingContext.prototype);
184
+ } catch (e) {}
185
+
186
+ // ── 12. Canvas fingerprint noise ───────────────────────────────────────
187
+ // Per-pixel noise driven by a seeded PRNG so the pattern is stable per
188
+ // account but varies across pixels (both up and down). The old fixed-stride
189
+ // "+1 at (i+seed)%7===0" was detectable because it only ever brightened.
190
+ try {
191
+ var seed = (FP.canvasNoiseSeed >>> 0) || 1;
192
+ function cnvRand() {
193
+ seed |= 0; seed = (seed + 0x6D2B79F5) | 0;
194
+ var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
195
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
196
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
197
+ }
198
+ function applyCanvasNoise(data) {
199
+ for (var i = 0; i < data.length; i += 4) {
200
+ // ±2 per channel, pseudo-random, stable per-account
201
+ data[i] = (data[i] + ((cnvRand() * 5) | 0) - 2) & 0xFF; // R
202
+ data[i + 1] = (data[i + 1] + ((cnvRand() * 5) | 0) - 2) & 0xFF; // G
203
+ data[i + 2] = (data[i + 2] + ((cnvRand() * 5) | 0) - 2) & 0xFF; // B
204
+ // Alpha untouched
205
+ }
206
+ }
207
+ var origToDataURL = HTMLCanvasElement.prototype.toDataURL;
208
+ HTMLCanvasElement.prototype.toDataURL = function () {
209
+ var ctx = this.getContext('2d');
210
+ if (ctx && this.width > 0 && this.height > 0) {
211
+ try {
212
+ var imageData = ctx.getImageData(0, 0, Math.min(this.width, 16), Math.min(this.height, 16));
213
+ applyCanvasNoise(imageData.data);
214
+ ctx.putImageData(imageData, 0, 0);
215
+ } catch (e) {}
216
+ }
217
+ return origToDataURL.apply(this, arguments);
218
+ };
219
+
220
+ var origGetImageData = CanvasRenderingContext2D.prototype.getImageData;
221
+ CanvasRenderingContext2D.prototype.getImageData = function () {
222
+ var imageData = origGetImageData.apply(this, arguments);
223
+ try { applyCanvasNoise(imageData.data); } catch (e) {}
224
+ return imageData;
225
+ };
226
+ } catch (e) {}
227
+
228
+ // ── 13. AudioContext fingerprint noise ─────────────────────────────────
229
+ // Larger, varied offsets per sample (driven by a per-account seeded PRNG)
230
+ // so the noise is stable per account but not a detectable fixed tiny shift.
231
+ try {
232
+ var audioSeed = (FP.canvasNoiseSeed >>> 0) || 1;
233
+ function audioRand() {
234
+ audioSeed |= 0; audioSeed = (audioSeed + 0x6D2B79F5) | 0;
235
+ var t = Math.imul(audioSeed ^ (audioSeed >>> 15), 1 | audioSeed);
236
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
237
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
238
+ }
239
+ var origCreateAnalyser = (window.OfflineAudioContext || window.webkitOfflineAudioContext);
240
+ if (origCreateAnalyser) {
241
+ var OrigOAC = window.OfflineAudioContext || window.webkitOfflineAudioContext;
242
+ var origGetChannelData = AudioBuffer.prototype.getChannelData;
243
+ AudioBuffer.prototype.getChannelData = function () {
244
+ var data = origGetChannelData.apply(this, arguments);
245
+ try {
246
+ for (var i = 0; i < data.length; i++) {
247
+ // Vary every Nth sample by a larger ±1e-4 offset, pseudo-random
248
+ if (i % 50 === 0) data[i] = (data[i] + (audioRand() - 0.5) * 2e-4);
249
+ }
250
+ } catch (e) {}
251
+ return data;
252
+ };
253
+ }
254
+ } catch (e) {}
255
+
256
+ // ── 14. WebRTC IP leak prevention (CRITICAL for proxy isolation) ──────
257
+ // Firefox uses both RTCPeerConnection and mozRTCPeerConnection.
258
+ // We must block ALL WebRTC to prevent the real IP from leaking.
259
+ try {
260
+ // Completely disable WebRTC by making RTCPeerConnection a no-op
261
+ if (window.RTCPeerConnection) {
262
+ var OrigRTC = window.RTCPeerConnection;
263
+ window.RTCPeerConnection = function () {
264
+ var args = arguments;
265
+ if (args[0] && args[0].iceServers) {
266
+ // Strip all ICE servers — no STUN, no TURN
267
+ args[0].iceServers = [];
268
+ }
269
+ var pc = new OrigRTC(args[0], args[1]);
270
+ // Block all ICE candidates — never emit local IP
271
+ var origAddIceCandidate = pc.addIceCandidate.bind(pc);
272
+ pc.addIceCandidate = function (candidate) {
273
+ if (candidate && candidate.candidate) {
274
+ // Drop ALL candidates (host, srflx, relay) to prevent IP leak
275
+ return Promise.resolve();
276
+ }
277
+ return origAddIceCandidate(candidate);
278
+ };
279
+ // Scrub all local IPs from getStats()
280
+ var origGetStats = pc.getStats ? pc.getStats.bind(pc) : null;
281
+ if (origGetStats) {
282
+ pc.getStats = function () {
283
+ return origGetStats.apply(this, arguments).then(function (report) {
284
+ try {
285
+ report.forEach(function (stat) {
286
+ if (stat && typeof stat === 'object') {
287
+ if (typeof stat.ip === 'string') stat.ip = '0.0.0.0';
288
+ if (typeof stat.address === 'string') stat.address = '0.0.0.0';
289
+ if (typeof stat.relatedAddress === 'string') stat.relatedAddress = '0.0.0.0';
290
+ if (typeof stat.localAddress === 'string') stat.localAddress = '0.0.0.0';
291
+ if (typeof stat.remoteAddress === 'string') stat.remoteAddress = '0.0.0.0';
292
+ }
293
+ });
294
+ } catch (e) {}
295
+ return report;
296
+ });
297
+ };
298
+ }
299
+ // Strip host candidates from localDescription SDP
300
+ try {
301
+ var origLocalDesc = Object.getOwnPropertyDescriptor(pc, 'localDescription') ||
302
+ Object.getOwnPropertyDescriptor(Object.getPrototypeOf(pc), 'localDescription');
303
+ if (origLocalDesc && origLocalDesc.get) {
304
+ var origLDGet = origLocalDesc.get;
305
+ Object.defineProperty(pc, 'localDescription', {
306
+ get: function () {
307
+ var desc = origLDGet.call(this);
308
+ if (desc && typeof desc.sdp === 'string') {
309
+ desc = { type: desc.type, sdp: desc.sdp.replace(/a=candidate:[^\r\n]*\s(host|srflx)[^\r\n]*/gi, 'a=candidate:removed') };
310
+ }
311
+ return desc;
312
+ },
313
+ configurable: true,
314
+ });
315
+ }
316
+ } catch (e) {}
317
+ return pc;
318
+ };
319
+ window.RTCPeerConnection.prototype = OrigRTC.prototype;
320
+ }
321
+ // Also handle Firefox-specific mozRTCPeerConnection
322
+ if (window.mozRTCPeerConnection) {
323
+ var OrigMozRTC = window.mozRTCPeerConnection;
324
+ window.mozRTCPeerConnection = function () {
325
+ var args = arguments;
326
+ if (args[0] && args[0].iceServers) {
327
+ args[0].iceServers = [];
328
+ }
329
+ return new OrigMozRTC(args[0], args[1]);
330
+ };
331
+ window.mozRTCPeerConnection.prototype = OrigMozRTC.prototype;
332
+ }
333
+ // Also override webkitRTCPeerConnection if it exists
334
+ if (window.webkitRTCPeerConnection && !window.RTCPeerConnection) {
335
+ window.RTCPeerConnection = window.webkitRTCPeerConnection;
336
+ }
337
+ } catch (e) {}
338
+
339
+ // ── 15. CDP / DevTools detection mitigation ────────────────────────────
340
+ try {
341
+ // Remove window.cdc_ properties (automation driver markers)
342
+ Object.keys(window).forEach(function (k) {
343
+ if (k.startsWith('cdc_') || k.startsWith('$cdc_')) {
344
+ try { delete window[k]; } catch (e) {}
345
+ }
346
+ });
347
+ // Override console.debug to prevent CDP detection via binding
348
+ var origDebug = console.debug;
349
+ console.debug = function () {
350
+ // Check if called with a specific CDP detection marker
351
+ if (arguments.length === 1 && typeof arguments[0] === 'string' && arguments[0].startsWith('cdp')) {
352
+ return; // Swallow CDP probe
353
+ }
354
+ return origDebug.apply(console, arguments);
355
+ };
356
+ } catch (e) {}
357
+
358
+ // ── 16. iframe contentWindow hardening ─────────────────────────────────
359
+ try {
360
+ var origContentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
361
+ if (origContentWindow && origContentWindow.get) {
362
+ var origGet = origContentWindow.get;
363
+ Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', {
364
+ get: function () {
365
+ var w = origGet.call(this);
366
+ if (w) {
367
+ try { Object.defineProperty(w.navigator, 'webdriver', { get: () => false }); } catch (e) {}
368
+ }
369
+ return w;
370
+ },
371
+ configurable: true,
372
+ });
373
+ }
374
+ } catch (e) {}
375
+
376
+ // ── 17. Notification permission consistency ────────────────────────────
377
+ try {
378
+ if (window.Notification) {
379
+ Object.defineProperty(Notification, 'permission', {
380
+ get: function () { return 'default'; },
381
+ configurable: true,
382
+ });
383
+ }
384
+ } catch (e) {}
385
+
386
+ // ── 18. Hairline feature detection fix ─────────────────────────────────
387
+ try {
388
+ // Some bot detection checks for the -webkit-hairline feature
389
+ var origMatchMedia = window.matchMedia;
390
+ window.matchMedia = function (query) {
391
+ var result = origMatchMedia.call(this, query);
392
+ if (query && query.indexOf('hairline') !== -1) {
393
+ return { matches: false, media: query, addListener: function () {}, removeListener: function () {} };
394
+ }
395
+ return result;
396
+ };
397
+ } catch (e) {}
398
+
399
+ // ── 19. navigator.connection (Network Information API) ─────────────────
400
+ try {
401
+ if (navigator.connection) {
402
+ Object.defineProperty(navigator.connection, 'effectiveType', { get: function () { return FP.connection.effectiveType; }, configurable: true });
403
+ Object.defineProperty(navigator.connection, 'downlink', { get: function () { return FP.connection.downlink; }, configurable: true });
404
+ Object.defineProperty(navigator.connection, 'rtt', { get: function () { return FP.connection.rtt; }, configurable: true });
405
+ Object.defineProperty(navigator.connection, 'saveData', { get: function () { return false; }, configurable: true });
406
+ }
407
+ } catch (e) {}
408
+
409
+ // ── 20. navigator.getBattery() spoofing ───────────────────────────────
410
+ try {
411
+ if (navigator.getBattery) {
412
+ navigator.getBattery = function () {
413
+ return Promise.resolve({
414
+ charging: FP.battery.charging,
415
+ chargingTime: FP.battery.charging ? 1280 : Infinity,
416
+ dischargingTime: FP.battery.charging ? Infinity : 12600,
417
+ level: FP.battery.level,
418
+ addEventListener: function () {},
419
+ removeEventListener: function () {},
420
+ });
421
+ };
422
+ }
423
+ } catch (e) {}
424
+
425
+ // ── 21. navigator.mediaDevices.enumerateDevices() spoofing ─────────────
426
+ try {
427
+ if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
428
+ var origEnumerate = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
429
+ navigator.mediaDevices.enumerateDevices = function () {
430
+ return origEnumerate().then(function (realDevices) {
431
+ // If real devices exist, keep them but randomize IDs
432
+ if (realDevices && realDevices.length > 0) return realDevices;
433
+ // Otherwise return fake devices based on fingerprint
434
+ var fake = [];
435
+ var counts = FP.mediaDevices;
436
+ for (var i = 0; i < counts.audioinput; i++) fake.push({ kind: 'audioinput', deviceId: 'default', label: '', groupId: 'group' + i });
437
+ for (var i = 0; i < counts.audiooutput; i++) fake.push({ kind: 'audiooutput', deviceId: 'default', label: '', groupId: 'group' + i });
438
+ for (var i = 0; i < counts.videoinput; i++) fake.push({ kind: 'videoinput', deviceId: 'default', label: '', groupId: 'group' + i });
439
+ return fake;
440
+ });
441
+ };
442
+ }
443
+ } catch (e) {}
444
+
445
+ // ── 22. Font fingerprinting defense ─────────────────────────────────────
446
+ try {
447
+ if (document.fonts && document.fonts.check) {
448
+ var origFontCheck = document.fonts.check.bind(document.fonts);
449
+ document.fonts.check = function (font, text) {
450
+ // Return true for common fonts, false for uncommon probe fonts
451
+ var commonFonts = ['Arial', 'Helvetica', 'Times New Roman', 'Courier New', 'Georgia', 'Verdana', 'Tahoma', 'Trebuchet MS', 'Segoe UI', 'Calibri'];
452
+ for (var i = 0; i < commonFonts.length; i++) {
453
+ if (font && font.indexOf(commonFonts[i]) !== -1) return true;
454
+ }
455
+ return origFontCheck(font, text);
456
+ };
457
+ }
458
+ } catch (e) {}
459
+
460
+ // ── 23. Intl properties aligned with locale/timezone ───────────────────
461
+ try {
462
+ var origDateTimeFormat = window.Intl.DateTimeFormat;
463
+ window.Intl.DateTimeFormat = function () {
464
+ var args = Array.prototype.slice.call(arguments);
465
+ if (!args[0]) args[0] = FP.locale;
466
+ if (!args[1] || !args[1].timeZone) {
467
+ args[1] = args[1] || {};
468
+ args[1].timeZone = FP.timezone;
469
+ }
470
+ return new origDateTimeFormat(args[0], args[1]);
471
+ };
472
+ window.Intl.DateTimeFormat.prototype = origDateTimeFormat.prototype;
473
+ } catch (e) {}
474
+
475
+ // ── 24. window.outerWidth/outerHeight aligned with screen ───────────────
476
+ try {
477
+ Object.defineProperty(window, 'outerWidth', { get: function () { return FP.screen.width; }, configurable: true });
478
+ Object.defineProperty(window, 'outerHeight', { get: function () { return FP.screen.height; }, configurable: true });
479
+ } catch (e) {}
480
+
481
+ // ── 25. navigator.maxTouchPoints (0 for desktop) ────────────────────────
482
+ try {
483
+ Object.defineProperty(navigator, 'maxTouchPoints', {
484
+ get: function () { return FP.isMobile ? 5 : 0; },
485
+ configurable: true,
486
+ });
487
+ } catch (e) {}
488
+
489
+ // ── 26. navigator.oscpu (Firefox-specific) ──────────────────────────────
490
+ try {
491
+ Object.defineProperty(navigator, 'oscpu', {
492
+ get: function () { return FP.oscpu; },
493
+ configurable: true,
494
+ });
495
+ } catch (e) {}
496
+
497
+ // ── 27. navigator.buildID (Firefox-specific) ────────────────────────────
498
+ try {
499
+ Object.defineProperty(navigator, 'buildID', {
500
+ get: function () { return FP.buildID; },
501
+ configurable: true,
502
+ });
503
+ } catch (e) {}
504
+
505
+ // ── 28. screen.availLeft/availTop ───────────────────────────────────────
506
+ try {
507
+ Object.defineProperty(screen, 'availLeft', { get: function () { return 0; }, configurable: true });
508
+ Object.defineProperty(screen, 'availTop', { get: function () { return 0; }, configurable: true });
509
+ } catch (e) {}
510
+
511
+ // ── 29. document.hasStorageAccess() ────────────────────────────────────
512
+ try {
513
+ if (document.hasStorageAccess) {
514
+ var origHasStorageAccess = document.hasStorageAccess.bind(document);
515
+ document.hasStorageAccess = function () {
516
+ return Promise.resolve(true);
517
+ };
518
+ }
519
+ } catch (e) {}
520
+
521
+ // ── 30. navigator.serviceWorker consistency ────────────────────────────
522
+ try {
523
+ // Ensure serviceWorker exists (real browsers have it)
524
+ if (!navigator.serviceWorker) {
525
+ Object.defineProperty(navigator, 'serviceWorker', {
526
+ get: function () { return { register: function () { return Promise.reject(); }, getRegistrations: function () { return Promise.resolve([]); } }; },
527
+ configurable: true,
528
+ });
529
+ }
530
+ } catch (e) {}
531
+
532
+ // ── 31. window.history.length padding ──────────────────────────────────
533
+ try {
534
+ // Don't override history.length (read-only), but push some states
535
+ // to make it look like the user has been browsing
536
+ if (window.history.length < 3) {
537
+ try { window.history.pushState({}, '', window.location.href); } catch (e) {}
538
+ try { window.history.pushState({}, '', window.location.href); } catch (e) {}
539
+ }
540
+ } catch (e) {}
541
+
542
+ // ── 32. Performance.now() timing jitter ────────────────────────────────
543
+ try {
544
+ // Per-account seeded PRNG (mulberry32) so jitter is stable per account but
545
+ // pseudo-random across calls — a sinusoidal jitter (the old impl) is
546
+ // detectable by sampling many calls. Jitter is ±0.02ms.
547
+ var perfSeed = (FP.perfJitter || 1) >>> 0;
548
+ var perfState = perfSeed;
549
+ function perfRand() {
550
+ perfState |= 0; perfState = (perfState + 0x6D2B79F5) | 0;
551
+ var t = Math.imul(perfState ^ (perfState >>> 15), 1 | perfState);
552
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
553
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
554
+ }
555
+ var origNow = Performance.prototype.now;
556
+ Performance.prototype.now = function () {
557
+ var real = origNow.call(this);
558
+ return real + (perfRand() - 0.5) * 0.04;
559
+ };
560
+ } catch (e) {}
561
+
562
+ // ── 33. navigator.doNotTrack consistency ───────────────────────────────
563
+ try {
564
+ Object.defineProperty(navigator, 'doNotTrack', {
565
+ get: function () { return '1'; },
566
+ configurable: true,
567
+ });
568
+ } catch (e) {}
569
+
570
+ // ── 34. window.devicePixelRatio aligned with fingerprint ───────────────
571
+ try {
572
+ Object.defineProperty(window, 'devicePixelRatio', {
573
+ get: function () { return FP.devicePixelRatio || 1; },
574
+ configurable: true,
575
+ });
576
+ } catch (e) {}
577
+
578
+ // ── 35. SpeechSynthesis API consistency ────────────────────────────────
579
+ try {
580
+ if (window.speechSynthesis) {
581
+ var origGetVoices = window.speechSynthesis.getVoices.bind(window.speechSynthesis);
582
+ window.speechSynthesis.getVoices = function () {
583
+ var voices = origGetVoices();
584
+ if (voices && voices.length > 0) return voices;
585
+ // Return a minimal set if none available
586
+ return [
587
+ { name: 'Microsoft David - English (United States)', lang: 'en-US', localService: true, default: true, voiceURI: 'Microsoft David' },
588
+ { name: 'Microsoft Zira - English (United States)', lang: 'en-US', localService: true, default: false, voiceURI: 'Microsoft Zira' },
589
+ ];
590
+ };
591
+ }
592
+ } catch (e) {}
593
+
594
+ // ── 36. navigator.vendor / navigator.product (Chrome-specific) ─────────
595
+ try {
596
+ Object.defineProperty(navigator, 'vendor', {
597
+ get: function () { return 'Google Inc.'; },
598
+ configurable: true,
599
+ });
600
+ Object.defineProperty(navigator, 'product', {
601
+ get: function () { return 'Gecko'; },
602
+ configurable: true,
603
+ });
604
+ Object.defineProperty(navigator, 'productSub', {
605
+ get: function () { return '20030107'; },
606
+ configurable: true,
607
+ });
608
+ } catch (e) {}
609
+
610
+ // ── 36b. window.chrome object (CRITICAL — Chrome detection) ───────────
611
+ // Sites check window.chrome to detect if browser is Chrome.
612
+ // Playwright Chromium has a partial chrome object — fill it completely.
613
+ try {
614
+ if (!window.chrome) {
615
+ window.chrome = {};
616
+ }
617
+ // runtime object — most commonly checked
618
+ if (!window.chrome.runtime) {
619
+ window.chrome.runtime = {
620
+ OnInstalledReason: { CHROME_UPDATE: 'chrome_update', INSTALL: 'install', UPDATE: 'update' },
621
+ OnRestartRequiredReason: { APP_UPDATE: 'app_update', OS_UPDATE: 'os_update', PERIODIC: 'periodic' },
622
+ PlatformArch: { ARM: 'arm', ARM64: 'arm64', MIPS: 'mips', MIPS64: 'mips64', X86_32: 'x86-32', X86_64: 'x86-64' },
623
+ PlatformNaclArch: { ARM: 'arm', MIPS: 'mips', MIPS64: 'mips64', X86_32: 'x86-32', X86_64: 'x86-64' },
624
+ PlatformOs: { ANDROID: 'android', CROS: 'cros', LINUX: 'linux', MAC: 'mac', OPENBSD: 'openbsd', WIN: 'win' },
625
+ RequestUpdateCheckStatus: { NO_UPDATE: 'no_update', THROTTLED: 'throttled', UPDATE_AVAILABLE: 'update_available' },
626
+ connect: function () {},
627
+ sendMessage: function () {},
628
+ };
629
+ }
630
+ // app object
631
+ if (!window.chrome.app) {
632
+ window.chrome.app = {
633
+ isInstalled: false,
634
+ InstallState: { DISABLED: 'disabled', INSTALLED: 'installed', NOT_INSTALLED: 'not_installed' },
635
+ RunningState: { CANNOT_RUN: 'cannot_run', READY_TO_RUN: 'ready_to_run', RUNNING: 'running' },
636
+ getDetails: function () { return null; },
637
+ getIsInstalled: function () { return false; },
638
+ };
639
+ }
640
+ // csi and loadTimes (used by bot detection)
641
+ if (!window.chrome.csi) {
642
+ window.chrome.csi = function () { return { startE: Date.now(), onloadT: Date.now(), pageT: Math.random() * 5000 + 1000, tran: 15 }; };
643
+ }
644
+ if (!window.chrome.loadTimes) {
645
+ window.chrome.loadTimes = function () {
646
+ return {
647
+ commitLoadTime: Date.now() / 1000 - Math.random() * 10,
648
+ connectionInfo: 'h2',
649
+ finishDocumentLoadTime: Date.now() / 1000 - Math.random() * 5,
650
+ finishLoadTime: Date.now() / 1000 - Math.random() * 3,
651
+ firstPaintAfterLoadTime: 0,
652
+ firstPaintTime: Date.now() / 1000 - Math.random() * 8,
653
+ navigationType: 'Other',
654
+ npnNegotiatedProtocol: 'h2',
655
+ requestTime: Date.now() / 1000 - Math.random() * 15,
656
+ startDnsTime: Date.now() / 1000 - Math.random() * 14,
657
+ startLoadTime: Date.now() / 1000 - Math.random() * 12,
658
+ wasAlternateProtocolAvailable: false,
659
+ wasFetchedViaSpdy: true,
660
+ wasNpnNegotiated: true,
661
+ };
662
+ };
663
+ }
664
+ } catch (e) {}
665
+
666
+ // ── 36c. Sec-CH-UA client hints (Chrome-specific anti-detection) ───────
667
+ try {
668
+ if (navigator.userAgentData) {
669
+ // Override brands with Chrome-specific values
670
+ Object.defineProperty(navigator.userAgentData, 'brands', {
671
+ get: function () {
672
+ return [
673
+ { brand: 'Chromium', version: FP.chromeVersion || '125' },
674
+ { brand: 'Google Chrome', version: FP.chromeVersion || '125' },
675
+ { brand: 'Not.A/Brand', version: '99' },
676
+ ];
677
+ },
678
+ configurable: true,
679
+ });
680
+ Object.defineProperty(navigator.userAgentData, 'mobile', {
681
+ get: function () { return FP.isMobile || false; },
682
+ configurable: true,
683
+ });
684
+ Object.defineProperty(navigator.userAgentData, 'platform', {
685
+ get: function () { return FP.userAgentDataPlatform || 'Windows'; },
686
+ configurable: true,
687
+ });
688
+ }
689
+ } catch (e) {}
690
+
691
+ // ── 36d. Remove Firefox-specific properties (not in Chrome) ───────────
692
+ try {
693
+ // Chrome doesn't have navigator.oscpu or navigator.buildID
694
+ if (navigator.oscpu !== undefined) {
695
+ Object.defineProperty(navigator, 'oscpu', {
696
+ get: function () { return undefined; },
697
+ configurable: true,
698
+ });
699
+ }
700
+ if (navigator.buildID !== undefined) {
701
+ Object.defineProperty(navigator, 'buildID', {
702
+ get: function () { return undefined; },
703
+ configurable: true,
704
+ });
705
+ }
706
+ } catch (e) {}
707
+
708
+ // ── 37. Geolocation API — block real location leak ─────────────────────
709
+ try {
710
+ if (navigator.geolocation) {
711
+ var origGetCurrentPosition = navigator.geolocation.getCurrentPosition.bind(navigator.geolocation);
712
+ var origWatchPosition = navigator.geolocation.watchPosition.bind(navigator.geolocation);
713
+ // Return an error so sites can't get real GPS coordinates
714
+ navigator.geolocation.getCurrentPosition = function (success, error) {
715
+ if (error) error({ code: 1, message: 'User denied Geolocation' });
716
+ };
717
+ navigator.geolocation.watchPosition = function (success, error) {
718
+ if (error) error({ code: 1, message: 'User denied Geolocation' });
719
+ return 0;
720
+ };
721
+ }
722
+ } catch (e) {}
723
+
724
+ // ── 38. navigator.connection.effectiveType spoofing (extra) ───────────
725
+ try {
726
+ if (navigator.connection) {
727
+ Object.defineProperty(navigator.connection, 'type', {
728
+ get: function () { return 'wifi'; },
729
+ configurable: true,
730
+ });
731
+ }
732
+ } catch (e) {}
733
+
734
+ // ── 39. (removed — Chrome NEEDS window.chrome, don't delete it) ────────
735
+
736
+ // ── 40. navigator.credentials API — prevent credential leak ───────────
737
+ try {
738
+ if (navigator.credentials) {
739
+ var origGet = navigator.credentials.get.bind(navigator.credentials);
740
+ navigator.credentials.get = function () { return Promise.resolve(null); };
741
+ }
742
+ } catch (e) {}
743
+
744
+ // ── 41. Disable WebRTC leak via mediaDevices (getDisplayMedia) ─────────
745
+ try {
746
+ if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
747
+ var origGetDisplayMedia = navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices);
748
+ navigator.mediaDevices.getDisplayMedia = function () {
749
+ return Promise.reject(new Error('Permission denied'));
750
+ };
751
+ }
752
+ } catch (e) {}
753
+
754
+ // ── 37. navigator.cookieEnabled / navigator.onLine ────────────────────
755
+ try {
756
+ Object.defineProperty(navigator, 'cookieEnabled', {
757
+ get: function () { return true; },
758
+ configurable: true,
759
+ });
760
+ Object.defineProperty(navigator, 'onLine', {
761
+ get: function () { return true; },
762
+ configurable: true,
763
+ });
764
+ } catch (e) {}
765
+
766
+ // ── 38. document.visibilityState / window focus events ───────────────
767
+ // Twitter checks if the tab is active/focused — Playwright tabs can report 'hidden'
768
+ try {
769
+ Object.defineProperty(document, 'visibilityState', {
770
+ get: function () { return 'visible'; },
771
+ configurable: true,
772
+ });
773
+ Object.defineProperty(document, 'hidden', {
774
+ get: function () { return false; },
775
+ configurable: true,
776
+ });
777
+ Object.defineProperty(document, 'webkitVisibilityState', {
778
+ get: function () { return 'visible'; },
779
+ configurable: true,
780
+ });
781
+ Object.defineProperty(document, 'webkitHidden', {
782
+ get: function () { return false; },
783
+ configurable: true,
784
+ });
785
+ // Ensure hasFocus returns true
786
+ document.hasFocus = function () { return true; };
787
+ // Dispatch focus events to simulate active tab
788
+ try { window.dispatchEvent(new Event('focus')); } catch (e) {}
789
+ try { document.dispatchEvent(new Event('visibilitychange')); } catch (e) {}
790
+ } catch (e) {}
791
+
792
+ // ── 39. event.isTrusted enforcement ────────────────────────────────────
793
+ // Twitter checks if click/keyboard events have isTrusted=true.
794
+ // Playwright's mouse.click produces trusted events, but element.click() and
795
+ // dispatchEvent() do not. Rather than blanket-patching HTMLElement.click
796
+ // (which drops focus/activation behavior and breaks form submit), we only
797
+ // intercept .click() and re-dispatch a MouseEvent when the browser would
798
+ // otherwise produce an untrusted event. If the platform already produces a
799
+ // trusted click (Playwright's .click() path), the original is preserved.
800
+ try {
801
+ var origElClick = HTMLElement.prototype.click;
802
+ HTMLElement.prototype.click = function () {
803
+ try {
804
+ // Probe: synthesize a click event and check isTrusted. If the engine
805
+ // already produces trusted clicks for programmatic .click(), bail.
806
+ var probe = new MouseEvent('click', { bubbles: false, cancelable: false });
807
+ if (probe.isTrusted) {
808
+ return origElClick.call(this);
809
+ }
810
+ var rect = this.getBoundingClientRect();
811
+ var x = rect.left + rect.width / 2;
812
+ var y = rect.top + rect.height / 2;
813
+ var evt = new MouseEvent('click', {
814
+ bubbles: true, cancelable: true, view: window,
815
+ clientX: x, clientY: y,
816
+ });
817
+ this.dispatchEvent(evt);
818
+ } catch (e) {
819
+ return origElClick.call(this);
820
+ }
821
+ };
822
+ } catch (e) {}
823
+
824
+ // ── 40. Date.prototype.getTimezoneOffset aligned with timezone ────────
825
+ try {
826
+ // Compute offset from the fingerprint timezone
827
+ var tzOffset = (function () {
828
+ try {
829
+ var formatter = new Intl.DateTimeFormat('en-US', { timeZone: FP.timezone, timeZoneName: 'short' });
830
+ var parts = formatter.formatToParts(new Date());
831
+ var tzName = parts.find(function (p) { return p.type === 'timeZoneName'; });
832
+ if (!tzName) return 0;
833
+ // Approximate offset from common timezone abbreviations
834
+ var offsets = {
835
+ 'EST': 300, 'EDT': 240, 'CST': 360, 'CDT': 300, 'MST': 420, 'MDT': 360,
836
+ 'PST': 480, 'PDT': 420, 'GMT': 0, 'BST': -60, 'CET': -60, 'CEST': -120,
837
+ 'EET': -120, 'EEST': -180, 'MSK': -180, 'AST': 240, 'AKST': 540, 'AKDT': 480,
838
+ 'HST': 600, 'JST': -540, 'KST': -540, 'IST': -330, 'PKT': -300,
839
+ 'WIB': -420, 'ICT': -420, 'SGT': -480, 'HKT': -480, 'AST_AR': -180,
840
+ };
841
+ // Try to get offset by comparing local time with target timezone
842
+ var now = new Date();
843
+ var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
844
+ var target = new Date(utc.toLocaleString('en-US', { timeZone: FP.timezone }));
845
+ var localNow = new Date(utc.toLocaleString('en-US'));
846
+ return Math.round((localNow - target) / 60000);
847
+ } catch (e) { return 0; }
848
+ })();
849
+ Object.defineProperty(Date.prototype, 'getTimezoneOffset', {
850
+ value: function () { return tzOffset; },
851
+ configurable: true,
852
+ });
853
+ // Spoof Date.prototype.toString / toTimeString / toLocaleString so they
854
+ // agree with the spoofed offset and timezone. Without this, a detector
855
+ // can compare new Date().toString() (native tz) against the spoofed
856
+ // getTimezoneOffset() and catch the mismatch.
857
+ try {
858
+ var origToString = Date.prototype.toString;
859
+ var origToTimeString = Date.prototype.toTimeString;
860
+ var origToLocaleString = Date.prototype.toLocaleString;
861
+ var origToLocaleTimeString = Date.prototype.toLocaleTimeString;
862
+ function shiftMs(d) {
863
+ // milliseconds between native offset and spoofed offset
864
+ var native = d.getTimezoneOffset ? 0 : 0; // native already overridden above, so tzOffset applies
865
+ return -tzOffset * 60000; // shift so the displayed time reflects spoofed tz
866
+ }
867
+ Date.prototype.toString = function () {
868
+ try {
869
+ var shifted = new Date(this.getTime() + shiftMs(this));
870
+ var s = origToString.call(shifted);
871
+ // Replace the trailing parenthetical tz abbreviation with one derived from FP.timezone
872
+ var tzAbbr = (function () {
873
+ try {
874
+ var parts = new Intl.DateTimeFormat('en-US', { timeZone: FP.timezone, timeZoneName: 'short' }).formatToParts(new Date());
875
+ var tzn = parts.find(function (p) { return p.type === 'timeZoneName'; });
876
+ return tzn ? tzn.value : '';
877
+ } catch (e) { return ''; }
878
+ })();
879
+ return s.replace(/GMT[+-]\d{4}(?:\s+\([^)]+\))?/, 'GMT' + (tzOffset <= 0 ? '+' : '-') + String(Math.abs(tzOffset / 60 | 0)).padStart(2, '0') + String(Math.abs(tzOffset % 60)).padStart(2, '0') + (tzAbbr ? ' (' + tzAbbr + ')' : ''));
880
+ } catch (e) { return origToString.call(this); }
881
+ };
882
+ Date.prototype.toTimeString = function () {
883
+ try {
884
+ var shifted = new Date(this.getTime() + shiftMs(this));
885
+ return origToTimeString.call(shifted);
886
+ } catch (e) { return origToTimeString.call(this); }
887
+ };
888
+ Date.prototype.toLocaleString = function () {
889
+ try {
890
+ var args = Array.prototype.slice.call(arguments);
891
+ if (!args[0]) args[0] = FP.locale;
892
+ if (!args[1]) args[1] = { timeZone: FP.timezone };
893
+ else if (!args[1].timeZone) args[1].timeZone = FP.timezone;
894
+ return origToLocaleString.apply(this, args);
895
+ } catch (e) { return origToLocaleString.apply(this, arguments); }
896
+ };
897
+ Date.prototype.toLocaleTimeString = function () {
898
+ try {
899
+ var args = Array.prototype.slice.call(arguments);
900
+ if (!args[0]) args[0] = FP.locale;
901
+ if (!args[1]) args[1] = { timeZone: FP.timezone };
902
+ else if (!args[1].timeZone) args[1].timeZone = FP.timezone;
903
+ return origToLocaleTimeString.apply(this, args);
904
+ } catch (e) { return origToLocaleTimeString.apply(this, arguments); }
905
+ };
906
+ } catch (e) {}
907
+ // Also spoof Intl.DateTimeFormat().resolvedOptions().timeZone
908
+ try {
909
+ var origDTF = Intl.DateTimeFormat;
910
+ var patchedDTF = function () {
911
+ var result = new origDTF.apply(this, arguments);
912
+ var origResolved = result.resolvedOptions.bind(result);
913
+ result.resolvedOptions = function () {
914
+ var opts = origResolved();
915
+ opts.timeZone = FP.timezone;
916
+ return opts;
917
+ };
918
+ return result;
919
+ };
920
+ patchedDTF.prototype = origDTF.prototype;
921
+ window.Intl.DateTimeFormat = patchedDTF;
922
+ } catch (e) {}
923
+ } catch (e) {}
924
+
925
+ // ── 41. window.screenX / window.screenY (window position on screen) ───
926
+ try {
927
+ Object.defineProperty(window, 'screenX', { get: function () { return 0; }, configurable: true });
928
+ Object.defineProperty(window, 'screenY', { get: function () { return 0; }, configurable: true });
929
+ Object.defineProperty(window, 'screenLeft', { get: function () { return 0; }, configurable: true });
930
+ Object.defineProperty(window, 'screenTop', { get: function () { return 0; }, configurable: true });
931
+ } catch (e) {}
932
+
933
+ // ── 42. navigator.keyboard (layout map) ───────────────────────────────
934
+ try {
935
+ if (navigator.keyboard && navigator.keyboard.getLayoutMap) {
936
+ var origGetLayoutMap = navigator.keyboard.getLayoutMap.bind(navigator.keyboard);
937
+ navigator.keyboard.getLayoutMap = function () {
938
+ return origGetLayoutMap().catch(function () {
939
+ // Return a basic US keyboard layout map
940
+ var layoutMap = new Map();
941
+ var keys = ['KeyA','KeyB','KeyC','KeyD','KeyE','KeyF','KeyG','KeyH','KeyI','KeyJ','KeyK','KeyL','KeyM','KeyN','KeyO','KeyP','KeyQ','KeyR','KeyS','KeyT','KeyU','KeyV','KeyW','KeyX','KeyY','KeyZ'];
942
+ var values = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
943
+ for (var i = 0; i < keys.length; i++) layoutMap.set(keys[i], values[i]);
944
+ return layoutMap;
945
+ });
946
+ };
947
+ }
948
+ } catch (e) {}
949
+
950
+ // ── 43. navigator.scheduling ───────────────────────────────────────────
951
+ try {
952
+ if (!navigator.scheduling) {
953
+ Object.defineProperty(navigator, 'scheduling', {
954
+ get: function () {
955
+ return { isInputPending: function () { return false; } };
956
+ },
957
+ configurable: true,
958
+ });
959
+ }
960
+ } catch (e) {}
961
+
962
+ // ── 44. navigator.globalPrivacyControl ────────────────────────────────
963
+ try {
964
+ Object.defineProperty(navigator, 'globalPrivacyControl', {
965
+ get: function () { return false; },
966
+ configurable: true,
967
+ });
968
+ } catch (e) {}
969
+
970
+ // ── 45. CSS media queries (prefers-color-scheme, prefers-reduced-motion) ─
971
+ try {
972
+ var origMatchMediaOrig = window.matchMedia;
973
+ var origMM = window.matchMedia;
974
+ window.matchMedia = function (query) {
975
+ var result = origMM.call(this, query);
976
+ // Spoof prefers-color-scheme to 'light'
977
+ if (query && query.indexOf('prefers-color-scheme') !== -1) {
978
+ return { matches: query.indexOf('dark') === -1, media: query, addListener: function () {}, removeListener: function () {}, addEventListener: function () {}, removeEventListener: function () {}, dispatchEvent: function () { return false; } };
979
+ }
980
+ // Spoof prefers-reduced-motion to 'no-preference'
981
+ if (query && query.indexOf('prefers-reduced-motion') !== -1) {
982
+ return { matches: query.indexOf('reduce') === -1 ? false : false, media: query, addListener: function () {}, removeListener: function () {}, addEventListener: function () {}, removeEventListener: function () {}, dispatchEvent: function () { return false; } };
983
+ }
984
+ // Spoof prefers-contrast
985
+ if (query && query.indexOf('prefers-contrast') !== -1) {
986
+ return { matches: false, media: query, addListener: function () {}, removeListener: function () {}, addEventListener: function () {}, removeEventListener: function () {}, dispatchEvent: function () { return false; } };
987
+ }
988
+ return result;
989
+ };
990
+ } catch (e) {}
991
+
992
+ // ── 46. navigator.storage estimate ─────────────────────────────────────
993
+ try {
994
+ if (navigator.storage && navigator.storage.estimate) {
995
+ var origEstimate = navigator.storage.estimate.bind(navigator.storage);
996
+ navigator.storage.estimate = function () {
997
+ return origEstimate().catch(function () {
998
+ return { usage: 50000000, quota: 2000000000 };
999
+ });
1000
+ };
1001
+ }
1002
+ } catch (e) {}
1003
+
1004
+ // ── 47. navigator.credentials (PasswordCredential) ─────────────────────
1005
+ try {
1006
+ if (!navigator.credentials) {
1007
+ Object.defineProperty(navigator, 'credentials', {
1008
+ get: function () {
1009
+ return { get: function () { return Promise.resolve(null); }, store: function () { return Promise.resolve(null); }, create: function () { return Promise.resolve(null); }, preventSilentAccess: function () { return Promise.resolve(); } };
1010
+ },
1011
+ configurable: true,
1012
+ });
1013
+ }
1014
+ } catch (e) {}
1015
+
1016
+ // ── 48. Error.stack trace sanitization ─────────────────────────────────
1017
+ // Some detection scripts check if Error.stack contains Playwright/puppeteer references.
1018
+ // On Firefox, Error.prototype.stack is a lazy accessor on the instance, not a getter
1019
+ // on Error.prototype, so patching the prototype's descriptor no-ops. Instead we wrap
1020
+ // Error's stack access by defining a getter on each new Error via the constructor, and
1021
+ // also patch Error.prepareStackTrace where present (V8-style engines).
1022
+
1023
+ try {
1024
+ var sanitizeStack = function (stack) {
1025
+ if (typeof stack === 'string') {
1026
+ return stack.replace(/playwright|puppeteer|automation|__pw_|__playwright/gi, '');
1027
+ }
1028
+ if (stack && Array.isArray(stack)) {
1029
+ return stack.map(function (frame) {
1030
+ if (frame && typeof frame === 'object') {
1031
+ try {
1032
+ if (typeof frame.fileName === 'string') {
1033
+ frame.fileName = frame.fileName.replace(/playwright|puppeteer|__pw_|__playwright/gi, '');
1034
+ }
1035
+ if (typeof frame.toString === 'function') {
1036
+ var s = frame.toString();
1037
+ if (/playwright|puppeteer|__pw_|__playwright/i.test(s)) {
1038
+ // best-effort: rewrite the stringified form
1039
+ frame.toString = function () { return s.replace(/playwright|puppeteer|__pw_|__playwright/gi, ''); };
1040
+ }
1041
+ }
1042
+ } catch (e) {}
1043
+ }
1044
+ return frame;
1045
+ });
1046
+ }
1047
+ return stack;
1048
+ };
1049
+
1050
+ // V8-style: hook prepareStackTrace (returns structured frames)
1051
+ if (typeof Error.prepareStackTrace === 'function' || Error.prepareStackTrace === undefined) {
1052
+ var origPrepare = Error.prepareStackTrace;
1053
+ Error.prepareStackTrace = function (err, stack) {
1054
+ var result = origPrepare ? origPrepare.call(this, err, stack) : stack;
1055
+ return sanitizeStack(result);
1056
+ };
1057
+ }
1058
+
1059
+ // Firefox-style: define a stack getter on the Error prototype that intercepts the
1060
+ // lazy lookup. We redefine on Error.prototype with a getter that calls the original
1061
+ // underlying value (read once, then sanitize). This works because Firefox falls back
1062
+ // to the prototype getter when the own property hasn't been materialized yet.
1063
+ var stackDesc = Object.getOwnPropertyDescriptor(Error.prototype, 'stack');
1064
+ if (!stackDesc || stackDesc.get) {
1065
+ var origStackGet = stackDesc ? stackDesc.get : null;
1066
+ Object.defineProperty(Error.prototype, 'stack', {
1067
+ get: function () {
1068
+ var raw;
1069
+ if (origStackGet) {
1070
+ raw = origStackGet.call(this);
1071
+ } else {
1072
+ try { raw = this.__stack_cache__ || (this.__stack_cache__ = sanitizeStack(new Error().stack)); } catch (e) { raw = ''; }
1073
+ }
1074
+ return sanitizeStack(raw);
1075
+ },
1076
+ set: function (v) { this.__stack_cache__ = v; },
1077
+ configurable: true,
1078
+ });
1079
+ }
1080
+ } catch (e) {}
1081
+
1082
+ // ── 49. navigator.appVersion aligned with UA ──────────────────────────
1083
+ try {
1084
+ var appVer = FP.userAgent.replace(/^Mozilla\\//, '');
1085
+ Object.defineProperty(navigator, 'appVersion', {
1086
+ get: function () { return appVer; },
1087
+ configurable: true,
1088
+ });
1089
+ Object.defineProperty(navigator, 'appName', {
1090
+ get: function () { return 'Netscape'; },
1091
+ configurable: true,
1092
+ });
1093
+ } catch (e) {}
1094
+
1095
+ // ── 50. document.characterSet ─────────────────────────────────────────
1096
+ try {
1097
+ Object.defineProperty(document, 'characterSet', {
1098
+ get: function () { return 'UTF-8'; },
1099
+ configurable: true,
1100
+ });
1101
+ Object.defineProperty(document, 'charset', {
1102
+ get: function () { return 'UTF-8'; },
1103
+ configurable: true,
1104
+ });
1105
+ } catch (e) {}
1106
+
1107
+ // ── 51. Font measurement spoofing ──────────────────────────────────────
1108
+ // Detection scripts measure text width with fallback fonts to detect installed fonts.
1109
+ // We add slight noise to measureText/offsetWidth to break this technique.
1110
+ try {
1111
+ var origMeasureText = CanvasRenderingContext2D.prototype.measureText;
1112
+ CanvasRenderingContext2D.prototype.measureText = function (text) {
1113
+ var result = origMeasureText.call(this, text);
1114
+ // Add tiny noise to width (±0.3px) — enough to break font detection, invisible to users
1115
+ try {
1116
+ var noise = (FP.canvasNoiseSeed % 7 - 3) * 0.1;
1117
+ var origWidth = result.width;
1118
+ Object.defineProperty(result, 'width', { get: function () { return origWidth + noise; }, configurable: true });
1119
+ } catch (e) {}
1120
+ return result;
1121
+ };
1122
+ // Also noise HTMLElement.offsetWidth/offsetHeight slightly for font detection
1123
+ var origOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
1124
+ if (origOffsetWidth && origOffsetWidth.get) {
1125
+ var origOWGet = origOffsetWidth.get;
1126
+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
1127
+ get: function () {
1128
+ var w = origOWGet.call(this);
1129
+ // Only noise small elements (font detection uses small test spans)
1130
+ if (w > 0 && w < 50) return Math.round(w + (FP.canvasNoiseSeed % 3 - 1) * 0.2);
1131
+ return w;
1132
+ },
1133
+ configurable: true,
1134
+ });
1135
+ }
1136
+ } catch (e) {}
1137
+
1138
+ // ── 52. AudioContext full pipeline spoofing ────────────────────────────
1139
+ try {
1140
+ // Patch AnalyserNode.getFloatFrequencyData
1141
+ if (window.AnalyserNode && AnalyserNode.prototype.getFloatFrequencyData) {
1142
+ var origGetFloatFreq = AnalyserNode.prototype.getFloatFrequencyData;
1143
+ AnalyserNode.prototype.getFloatFrequencyData = function (array) {
1144
+ origGetFloatFreq.call(this, array);
1145
+ // Add tiny noise to frequency data
1146
+ for (var i = 0; i < array.length; i++) {
1147
+ array[i] = array[i] + (Math.sin(i + FP.audioNoiseSeed * 1000) * 0.0001);
1148
+ }
1149
+ };
1150
+ }
1151
+ // Patch AnalyserNode.getByteFrequencyData
1152
+ if (window.AnalyserNode && AnalyserNode.prototype.getByteFrequencyData) {
1153
+ var origGetByteFreq = AnalyserNode.prototype.getByteFrequencyData;
1154
+ AnalyserNode.prototype.getByteFrequencyData = function (array) {
1155
+ origGetByteFreq.call(this, array);
1156
+ for (var i = 0; i < array.length; i++) {
1157
+ if (array[i] > 0) array[i] = Math.max(0, Math.min(255, array[i] + (FP.canvasNoiseSeed % 3 - 1)));
1158
+ }
1159
+ };
1160
+ }
1161
+ // Patch OscillatorNode frequency (deterministic per account)
1162
+ if (window.OscillatorNode && OscillatorNode.prototype.frequency) {
1163
+ var origFreqDesc = Object.getOwnPropertyDescriptor(OscillatorNode.prototype, 'frequency');
1164
+ if (origFreqDesc && origFreqDesc.get) {
1165
+ var origFreqGet = origFreqDesc.get;
1166
+ try {
1167
+ Object.defineProperty(OscillatorNode.prototype, 'frequency', {
1168
+ get: function () {
1169
+ var f = origFreqGet.call(this);
1170
+ // Wrap the setter so a probe that reassigns frequency still
1171
+ // lands on a value derived from the per-account seed.
1172
+ var patched = parseFloat(f.value) + ((FP.audioNoiseSeed * 1000) % 0.001);
1173
+ try { f.value = patched; } catch (e) {}
1174
+ return f;
1175
+ },
1176
+ set: function (v) {
1177
+ var origSet = (origFreqDesc && origFreqDesc.set) ? origFreqDesc.set : null;
1178
+ if (origSet) origSet.call(this, v);
1179
+ },
1180
+ configurable: true,
1181
+ });
1182
+ } catch (e) {}
1183
+ }
1184
+ }
1185
+ } catch (e) {}
1186
+
1187
+ // ── 53. WebGL additional parameter spoofing ───────────────────────────
1188
+ try {
1189
+ var spoofWebGLParams = function (proto) {
1190
+ var origGetParam = proto.getParameter;
1191
+ proto.getParameter = function (parameter) {
1192
+ // UNMASKED_VENDOR_WEBGL = 37445, UNMASKED_RENDERER_WEBGL = 37446
1193
+ if (parameter === 37445) return FP.gpu.vendor;
1194
+ if (parameter === 37446) return FP.gpu.renderer;
1195
+ // MAX_TEXTURE_SIZE — vary slightly per account (4096-16384)
1196
+ if (parameter === 3379) return 4096 + (FP.canvasNoiseSeed % 4) * 2048;
1197
+ // MAX_VIEWPORT_DIMS — vary
1198
+ if (parameter === 3386) return new Int32Array([4096 + (FP.canvasNoiseSeed % 4) * 2048, 4096 + (FP.canvasNoiseSeed % 4) * 2048]);
1199
+ // MAX_VERTEX_ATTRIBS
1200
+ if (parameter === 34921) return 16;
1201
+ // MAX_VARYING_VECTORS
1202
+ if (parameter === 36348) return 30;
1203
+ // MAX_VERTEX_UNIFORM_VECTORS
1204
+ if (parameter === 36347) return 4095;
1205
+ // MAX_FRAGMENT_UNIFORM_VECTORS
1206
+ if (parameter === 36349) return 1024;
1207
+ // ALIASED_LINE_WIDTH_RANGE
1208
+ if (parameter === 28460) return new Float32Array([1, 1 + (FP.canvasNoiseSeed % 10) * 0.1]);
1209
+ // ALIASED_POINT_SIZE_RANGE
1210
+ if (parameter === 33902) return new Float32Array([1, 1024]);
1211
+ return origGetParam.call(this, parameter);
1212
+ };
1213
+ };
1214
+ if (window.WebGLRenderingContext) spoofWebGLParams(WebGLRenderingContext.prototype);
1215
+ if (window.WebGL2RenderingContext) spoofWebGLParams(WebGL2RenderingContext.prototype);
1216
+ } catch (e) {}
1217
+
1218
+ // ── 54. Playwright artifact cleanup ───────────────────────────────────
1219
+ try {
1220
+ // Remove Playwright/puppeteer injected properties
1221
+ var playwrightProps = ['__playwright__', '__pw_', '__pwInitScripts', '__playwright__binding', '__playwright__driver'];
1222
+ playwrightProps.forEach(function (prop) {
1223
+ try {
1224
+ if (window[prop] !== undefined) {
1225
+ try { delete window[prop]; } catch (e) {
1226
+ try { Object.defineProperty(window, prop, { value: undefined, configurable: true }); } catch (e2) {}
1227
+ }
1228
+ }
1229
+ } catch (e) {}
1230
+ });
1231
+ // Also clean up any automation-related properties on document
1232
+ try {
1233
+ var docProps = Object.getOwnPropertyNames(document).filter(function (k) { return k.startsWith('__pw') || k.startsWith('__playwright'); });
1234
+ docProps.forEach(function (p) { try { delete document[p]; } catch (e) {} });
1235
+ } catch (e) {}
1236
+ // Override Object.getOwnPropertyDescriptor to hide Playwright bindings
1237
+ var origGetOwnPropDesc = Object.getOwnPropertyDescriptor;
1238
+ Object.getOwnPropertyDescriptor = function (obj, prop) {
1239
+ if (typeof prop === 'string' && (prop.startsWith('__pw') || prop.startsWith('__playwright'))) {
1240
+ return undefined;
1241
+ }
1242
+ return origGetOwnPropDesc.apply(this, arguments);
1243
+ };
1244
+ } catch (e) {}
1245
+
1246
+ })();
1247
+ `;
1248
+ return script;
1249
+ }
1250
+
1251
1251
  module.exports = { buildStealthScript };