-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
7189 lines (6707 loc) · 350 KB
/
main.js
File metadata and controls
7189 lines (6707 loc) · 350 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
// Silence Node.js deprecation warnings from transitive deps (e.g. discord-rpc → punycode)
process.noDeprecation = true;
// Suppress Electron ExtensionLoadWarning (MV2 deprecation) from stderr
const _stderrWrite = process.stderr.write.bind(process.stderr);
process.stderr.write = function(data, ...args) {
if (typeof data === 'string' && data.includes('ExtensionLoadWarning')) return true;
return _stderrWrite(data, ...args);
};
const {
app, BrowserWindow, BrowserView,
ipcMain, dialog, shell, session, Menu, clipboard, screen,
} = require('electron');
const path = require('path');
const fs = require('fs');
const https = require('https');
const { spawn } = require('child_process');
const { pathToFileURL } = require('url');
const os = require('os');
const { shouldBlock } = require('./blocklist.js');
// Domains never blocked regardless of settings (needed for site functionality)
const BUILTIN_WHITELIST = [
// TikTok — only core content/video delivery domains; tracker subdomains are NOT listed
// so they can be blocked by shouldBlock() normally.
'tiktok.com','tiktokv.com','tiktokcdn.com','tiktokcdn-us.com','ttwstatic.com',
'ibytedtos.com','ibyteimg.com','byteoversea.com',
// Spotify — ALL domains required for full functionality including DRM
'spotify.com','*.spotify.com',
'scdn.co','*.scdn.co',
'spotifycdn.com','*.spotifycdn.com',
'spotifycdn.net','*.spotifycdn.net',
'pscdn.co','*.pscdn.co',
'spotilocal.com','*.spotilocal.com',
'audio-ak-spotify-com.akamaized.net',
'spclient.wg.spotify.com','apresolve.spotify.com','dealer.spotify.com',
'open.spotify.com','accounts.spotify.com','api.spotify.com',
'www.spotify.com','play.spotify.com','login.spotify.com',
'auth.spotify.com','api-partner.spotify.com','*.spotifycdn.net',
'*.spotifycdn.com','*.spotifycdn.co',
// Google — ALL auth, sign-in, and service domains must preserve headers intact.
// Google's OAuth flow validates Referer, Sec-Fetch-*, and other headers across
// redirects between these domains. Any stripping triggers the
// "This browser may not be secure" block on accounts.google.com.
'google.com','accounts.google.com','apis.google.com',
'googleapis.com','googleusercontent.com','gstatic.com',
'gmail.com','youtube.com','ytimg.com','ggpht.com',
'translate.google.com', // For translation feature
'translate.goog', '*.translate.goog', // Google's .translate.goog proxy (page translation)
// Bing — Microsoft search engine needs proper headers to work
'bing.com','www.bing.com',
// NOTE: google-analytics.com and googletagmanager.com intentionally NOT listed here
// so they remain blockable by shouldBlock(). They don't affect Google auth flows.
];
// Tracker/analytics subdomains that must be blocked even if their parent domain
// is in BUILTIN_WHITELIST. These take priority over the whitelist.
const TRACKER_FORCE_BLOCK = new Set([
// TikTok analytics, logging, monitoring, and ad infrastructure
'analytics.tiktok.com', 'log.tiktok.com', 'log-va.tiktok.com',
'log-sg.tiktok.com', 'log-useast2a.tiktok.com', 'log-useast8.tiktok.com',
'mon.tiktok.com', 'stats.tiktok.com', 'event.tiktok.com',
'metrics.tiktok.com', 'monitor.tiktok.com', 'tracker.tiktok.com',
'ads.tiktok.com', 'business.tiktok.com',
// ByteDance tracking SDK and analytics infrastructure (not needed for playback)
'snssdk.com', 'bdurl.net', 'musical.ly',
'toblog.ctobsnssdk.com', 'lf16-tiktok-web.tiktokcdn.com',
// Google tracker subdomains — force-block even though googleapis.com/gstatic.com
// are in BUILTIN_WHITELIST for auth. These subdomains carry no auth traffic.
'imasdk.googleapis.com',
'pagead2.googlesyndication.com', 'tpc.googlesyndication.com',
'stats.g.doubleclick.net', 'cm.g.doubleclick.net',
'fundingchoicesmessages.google.com',
'adservice.google.com',
'ssl.google-analytics.com', 'analytics.google.com',
'csi.gstatic.com',
]);
if (process.platform === 'win32') app.setAppUserModelId('com.lander.browser');
// Remove the automation flag Electron sets by default — Google checks this
// to determine if the browser is automated/non-standard. Must be set before
// any window is created (commandLine switches are read at startup).
app.commandLine.appendSwitch('disable-blink-features', 'AutomationControlled');
// ── ENHANCED PRIVACY ─────────────────────────────────────────────────────────
// Prevent IP leaks through WebRTC — hides local/VPN IPs but keeps WebRTC
// functional for video calls (Discord, Meet, etc.).
app.commandLine.appendSwitch('webrtc-ip-handling-policy', 'default_public_interface_only');
// ── Privacy-preserving network flags ─────────────────────────────────────────
// NOTE: --disable-background-networking is intentionally NOT used here.
// It also kills speculative DNS prefetch and TCP preconnect, which Chrome uses
// to warm connections before the user clicks — a major page-load speedup.
// Instead we use targeted flags that only disable the phone-home services:
// No Google field trials / A-B experiments (stops phoning home to Finch servers)
app.commandLine.appendSwitch('disable-field-trial-config');
// No component update pings (CRLSets, Widevine update checks, etc.)
app.commandLine.appendSwitch('disable-component-update');
// No Safe Browsing URL reporting to Google
app.commandLine.appendSwitch('disable-client-side-phishing-detection');
// Suppress Chrome's built-in translation offer (we have our own translate)
app.commandLine.appendSwitch('disable-translate');
// No default apps check
app.commandLine.appendSwitch('disable-default-apps');
// No spell check network requests (local dictionary still works)
app.commandLine.appendSwitch('disable-spell-check-service');
// No crash reporter phone-home
app.commandLine.appendSwitch('disable-crash-reporter');
// No Google account sync
app.commandLine.appendSwitch('disable-sync');
// Disable hyperlink auditing pings (<a ping="..."> attribute)
app.commandLine.appendSwitch('no-pings');
// Disable domain reliability monitoring (Chromium phones home on navigation errors)
app.commandLine.appendSwitch('disable-domain-reliability');
// Disable metrics reporting
app.commandLine.appendSwitch('metrics-recording-only');
// Disable network prediction / prefetching to prevent DNS leaks
app.commandLine.appendSwitch('disable-features', 'NetworkPrediction,OptimizationHints');
// Force partitioned third-party cookies (prevents cross-site tracking)
app.commandLine.appendSwitch('partitioned-cookies');
// ── Widevine CDM (enables DRM for Spotify, Netflix, etc.) ─────────────────────
// Priority order:
// 1. Lander's own downloaded CDM (no Chrome/Edge needed)
// 2. Chrome / Edge / Brave system install fallback
// If nothing is found at startup, widevineAutoDownload() runs after app ready
// and saves the CDM to userData — takes effect on next launch.
let _widevineLoaded = false;
(function tryLoadWidevine() {
// ── Shared helpers ──────────────────────────────────────────────────────────
const _sortVersions = arr => arr
.filter(v => /^\d+\.\d+\.\d+\.\d+$/.test(v))
.sort((a, b) => {
const pa = a.split('.').map(Number), pb = b.split('.').map(Number);
for (let i = 0; i < 4; i++) { if (pa[i] !== pb[i]) return pb[i] - pa[i]; }
return 0;
});
const _register = (cdmPath, version) => {
app.commandLine.appendSwitch('widevine-cdm-path', cdmPath);
app.commandLine.appendSwitch('widevine-cdm-version', version || '');
_widevineLoaded = true;
return true;
};
// ── 1. Lander's own downloaded CDM (userData/landerbrowser/WidevineCdm/<ver>/) ───
function _tryOwnCdm() {
let userData;
try { userData = app.getPath('userData'); } catch { return false; }
const base = path.join(userData, 'landerbrowser', 'WidevineCdm');
if (!fs.existsSync(base)) return false;
const dllName = process.platform === 'win32' ? 'widevinecdm.dll'
: process.platform === 'linux' ? 'libwidevinecdm.so'
: 'libwidevinecdm.dylib';
for (const ver of _sortVersions(fs.readdirSync(base))) {
const cdmPath = path.join(base, ver, dllName);
if (fs.existsSync(cdmPath)) {
let version = ver;
try { version = JSON.parse(fs.readFileSync(path.join(base, ver, 'manifest.json'), 'utf8')).version || ver; } catch {}
return _register(cdmPath, version);
}
}
return false;
}
// ── 2. Chrome/Edge "Application\<ver>\WidevineCdm" layout ──────────────────
function _tryDir(base) {
if (!fs.existsSync(base)) return false;
for (const ver of _sortVersions(fs.readdirSync(base))) {
const cdmPath = path.join(base, ver, 'WidevineCdm', '_platform_specific', 'win_x64', 'widevinecdm.dll');
const manifest = path.join(base, ver, 'WidevineCdm', 'manifest.json');
if (fs.existsSync(cdmPath) && fs.existsSync(manifest)) {
try { return _register(cdmPath, JSON.parse(fs.readFileSync(manifest, 'utf8')).version || ''); } catch {}
}
}
return false;
}
// ── 3. Chrome/Edge "User Data\WidevineCdm\<ver>" layout ────────────────────
function _tryUserDataDir(base) {
if (!fs.existsSync(base)) return false;
for (const ver of _sortVersions(fs.readdirSync(base))) {
const cdmPath = path.join(base, ver, '_platform_specific', 'win_x64', 'widevinecdm.dll');
const manifest = path.join(base, ver, 'manifest.json');
if (fs.existsSync(cdmPath) && fs.existsSync(manifest)) {
try { return _register(cdmPath, JSON.parse(fs.readFileSync(manifest, 'utf8')).version || ver); } catch {}
}
}
return false;
}
try {
// Always check our own CDM first — works without any other browser installed
if (_tryOwnCdm()) return;
if (process.platform === 'win32') {
const local = process.env.LOCALAPPDATA || '';
const prog = process.env.PROGRAMFILES || 'C:\\Program Files';
const prog86 = process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)';
const userDataCandidates = [
path.join(local, 'Google', 'Chrome', 'User Data', 'WidevineCdm'),
path.join(local, 'Microsoft', 'Edge', 'User Data', 'WidevineCdm'),
path.join(local, 'BraveSoftware', 'Brave-Browser', 'User Data', 'WidevineCdm'),
path.join(prog, 'Google', 'Chrome', 'User Data', 'WidevineCdm'),
];
let found = false;
for (const c of userDataCandidates) { if (_tryUserDataDir(c)) { found = true; break; } }
if (!found) {
for (const c of [
path.join(local, 'Google', 'Chrome', 'Application'),
path.join(local, 'Microsoft', 'Edge', 'Application'),
path.join(prog, 'Google', 'Chrome', 'Application'),
path.join(prog86, 'Google', 'Chrome', 'Application'),
path.join(prog, 'Microsoft', 'Edge', 'Application'),
]) { if (_tryDir(c)) break; }
}
} else if (process.platform === 'darwin') {
const _tryMacCdm = (cdmPath, manifestPath) => {
if (!fs.existsSync(cdmPath) || !fs.existsSync(manifestPath)) return false;
try { return _register(cdmPath, JSON.parse(fs.readFileSync(manifestPath, 'utf8')).version || ''); } catch { return false; }
};
const _macBase = (n, f) =>
`/Applications/${n}.app/Contents/Frameworks/${f}.framework/Versions/Current/Libraries/WidevineCdm`;
const _ch = _macBase('Google Chrome', 'Google Chrome Framework');
const _br = _macBase('Brave Browser', 'Brave Browser Framework');
[
[_ch + '/_platform_specific/mac_arm64/libwidevinecdm.dylib', _ch + '/manifest.json'],
[_ch + '/_platform_specific/mac_x64/libwidevinecdm.dylib', _ch + '/manifest.json'],
[_br + '/_platform_specific/mac_arm64/libwidevinecdm.dylib', _br + '/manifest.json'],
[_br + '/_platform_specific/mac_x64/libwidevinecdm.dylib', _br + '/manifest.json'],
].some(([cdm, mf]) => _tryMacCdm(cdm, mf));
} else if (process.platform === 'linux') {
const home = process.env.HOME || '';
function _tryLinuxCdmDir(base) {
if (!fs.existsSync(base)) return false;
for (const ver of _sortVersions(fs.readdirSync(base))) {
const cdmPath = path.join(base, ver, '_platform_specific', 'linux_x64', 'libwidevinecdm.so');
const manifest = path.join(base, ver, 'manifest.json');
if (fs.existsSync(cdmPath) && fs.existsSync(manifest)) {
try { return _register(cdmPath, JSON.parse(fs.readFileSync(manifest, 'utf8')).version || ''); } catch {}
}
}
return false;
}
for (const c of [
path.join(home, '.config', 'google-chrome', 'WidevineCdm'),
path.join(home, '.config', 'chromium', 'WidevineCdm'),
path.join(home, '.var', 'app', 'com.google.Chrome', 'config', 'google-chrome', 'WidevineCdm'),
path.join(home, '.var', 'app', 'org.chromium.Chromium', 'config', 'chromium', 'WidevineCdm'),
path.join(home, 'snap', 'google-chrome', 'current', '.config', 'google-chrome', 'WidevineCdm'),
'/opt/google/chrome/WidevineCdm',
'/usr/lib/chromium/WidevineCdm',
'/usr/lib/chromium-browser/WidevineCdm',
]) { if (_tryLinuxCdmDir(c)) break; }
}
} catch { /* Widevine unavailable — silently continue */ }
})();
// ── Widevine self-downloader ──────────────────────────────────────────────────
// Downloads Widevine CDM directly from Google's component update server —
// no Chrome or Edge installation required. Triggered at app ready when no
// CDM is found. The downloaded binary is stored in userData and loaded on
// the NEXT launch (commandLine switches must be set before app ready).
function _widevineDownloadBuffer(url) {
return new Promise((resolve, reject) => {
function follow(u) {
const parsed = new URL(u);
const opts = {
hostname: parsed.hostname,
path: parsed.pathname + parsed.search,
headers: { 'User-Agent': 'GoogleUpdate/1.3.36.372 winhttp' },
};
https.get(opts, res => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
return follow(res.headers.location);
}
if (res.statusCode !== 200) return reject(new Error('HTTP ' + res.statusCode));
const chunks = [];
res.on('data', c => chunks.push(c));
res.on('end', () => resolve(Buffer.concat(chunks)));
}).on('error', reject);
}
follow(url);
});
}
function _widevineQueryUpdateServer() {
return new Promise((resolve, reject) => {
const osPlatform = process.platform === 'win32' ? 'win'
: process.platform === 'darwin' ? 'mac' : 'linux';
const appid = 'oimompecagnajdejgnnjijobebaeignd';
const body = Buffer.from(
'<?xml version="1.0" encoding="UTF-8"?>' +
'<request protocol="3.1" version="chrome-142.0.0.0" prodversion="142.0.0.0" lang="en-US" installsource="ondemandupdate">' +
`<os platform="${osPlatform}" arch="x64"/>` +
`<app appid="${appid}" version="0.0.0.0"><updatecheck/></app>` +
'</request>',
'utf8'
);
const req = https.request({
hostname: 'update.googleapis.com',
path: '/service/update2/crx',
method: 'POST',
headers: {
'Content-Type': 'application/xml',
'Content-Length': body.length,
'User-Agent': 'GoogleUpdate/1.3.36.372 winhttp',
},
timeout: 12000,
}, res => {
const chunks = [];
res.on('data', c => chunks.push(c));
res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('Widevine update server timeout')); });
req.write(body);
req.end();
});
}
function _widevineParseUpdateXml(xml) {
// Extract codebase URL (download prefix)
const cbMatch = xml.match(/codebase="([^"]+)"/);
// Extract package filename (the .crx3 file)
const nameMatch = xml.match(/name="([^"]+\.crx3?)"/);
// Extract CDM version from manifest element
const verMatch = xml.match(/<manifest[^>]+version="(\d+\.\d+\.\d+\.\d+)"/);
if (!cbMatch || !nameMatch || !verMatch) return null;
return {
version: verMatch[1],
downloadUrl: cbMatch[1] + nameMatch[1],
};
}
function _widevineExtractZipFromCrx3(buf) {
// CRX3 = "Cr24" magic + version(4) + header_size(4) + protobuf_header(header_size) + ZIP
if (buf.length < 12 || buf.toString('ascii', 0, 4) !== 'Cr24') throw new Error('Not a CRX file');
if (buf.readUInt32LE(4) !== 3) throw new Error('Only CRX3 is supported');
const zipStart = 12 + buf.readUInt32LE(8);
if (zipStart >= buf.length) throw new Error('CRX3 header extends beyond file');
return buf.slice(zipStart);
}
async function _widevineExtractFromZip(zipBuf, destDir) {
// Pure Node.js ZIP extractor — no external dependencies, uses built-in zlib
const zlib = require('zlib');
const dllName = process.platform === 'win32' ? 'widevinecdm.dll'
: process.platform === 'linux' ? 'libwidevinecdm.so'
: 'libwidevinecdm.dylib';
const platformSubdir = process.platform === 'win32' ? '_platform_specific/win_x64'
: process.platform === 'linux' ? '_platform_specific/linux_x64'
: (process.arch === 'arm64' ? '_platform_specific/mac_arm64' : '_platform_specific/mac_x64');
const targetDll = `${platformSubdir}/${dllName}`;
let dllWritten = false;
let offset = 0;
while (offset + 30 <= zipBuf.length) {
const sig = zipBuf.readUInt32LE(offset);
// Central directory or end-of-central-directory record — done scanning local entries
if (sig === 0x02014b50 || sig === 0x06054b50) break;
if (sig !== 0x04034b50) { offset++; continue; } // skip until local file header
const compression = zipBuf.readUInt16LE(offset + 8);
const compSize = zipBuf.readUInt32LE(offset + 18);
const fnLen = zipBuf.readUInt16LE(offset + 26);
const extraLen = zipBuf.readUInt16LE(offset + 28);
const filename = zipBuf.toString('utf8', offset + 30, offset + 30 + fnLen).replace(/\\/g, '/');
const dataOffset = offset + 30 + fnLen + extraLen;
const isDll = filename === targetDll || filename.endsWith('/' + dllName);
const isManifest = filename === 'manifest.json';
if (isDll || isManifest) {
const compressed = zipBuf.slice(dataOffset, dataOffset + compSize);
let data;
if (compression === 0) {
data = compressed; // stored — no compression
} else if (compression === 8) {
data = zlib.inflateRawSync(compressed); // deflate — standard ZIP compression
} else {
throw new Error(`Unsupported ZIP compression method: ${compression}`);
}
const outPath = path.join(destDir, isDll ? dllName : 'manifest.json');
fs.writeFileSync(outPath, data);
if (isDll) dllWritten = true;
}
offset = dataOffset + compSize;
}
if (!dllWritten) throw new Error('CDM binary not found in CRX package');
}
async function widevineAutoDownload() {
if (_widevineLoaded) return; // already loaded from disk at startup
try {
let userData;
try { userData = app.getPath('userData'); } catch { return; }
send('toast', 'Downloading Widevine DRM (needed for Spotify/Netflix)…', 'teal');
const xml = await _widevineQueryUpdateServer();
const info = _widevineParseUpdateXml(xml);
if (!info) throw new Error('Could not parse Widevine update server response');
const { version, downloadUrl } = info;
const destDir = path.join(userData, 'landerbrowser', 'WidevineCdm', version);
fs.mkdirSync(destDir, { recursive: true });
const crxBuf = await _widevineDownloadBuffer(downloadUrl);
const zipBuf = _widevineExtractZipFromCrx3(crxBuf);
await _widevineExtractFromZip(zipBuf, destDir);
// Write a minimal manifest if the ZIP didn't contain one
const mfPath = path.join(destDir, 'manifest.json');
if (!fs.existsSync(mfPath)) fs.writeFileSync(mfPath, JSON.stringify({ version }));
// Make the binary executable on Unix
if (process.platform !== 'win32') {
const dllName = process.platform === 'linux' ? 'libwidevinecdm.so' : 'libwidevinecdm.dylib';
try { fs.chmodSync(path.join(destDir, dllName), 0o755); } catch {}
}
send('toast', `Widevine ${version} ready — restart Lander Browser for Spotify/Netflix DRM`, 'teal');
} catch (err) {
// Silently fail — DRM just won't work until a later attempt or manual install
send('toast', 'Widevine download failed — DRM (Spotify/Netflix) may not work', 'err');
}
}
// Allow audio/video autoplay without user gesture (needed for Music Player)
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');
// Prevent Chromium from EVER suspending background renderer processes or their media.
// This is the definitive fix for videos/audio pausing when a BV is detached from the window.
// JS-level overrides (visibility, blur, etc.) can race with native Chromium scheduler events;
// these flags disable the scheduler behaviour entirely at the process level.
app.commandLine.appendSwitch('disable-renderer-backgrounding');
app.commandLine.appendSwitch('disable-background-media-suspend');
// ── Default browser + external URL handling ──────────────────────────────────
// Register RAW as a capable handler for http/https at the OS level.
// On Windows 10/11 this writes the registry entries; user still selects via Settings.
// On macOS this may set it directly depending on OS version.
app.setAsDefaultProtocolClient('https');
app.setAsDefaultProtocolClient('http');
// Extract a navigable URL from a process argv array (set as default browser or open-with).
function getArgUrl(argv) {
for (const a of (argv || []).slice(1)) {
if (/^https?:\/\//i.test(a)) return a;
if (/^file:\/\//i.test(a)) return a;
// Windows: file path passed directly (e.g. double-click .html)
if (/\.(html?|xhtml|pdf)$/i.test(a)) {
try { if (fs.existsSync(a)) return pathToFileURL(a).href; } catch {}
}
}
return null;
}
// ── Explicit userData path — prevents Chromium "Unable to move the cache" errors ──
// Without this, Electron picks an OS default that can conflict with other instances
// or trigger cache migration failures (Access Denied 0x5) on Windows.
app.name = 'lander-browser';
app.setPath('userData', require('path').join(app.getPath('appData'), 'lander-browser'));
// Single-instance lock: if RAW is already running and an external link is clicked,
// forward the URL to the existing window instead of opening a second instance.
const _gotSingleLock = app.requestSingleInstanceLock();
if (!_gotSingleLock) { app.quit(); }
app.on('second-instance', (_, argv) => {
if (!win) return;
if (win.isMinimized()) win.restore();
win.focus();
const url = getArgUrl(argv);
if (url) createTab(url, true);
});
// macOS: link clicked in another app while RAW is already running
let _pendingExtUrl = null;
app.on('open-url', (event, url) => {
event.preventDefault();
if (win) createTab(url, true);
else _pendingExtUrl = url;
});
const SPOOF_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36';
const SPOOF_UA_HINTS = '"Not_A Brand";v="8", "Chromium";v="142", "Google Chrome";v="142"';
// Pool of realistic user agents used when per-tab UA rotation is enabled.
const _UA_ROTATE_POOL = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 14.2; rv:133.0) Gecko/20100101 Firefox/133.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
];
// ── Global UA fallback ─────────────────────────────────────────────────────────
// The deepest possible override — covers every WebContents that has NOT had
// setUserAgent() called explicitly (service workers, pre-flight auth checks,
// non-partitioned popup windows, etc.). Must be set BEFORE app.whenReady().
app.userAgentFallback = SPOOF_UA;
// Set the UA at the Chromium process level — applies to every renderer, service
// worker, and sub-frame before any JS runs, overriding Electron's own binary string.
app.commandLine.appendSwitch('user-agent', SPOOF_UA);
// ── Enable features — ONE call; Chromium only honours the last value ──────────
// HardwareMediaKeyHandling + MediaSessionService: media keys & OS media HUD.
// PlatformEncryptedMediaFoundation (win32 only): DRM via Media Foundation.
//
// NOTE: StoragePartitioning and BlockThirdPartyCookies are intentionally NOT
// enabled here. In Chromium 120+ (Electron 36+) these features operate BELOW
// Electron's webRequest layer and block third-party cookies/storage for DRM
// license servers (e.g. spclient.wg.spotify.com) even when those domains are
// whitelisted in our request handlers. Removing them fixes Widevine/Spotify DRM.
// Cross-site isolation is still enforced by our webRequest interceptors.
if (process.platform === 'win32') {
app.commandLine.appendSwitch('enable-features',
'HardwareMediaKeyHandling,MediaSessionService,PlatformEncryptedMediaFoundation');
} else {
app.commandLine.appendSwitch('enable-features',
'HardwareMediaKeyHandling,MediaSessionService');
}
// ── Disable features — ONE call; Chromium only honours the last value ─────────
// NetworkPrediction: no speculative pre-connections leaking browsing intent.
// DnsOverHttps: disable Chromium's built-in DoH (use OS resolver).
// PrefetchPrivacyChanges: keep prefetch from pinging third-party hosts.
// WebRtcHideLocalIpsWithMdns: expose real IP (mDNS can interfere with WebRTC).
// WebAuthentication*: suppress Windows Hello / FIDO2 / passkey dialogs.
app.commandLine.appendSwitch('disable-features',
'NetworkPrediction,DnsOverHttps,PrefetchPrivacyChanges,' +
'WebRtcHideLocalIpsWithMdns,WebAuthentication,WebAuthenticationCableSecondFactor,' +
'WebAuthenticationPasskeysInBrowserWindow,WebAuthenticationRemoteDesktopSupport');
app.commandLine.appendSwitch('no-pings'); // suppress <a ping=> hyperlink auditing
// ── Anti-bot detection flags ─────────────────────────────────────────────────
// Remove Electron-specific infobars / first-run markers that differ from Chrome.
app.commandLine.appendSwitch('disable-infobars');
app.commandLine.appendSwitch('no-first-run');
app.commandLine.appendSwitch('no-default-browser-check');
// Disable component extensions (Chrome's built-in internal extensions like PDF
// viewer) — Electron loads different ones which can be detected via chrome.runtime.
app.commandLine.appendSwitch('disable-component-extensions-with-background-pages');
// Ensure the user-data-dir doesn't leak an Electron-specific path in error reports
app.commandLine.appendSwitch('disable-crash-reporter');
app.commandLine.appendSwitch('disable-gpu-shader-disk-cache'); // prevent GPU cache creation errors
// ── YouTube stealth ad-skip content script ────────────────────────────────────
// ── YouTube Ad Blocker (stealth, comprehensive) ───────────────────────────────
// Design:
// • All injected identifiers are randomised per-injection — no static names to fingerprint
// • Intercepts fetch/XHR to strip ad formats from YouTube player API responses
// • CSS hides every known ad surface (display-ads, overlays, banners, companion ads)
// • MutationObserver reacts only to ad-relevant DOM/attribute changes (low overhead)
// • Speeds through video ads (mute + seek to end + auto-skip button click)
// • Dismisses overlay ads, bot-check dialogs, and enforcement modals
// • Saves/restores user mute/volume/playbackRate around each ad
// • Works on initial page load AND YouTube SPA navigations
const YT_AD_SKIP = `(function(){
if(window.location.pathname.indexOf('/shorts/')===0)return;
// ── Randomised namespace so no static property name is detectable ────────────
var _nsKey='__ytb_'+Math.random().toString(36).slice(2,9);
var _styleId='s'+Math.random().toString(36).slice(2,11);
var _prevNs=window.__ytAdNs;
if(_prevNs){
try{window[_prevNs]&&window[_prevNs].obs&&window[_prevNs].obs.disconnect();}catch(e){}
try{window[_prevNs]&&window[_prevNs].iv&&clearInterval(window[_prevNs].iv);}catch(e){}
try{window[_prevNs]&&window[_prevNs].wObs&&window[_prevNs].wObs.disconnect();}catch(e){}
try{delete window[_prevNs];}catch(e){}
}
window.__ytAdNs=_nsKey;
window[_nsKey]={};
// ── Intercept fetch & XHR: strip ad formats from player/next API responses ──
// This is the most reliable way to prevent ads at the data level.
// We only modify responses from known YouTube player endpoints; everything else
// is passed through unchanged so normal site functionality is unaffected.
(function _patchNetwork(){
function _cleanPlayerResp(obj){
if(!obj||typeof obj!=='object')return obj;
// Remove adPlacements, playerAds, and companionSlots from any object depth
var AD_KEYS=['adPlacements','adSlots','playerAds','adBreakParams',
'adThrottlingModel','companionAdSlots','adErrorInterstitial',
'playerLegacyDesktopWatchAdsRenderer','adPreroll'];
AD_KEYS.forEach(function(k){if(obj[k])obj[k]=[];});
// Also clear the ad-related fields inside playerConfig
if(obj.playerConfig&&obj.playerConfig.adConfig)obj.playerConfig.adConfig={};
if(obj.playerConfig&&obj.playerConfig.mediaCommonConfig)
delete obj.playerConfig.mediaCommonConfig.mediaUstreamerRequestConfig;
return obj;
}
function _tryPatch(text){
try{
var j=JSON.parse(text);
_cleanPlayerResp(j);
// Also handle wrapped responses like {[{"responseContext":...},...]}
if(Array.isArray(j))j.forEach(_cleanPlayerResp);
return JSON.stringify(j);
}catch(e){return text;}
}
function _isAdUrl(url){
return/\/(youtubei|player|next|browse)\//i.test(url)&&
/youtube\.com|yt\.be/i.test(url);
}
// Patch fetch
var _origFetch=window.fetch;
window.fetch=function(input,init){
var url=typeof input==='string'?input:(input&&input.url)||'';
var p=_origFetch.apply(this,arguments);
if(!_isAdUrl(url))return p;
return p.then(function(resp){
if(!resp.ok)return resp;
var ct=resp.headers.get('content-type')||'';
if(ct.indexOf('json')===-1)return resp;
return resp.text().then(function(txt){
var patched=_tryPatch(txt);
return new Response(patched,{status:resp.status,statusText:resp.statusText,headers:resp.headers});
});
});
};
// Patch XHR
var _origOpen=XMLHttpRequest.prototype.open;
var _origSend=XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open=function(m,u){
this._ytAbUrl=u||'';
return _origOpen.apply(this,arguments);
};
XMLHttpRequest.prototype.send=function(){
if(_isAdUrl(this._ytAbUrl||'')){
this.addEventListener('readystatechange',function(){
if(this.readyState!==4)return;
var ct=this.getResponseHeader('content-type')||'';
if(ct.indexOf('json')===-1)return;
try{
Object.defineProperty(this,'responseText',{get:function(){
return _tryPatch(this._ytAbPatchedText||XMLHttpRequest.prototype.responseText.call(this));
},configurable:true});
this._ytAbPatchedText=_tryPatch(XMLHttpRequest.prototype.responseText.call(this)||'');
}catch(e){}
});
}
return _origSend.apply(this,arguments);
};
})();
// ── CSS: hide every known non-video ad surface ──────────────────────────────
(function _injectCSS(){
if(document.getElementById(_styleId))return;
var s=document.createElement('style');
s.id=_styleId;
s.textContent=
// In-feed and display ads
'ytd-promoted-sparkles-text-search-renderer,ytd-promoted-video-renderer,'+
'ytd-display-ad-renderer,ytd-banner-promo-renderer,#masthead-ad,'+
'ytd-ad-slot-renderer,ytd-in-feed-ad-layout-renderer,'+
'ytd-action-companion-ad-renderer,ytd-companion-slot-renderer,'+
'ytd-statement-banner-renderer,ytd-engagement-panel-section-list-renderer[target-id="engagement-panel-ads"],'+
// Player ad overlays and containers
'#player-ads,#player-ads>.ytd-watch-flexy,#frosted-glass-container,'+
'.ytp-ad-overlay-container,.ytp-ce-covering-ad,.ytp-ce-element,'+
'.ytp-ce-covering-overlay,.ytp-suggested-action,.ytp-ad-module,'+
// Google/DoubleClick ad iframes
'[id^="google_ads_iframe"],[id^="aswift_"],[id^="div-gpt-ad"],'+
// Pause overlay ads
'.ad-showing .ytp-pause-overlay,.ad-interrupting .ytp-pause-overlay,'+
// Ad text badges and progress bars
'.ytp-ad-text,.ytp-ad-preview-container,.ytp-ad-badge-container,'+
'.ytp-ad-message-container,.ytp-ad-image-overlay,'+
'.ytp-ad-overlay-ad-info-button-container,'+
'ytd-player-legacy-desktop-watch-ads-renderer,'+
'.ytp-ad-persistent-progress-bar-container,'+
'.ytp-ad-progress-list,.ytp-ad-simple-ad-badge,'+
// Companion / masthead ads
'ytd-display-ad-renderer[slot],ytd-action-companion-ad-renderer[slot],'+
'.ytd-video-masthead-ad-v3-renderer,#video-masthead-ad,'+
'ytd-companion-slot-renderer[slot],'+
// Feed ads (has-based selectors for modern YT layout engine)
'ytd-rich-item-renderer:has(.ytd-ad-slot-renderer),'+
'ytd-rich-section-renderer:has(ytd-statement-banner-renderer),'+
// 2024/2025: new ad slot types
'ytd-reel-shelf-renderer:has([is-ads]),'+
'ytd-shelf-renderer:has(ytd-in-feed-ad-layout-renderer),'+
'tp-yt-paper-dialog:has(ytd-enforcement-message-view-model),'+
// Survey / research panels that interrupt viewing
'.ytd-mealbar-promo-renderer'+
'{display:none!important;visibility:hidden!important}';
(document.head||document.documentElement).appendChild(s);
})();
var _wasInAd=false,_userMuted=false,_userRate=1,_userVolume=1,_restoreTimer=null;
function _inAd(player){
if(player&&(player.classList.contains('ad-showing')||
player.classList.contains('ad-interrupting')))return true;
if(document.querySelector('.ytp-ad-player-overlay-instream-info,.ytp-ad-persistent-progress-bar-container'))return true;
var adText=document.querySelector('.ytp-ad-text,.ytp-ad-simple-ad-badge,.ytp-ad-badge');
if(adText&&adText.offsetParent!==null)return true;
var skipBtn=document.querySelector('.ytp-ad-skip-button,.ytp-ad-skip-button-modern,.ytp-skip-ad-button,.ytp-ad-skip-button-slot,.ytp-ad-skip-button-container');
if(skipBtn&&skipBtn.offsetParent!==null)return true;
var progList=document.querySelector('.ytp-ad-progress-list');
if(progList&&progList.offsetParent!==null)return true;
return false;
}
function _getVideo(){
return document.querySelector('#movie_player video.html5-main-video')||
document.querySelector('#movie_player video')||
document.querySelector('video.html5-main-video')||
document.querySelector('video');
}
function _act(){
try{
// 1. Click any visible skip button first — cleanest outcome, no seek needed
var skipSel='.ytp-ad-skip-button-modern,.ytp-skip-ad-button,.ytp-ad-skip-button,'+
'.ytp-ad-skip-button-slot .ytp-button,button.ytp-ad-skip-button-modern,'+
'.ytp-ad-skip-button-container button,.ytp-ad-skip-button-slot button';
var skipBtns=document.querySelectorAll(skipSel);
for(var si=0;si<skipBtns.length;si++){
var sb=skipBtns[si];
if(sb&&sb.offsetParent!==null&&!sb.hidden&&sb.offsetWidth>0){
sb.click();
setTimeout(_act,300);
return;
}
}
var player=document.querySelector('#movie_player,.html5-video-player');
var video=_getVideo();
var inAd=_inAd(player);
if(inAd&&video&&video.readyState>0){
if(!_wasInAd){
_userMuted=video.muted;
_userRate=(video.playbackRate>2)?1:video.playbackRate;
_userVolume=video.volume;
}
_wasInAd=true;
if(!video.muted)video.muted=true;
// Seek to near end first (fastest path), then also boost speed
if(video.duration&&isFinite(video.duration)&&video.duration>0.1){
try{video.currentTime=Math.max(0,video.duration-0.05);}catch(e){}
}
try{if(video.playbackRate<16)video.playbackRate=16;}catch(e){}
if(video.paused&&video.readyState>=2)try{video.play();}catch(e){}
} else if(_wasInAd&&!inAd){
_wasInAd=false;
if(_restoreTimer)clearTimeout(_restoreTimer);
_restoreTimer=setTimeout(function(){
var v=_getVideo();
if(v){
try{v.playbackRate=_userRate||1;}catch(e){}
try{v.muted=_userMuted;}catch(e){}
try{if(!_userMuted)v.volume=_userVolume;}catch(e){}
if(v.paused&&v.readyState>=2)try{v.play();}catch(e){}
}
_restoreTimer=null;
},400);
}
// 2. Close overlay ads
document.querySelectorAll(
'.ytp-ad-overlay-close-button,.ytp-ad-overlay-slot-close-button,'+
'.ytp-suggested-action-badge-expanded-close-button,'+
'.ytp-ad-overlay-close-container,.ytp-ad-skip-button-slot button'
).forEach(function(el){try{if(el.offsetParent!==null)el.click();}catch(e){}});
// 3. Dismiss bot-check / ad-block enforcement dialogs
// YouTube uses multiple dialog implementations — cover all known ones
var enforceSel=
'ytd-enforcement-message-view-model,'+
'ytd-enforcement-message-view-model tp-yt-paper-button,'+
'tp-yt-paper-dialog ytd-enforcement-message-view-model,'+
'ytd-watch-modal tp-yt-paper-dialog,'+
'ytd-modal-with-title-and-button-renderer';
var dlg=document.querySelector(enforceSel);
if(dlg&&dlg.offsetParent!==null){
// Try the most common dismiss button patterns
var dismissSel=
'button[aria-label*="without" i],button[aria-label*="Continue" i],'+
'button[aria-label*="Watch" i],button[aria-label*="Dismiss" i],'+
'button[aria-label*="Got it" i],button[aria-label*="OK" i],'+
'.yt-spec-button-shape-next--filled,.yt-spec-button-shape-next--tonal,'+
'tp-yt-paper-button[dialog-confirm]';
var watchBtn=dlg.querySelector(dismissSel);
if(!watchBtn){
var btns=dlg.querySelectorAll('button,.yt-spec-button-shape-next,tp-yt-paper-button');
if(btns.length)watchBtn=btns[btns.length-1];
}
if(watchBtn)try{watchBtn.click();}catch(e){}
}
}catch(e){}
}
// ── MutationObserver — fires on ad-relevant class/node changes only ──────────
var _obs=new MutationObserver(function(muts){
var act=false;
for(var i=0;i<muts.length;i++){
var t=muts[i].target;
if(muts[i].type==='attributes'&&t&&t.classList&&
(t.classList.contains('ad-showing')||t.classList.contains('ad-interrupting'))){act=true;break;}
var added=muts[i].addedNodes;
for(var j=0;j<added.length;j++){
var n=added[j];
if(n.nodeType!==1)continue;
var c=(n.className||'')+(n.id||'');
if(c.indexOf('ytp-ad')!==-1||c.indexOf('ad-showing')!==-1||c.indexOf('ad-interrupt')!==-1||
(n.tagName&&(n.tagName==='YTD-AD-SLOT-RENDERER'||n.tagName==='YTD-IN-FEED-AD-LAYOUT-RENDERER'))){act=true;break;}
}
if(act)break;
}
if(act)_act();
});
window[_nsKey].obs=_obs;
// ── Polling fallback — active only when an ad is detected ───────────────────
var _iv=setInterval(function(){
var p=document.querySelector('#movie_player,.html5-video-player');
if(_inAd(p)||_wasInAd)_act();
},500);
window[_nsKey].iv=_iv;
function _attach(){
var p=document.querySelector('#movie_player,.html5-video-player,ytd-player,ytd-app');
if(p){
_obs.observe(p,{childList:true,subtree:true,attributes:true,attributeFilter:['class']});
window[_nsKey].wObs=null;
} else {
var _w=new MutationObserver(function(){
var p2=document.querySelector('#movie_player,.html5-video-player,ytd-player');
if(p2){
_w.disconnect();
window[_nsKey].wObs=null;
_obs.observe(p2,{childList:true,subtree:true,attributes:true,attributeFilter:['class']});
}
});
_w.observe(document.documentElement,{childList:true,subtree:false});
window[_nsKey].wObs=_w;
}
}
_attach();
_act();
setTimeout(_act,300);
setTimeout(_act,900);
setTimeout(_act,2200);
setTimeout(_act,4500);
})();`;
// ── YouTube ad-tracking URLs to block at network level ────────────────────────
// Only ad analytics/impression/delivery/tracking endpoints are blocked.
// Video content endpoints (videoplayback, manifest, etc.) are never touched.
// NOTE: imasdk.googleapis.com is intentionally NOT blocked — it initialises the
// ad framework; blocking it makes YouTube's player hang on a black screen and
// prevents all video playback.
const YT_AD_BLOCK_PATTERNS = [
// YouTube ad stats and tracking
/youtube\.com\/api\/stats\/ads/i,
/youtube\.com\/pagead\//i,
/youtube\.com\/ptracking/i,
/youtube\.com\/pagead\/paralleladview/i,
/youtube\.com\/pagead\/adview/i,
/youtube\.com\/pagead\/viewthroughconversion/i,
/youtube\.com\/get_video_info\?.*adformat/i,
// Ad-tagged QoE/watchtime pings only
/youtube\.com\/api\/stats\/qoe\?.*adformat/i,
/youtube\.com\/api\/stats\/watchtime\?.*(?:ad|ads_id)/i,
// DoubleClick / Google Ads delivery
/googleads\.g\.doubleclick\.net/i,
/pubads\.g\.doubleclick\.net/i,
/securepubads\.g\.doubleclick\.net/i,
/static\.doubleclick\.net/i,
/ad\.doubleclick\.net/i,
/googleadservices\.com/i,
/googlesyndication\.com/i,
/s0\.2mdn\.net/i,
/googlevideo\.com\/api\/stats\/ads/i,
// 2024/2025 ad logging
/jnn-pa\.googleapis\.com\/v1:logAdEvent/i,
/jnn-pa\.googleapis\.com\/v1\/events:recordImpression/i,
/jnn-pa\.googleapis\.com\/v1\/events:reportAdEvent/i,
// Google ad measurement beacons
/google\.com\/pagead\/adview/i,
/google\.com\/pagead\/conversion/i,
/google\.com\/pagead\/1p-user-list/i,
/google\.com\/ccm\/collect/i,
];
// ── Google / auth UA fix ────────────────────────────────────────────────────
// Injected via executeJavaScript (runs in the page's MAIN world, NOT preload
// isolated world, and ignores CSP entirely). This overrides navigator.userAgentData
// so Google's sign-in never sees the real "Electron" brand, which triggers the
// "This browser may not be secure" error at the password step.
// Must run on EVERY navigation to google.com / accounts.google.com etc.
//
// KEY ANTI-DETECTION: Google's scripts use Function.prototype.toString() and
// Object.getOwnPropertyDescriptor() to detect if properties have been overridden
// with custom getters. We wrap both so our overrides appear native.
const GOOGLE_UA_FIX = `(function(){
if(window._rbGoogleFix)return;
window._rbGoogleFix=true;
try{
/* ── Step 0: Function.prototype.toString stealth ────────────────────────
Google checks if getters are native by calling fn.toString() and looking
for "[native code]". We wrap toString so all our custom getters report
as native. This MUST happen before any _def calls. */
var _fakeNatives=new WeakSet();
var _origFnToStr=Function.prototype.toString;
var _toStrProxy=function toString(){
if(_fakeNatives.has(this))return'function '+((this.name||'')||'')+'() { [native code] }';
return _origFnToStr.call(this);
};
_fakeNatives.add(_toStrProxy);
Function.prototype.toString=_toStrProxy;
/* Also protect Function.prototype.call/apply/bind.toString from revealing overrides */
try{Object.defineProperty(Function.prototype,'toString',{writable:true,configurable:true});}catch(e){}
/* ── Step 0b: Object.getOwnPropertyDescriptor stealth ──────────────────
Google also uses Object.getOwnPropertyDescriptor(navigator, prop) to
inspect property descriptors and detect custom getters. We intercept
queries for key navigator properties and return native-looking descriptors. */
var _origGOPD=Object.getOwnPropertyDescriptor;
var _spoofedProps=new Map(); /* target -> Set of prop names */
Object.getOwnPropertyDescriptor=function(obj,prop){
var s=_spoofedProps.get(obj);
if(s&&s.has(prop)){
/* Return descriptor on Navigator.prototype instead — looks like the native one */
var d=_origGOPD.call(Object,Object.getPrototypeOf(obj)||obj,prop);
if(d)return d;
}
return _origGOPD.call(Object,obj,prop);
};
_fakeNatives.add(Object.getOwnPropertyDescriptor);
var _UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36';
var _br=[{brand:'Not_A Brand',version:'8'},{brand:'Chromium',version:'142'},{brand:'Google Chrome',version:'142'}];
var _fvl=[{brand:'Not_A Brand',version:'8.0.0.0'},{brand:'Chromium',version:'142.0.7504.61'},{brand:'Google Chrome',version:'142.0.7504.61'}];
var _aud={
brands:_br, mobile:false, platform:'Windows',
getHighEntropyValues:function getHighEntropyValues(hints){
return Promise.resolve({architecture:'x86',bitness:'64',brands:_br,
fullVersionList:_fvl,mobile:false,model:'',
platform:'Windows',platformVersion:'10.0.0',uaFullVersion:'142.0.7504.61',
wow64:false});
},
toJSON:function toJSON(){return {brands:_br,mobile:false,platform:'Windows'};}
};
_fakeNatives.add(_aud.getHighEntropyValues);
_fakeNatives.add(_aud.toJSON);
function _def(t,p,v){
try{
var g=function(){return v;};
_fakeNatives.add(g);
Object.defineProperty(t,p,{get:g,configurable:true});
/* Track overridden props so GOPD can spoof them */
if(!_spoofedProps.has(t))_spoofedProps.set(t,new Set());
_spoofedProps.get(t).add(p);
}catch(e){}
}
_def(navigator,'userAgentData',_aud);
_def(navigator,'webdriver',false);
_def(navigator,'userAgent',_UA);
_def(navigator,'appVersion','5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36');
_def(navigator,'vendor','Google Inc.');
_def(navigator,'platform','Win32');
_def(navigator,'language','en-US');
_def(navigator,'languages',Object.freeze(['en-US','en']));
_def(navigator,'hardwareConcurrency',8);
_def(navigator,'pdfViewerEnabled',true);
_def(navigator,'cookieEnabled',true);
_def(navigator,'onLine',true);
_def(navigator,'maxTouchPoints',0);
_def(navigator,'appCodeName','Mozilla');
_def(navigator,'appName','Netscape');
_def(navigator,'product','Gecko');
_def(navigator,'productSub','20030107');
/* Plugins — Chrome always has PDF viewers; empty plugins is a strong signal */
try{
var _fp={name:'PDF Viewer',description:'Portable Document Format',filename:'internal-pdf-viewer',length:0};
var _fp2={name:'Chrome PDF Viewer',description:'Portable Document Format',filename:'internal-pdf-viewer',length:0};
var _fp3={name:'Chromium PDF Viewer',description:'Portable Document Format',filename:'internal-pdf-viewer',length:0};